import { Link, useParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  ArrowLeft,
  FileText,
  Truck,
  User,
  Calendar,
  DollarSign,
  Loader2,
  AlertCircle,
  Printer,
  Mail,
  MessageCircle,
  CheckCircle2,
  XCircle,
  Clock,
  ArrowRightCircle,
  Wrench,
  Package,
  Eye,
} from 'lucide-react';
import { quotesApi } from '../services/api/quotes';
import type { Quote, QuoteItem } from '../services/api/quotes';
import type { QuoteStatus } from '../types';

const STATUS_CONFIG: Record<QuoteStatus, { label: string; color: string; bgColor: string; icon: typeof Clock }> = {
  draft: { label: 'Borrador', color: 'text-gray-700', bgColor: 'bg-gray-100', icon: FileText },
  sent: { label: 'Enviada', color: 'text-blue-700', bgColor: 'bg-blue-100', icon: Mail },
  viewed: { label: 'Vista', color: 'text-purple-700', bgColor: 'bg-purple-100', icon: Eye },
  approved: { label: 'Aprobada', color: 'text-green-700', bgColor: 'bg-green-100', icon: CheckCircle2 },
  rejected: { label: 'Rechazada', color: 'text-red-700', bgColor: 'bg-red-100', icon: XCircle },
  expired: { label: 'Expirada', color: 'text-yellow-700', bgColor: 'bg-yellow-100', icon: Clock },
  converted: { label: 'Convertida', color: 'text-emerald-700', bgColor: 'bg-emerald-100', icon: ArrowRightCircle },
};

export function QuoteDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  // Fetch quote
  const { data: quoteData, isLoading, error } = useQuery({
    queryKey: ['quote', id],
    queryFn: () => quotesApi.getById(id!),
    enabled: !!id,
  });

  const quote: Quote | undefined = quoteData?.data;

  // Fetch quote items
  const { data: itemsData } = useQuery({
    queryKey: ['quote-items', id],
    queryFn: () => quotesApi.getItems(id!),
    enabled: !!id,
  });

  const items: QuoteItem[] = itemsData?.data || [];

  // Send quote mutation
  const sendMutation = useMutation({
    mutationFn: () => quotesApi.send(id!),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['quote', id] });
      queryClient.invalidateQueries({ queryKey: ['quotes'] });
    },
  });

  // Change status mutation
  const statusMutation = useMutation({
    mutationFn: (status: QuoteStatus) => quotesApi.changeStatus(id!, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['quote', id] });
      queryClient.invalidateQueries({ queryKey: ['quotes'] });
    },
  });

  // Convert to order mutation
  const convertMutation = useMutation({
    mutationFn: () => quotesApi.convertToOrder(id!),
    onSuccess: (response) => {
      queryClient.invalidateQueries({ queryKey: ['quote', id] });
      queryClient.invalidateQueries({ queryKey: ['quotes'] });
      queryClient.invalidateQueries({ queryKey: ['service-orders'] });
      // Navigate to the new order
      const orderId = response.data?.orderId;
      if (orderId) {
        navigate(`/orders/${orderId}`);
      }
    },
  });

  const handlePrint = () => {
    window.print();
  };

  if (isLoading) {
    return (
      <div className="flex h-64 items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-diesel-600" />
      </div>
    );
  }

  if (error || !quote) {
    return (
      <div className="flex h-64 flex-col items-center justify-center text-gray-500">
        <AlertCircle className="mb-2 h-8 w-8" />
        <p>Error al cargar la cotizacion</p>
        <Link to="/quotes" className="mt-2 text-diesel-600 hover:text-diesel-700">
          Volver a cotizaciones
        </Link>
      </div>
    );
  }

  const statusConfig = STATUS_CONFIG[quote.status as QuoteStatus] || STATUS_CONFIG.draft;
  const StatusIcon = statusConfig.icon;

  // Calculate totals from items
  const laborItems = items.filter(i => i.item_type === 'service');
  const partItems = items.filter(i => i.item_type === 'part');
  const subtotal = items.reduce((sum, item) => sum + item.subtotal, 0);

  // Check if quote is expired
  const isExpired = quote.valid_until && new Date(quote.valid_until) < new Date();
  const canSend = quote.status === 'draft';
  const canApprove = (quote.status === 'sent' || quote.status === 'viewed') && !isExpired;
  const canConvert = quote.status === 'approved';

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            to="/quotes"
            className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
          >
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-2xl font-bold text-gray-900">{quote.quote_number}</h1>
              <span className={`inline-flex items-center gap-1 rounded-full px-3 py-1 text-sm font-medium ${statusConfig.bgColor} ${statusConfig.color}`}>
                <StatusIcon className="h-4 w-4" />
                {statusConfig.label}
              </span>
            </div>
            <p className="text-sm text-gray-500">
              Creada el {new Date(quote.created_at).toLocaleDateString('es-MX', {
                day: '2-digit',
                month: 'long',
                year: 'numeric',
              })}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={handlePrint}
            className="flex items-center gap-2 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
          >
            <Printer className="h-4 w-4" />
            Imprimir
          </button>
          {canSend && (
            <button
              onClick={() => sendMutation.mutate()}
              disabled={sendMutation.isPending}
              className="flex items-center gap-2 rounded-lg border border-blue-300 bg-blue-50 px-4 py-2 text-sm font-medium text-blue-700 hover:bg-blue-100"
            >
              {sendMutation.isPending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Mail className="h-4 w-4" />
              )}
              Enviar
            </button>
          )}
          {canApprove && (
            <>
              <button
                onClick={() => statusMutation.mutate('approved')}
                disabled={statusMutation.isPending}
                className="flex items-center gap-2 rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700"
              >
                <CheckCircle2 className="h-4 w-4" />
                Aprobar
              </button>
              <button
                onClick={() => statusMutation.mutate('rejected')}
                disabled={statusMutation.isPending}
                className="flex items-center gap-2 rounded-lg border border-red-300 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-50"
              >
                <XCircle className="h-4 w-4" />
                Rechazar
              </button>
            </>
          )}
          {canConvert && (
            <button
              onClick={() => convertMutation.mutate()}
              disabled={convertMutation.isPending}
              className="flex items-center gap-2 rounded-lg bg-diesel-600 px-4 py-2 text-sm font-medium text-white hover:bg-diesel-700"
            >
              {convertMutation.isPending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <ArrowRightCircle className="h-4 w-4" />
              )}
              Convertir a Orden
            </button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Main Content - Quote Preview */}
        <div className="lg:col-span-2">
          <div className="rounded-xl border border-gray-200 bg-white p-8 print:border-0 print:p-0">
            {/* Quote Header */}
            <div className="mb-8 border-b border-gray-200 pb-6">
              <div className="flex items-start justify-between">
                <div>
                  <h2 className="text-2xl font-bold text-gray-900">COTIZACION</h2>
                  <p className="text-lg font-semibold text-diesel-600">{quote.quote_number}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500">Fecha de Emision</p>
                  <p className="font-medium text-gray-900">
                    {new Date(quote.created_at).toLocaleDateString('es-MX')}
                  </p>
                  <p className="mt-2 text-sm text-gray-500">Valida Hasta</p>
                  <p className={`font-medium ${isExpired ? 'text-red-600' : 'text-gray-900'}`}>
                    {quote.valid_until
                      ? new Date(quote.valid_until).toLocaleDateString('es-MX')
                      : 'Sin fecha limite'}
                  </p>
                </div>
              </div>
            </div>

            {/* Customer & Vehicle Info */}
            <div className="mb-8 grid grid-cols-2 gap-6">
              <div>
                <h3 className="mb-2 text-sm font-semibold uppercase text-gray-500">Cliente</h3>
                <p className="font-medium text-gray-900">{quote.customer_name}</p>
              </div>
              <div>
                <h3 className="mb-2 text-sm font-semibold uppercase text-gray-500">Vehiculo</h3>
                <p className="font-medium text-gray-900">{quote.vehicle_info}</p>
              </div>
            </div>

            {/* Items Table */}
            <div className="mb-8">
              {/* Labor Items */}
              {laborItems.length > 0 && (
                <div className="mb-6">
                  <h3 className="mb-3 flex items-center gap-2 text-sm font-semibold uppercase text-gray-500">
                    <Wrench className="h-4 w-4" />
                    Mano de Obra
                  </h3>
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-gray-200">
                        <th className="pb-2 text-left text-sm font-medium text-gray-500">Descripcion</th>
                        <th className="pb-2 text-right text-sm font-medium text-gray-500">Cant</th>
                        <th className="pb-2 text-right text-sm font-medium text-gray-500">Precio</th>
                        <th className="pb-2 text-right text-sm font-medium text-gray-500">Total</th>
                      </tr>
                    </thead>
                    <tbody>
                      {laborItems.map((item) => (
                        <tr key={item.id} className="border-b border-gray-100">
                          <td className="py-3">
                            <p className="font-medium text-gray-900">{item.description}</p>
                          </td>
                          <td className="py-3 text-right text-gray-700">{item.quantity}</td>
                          <td className="py-3 text-right text-gray-700">
                            ${item.unit_price.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                          </td>
                          <td className="py-3 text-right font-medium text-gray-900">
                            ${item.subtotal.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {/* Part Items */}
              {partItems.length > 0 && (
                <div>
                  <h3 className="mb-3 flex items-center gap-2 text-sm font-semibold uppercase text-gray-500">
                    <Package className="h-4 w-4" />
                    Refacciones
                  </h3>
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-gray-200">
                        <th className="pb-2 text-left text-sm font-medium text-gray-500">Descripcion</th>
                        <th className="pb-2 text-right text-sm font-medium text-gray-500">Cant</th>
                        <th className="pb-2 text-right text-sm font-medium text-gray-500">Precio</th>
                        <th className="pb-2 text-right text-sm font-medium text-gray-500">Total</th>
                      </tr>
                    </thead>
                    <tbody>
                      {partItems.map((item) => (
                        <tr key={item.id} className="border-b border-gray-100">
                          <td className="py-3">
                            <p className="font-medium text-gray-900">{item.description}</p>
                          </td>
                          <td className="py-3 text-right text-gray-700">{item.quantity}</td>
                          <td className="py-3 text-right text-gray-700">
                            ${item.unit_price.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                          </td>
                          <td className="py-3 text-right font-medium text-gray-900">
                            ${item.subtotal.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            {/* Totals */}
            <div className="border-t border-gray-200 pt-6">
              <div className="flex justify-end">
                <div className="w-64 space-y-2">
                  <div className="flex justify-between text-gray-600">
                    <span>Mano de Obra</span>
                    <span>${quote.labor_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}</span>
                  </div>
                  <div className="flex justify-between text-gray-600">
                    <span>Refacciones</span>
                    <span>${quote.parts_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}</span>
                  </div>
                  {quote.discount_amount > 0 && (
                    <div className="flex justify-between text-green-600">
                      <span>Descuento</span>
                      <span>-${quote.discount_amount.toLocaleString('es-MX', { minimumFractionDigits: 2 })}</span>
                    </div>
                  )}
                  <div className="flex justify-between text-gray-600">
                    <span>Subtotal</span>
                    <span>${subtotal.toLocaleString('es-MX', { minimumFractionDigits: 2 })}</span>
                  </div>
                  <div className="flex justify-between text-gray-600">
                    <span>IVA</span>
                    <span>${quote.tax.toLocaleString('es-MX', { minimumFractionDigits: 2 })}</span>
                  </div>
                  <div className="flex justify-between border-t border-gray-200 pt-2 text-xl font-bold text-gray-900">
                    <span>Total</span>
                    <span>${quote.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Notes */}
            {quote.notes && (
              <div className="mt-8 rounded-lg bg-gray-50 p-4">
                <h3 className="mb-2 text-sm font-semibold text-gray-700">Notas</h3>
                <p className="text-sm text-gray-600">{quote.notes}</p>
              </div>
            )}

            {/* Terms */}
            <div className="mt-8 border-t border-gray-200 pt-6 text-xs text-gray-500">
              <p>* Precios expresados en Pesos Mexicanos (MXN)</p>
              <p>* Los precios estan sujetos a disponibilidad de refacciones</p>
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Customer Info */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <User className="h-5 w-5 text-diesel-600" />
              Cliente
            </h2>
            <div className="space-y-3">
              <p className="font-medium text-gray-900">{quote.customer_name}</p>
              {quote.customer_id && (
                <Link
                  to={`/customers?id=${quote.customer_id}`}
                  className="text-sm text-diesel-600 hover:text-diesel-700"
                >
                  Ver perfil del cliente
                </Link>
              )}
            </div>
          </div>

          {/* Vehicle Info */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Truck className="h-5 w-5 text-diesel-600" />
              Vehiculo
            </h2>
            <p className="font-medium text-gray-900">{quote.vehicle_info}</p>
          </div>

          {/* Timeline / Actions */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Calendar className="h-5 w-5 text-diesel-600" />
              Fechas
            </h2>
            <div className="space-y-3 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-500">Creada</span>
                <span className="text-gray-900">
                  {new Date(quote.created_at).toLocaleDateString('es-MX')}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Valida hasta</span>
                <span className={isExpired ? 'text-red-600' : 'text-gray-900'}>
                  {quote.valid_until
                    ? new Date(quote.valid_until).toLocaleDateString('es-MX')
                    : '-'}
                </span>
              </div>
              {quote.updated_at && (
                <div className="flex justify-between">
                  <span className="text-gray-500">Actualizada</span>
                  <span className="text-gray-900">
                    {new Date(quote.updated_at).toLocaleDateString('es-MX')}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Summary */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <DollarSign className="h-5 w-5 text-diesel-600" />
              Resumen
            </h2>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-500">Servicios</span>
                <span className="text-gray-900">{laborItems.length}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Refacciones</span>
                <span className="text-gray-900">{partItems.length}</span>
              </div>
              <div className="flex justify-between border-t border-gray-200 pt-2 font-medium">
                <span className="text-gray-700">Total</span>
                <span className="text-diesel-600">
                  ${quote.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>
            </div>
          </div>

          {/* Quick Actions */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h2 className="mb-4 text-lg font-semibold text-gray-900">Acciones Rapidas</h2>
            <div className="space-y-2">
              <button className="flex w-full items-center gap-2 rounded-lg border border-gray-200 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50">
                <MessageCircle className="h-4 w-4" />
                Enviar por WhatsApp
              </button>
              <button className="flex w-full items-center gap-2 rounded-lg border border-gray-200 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50">
                <Mail className="h-4 w-4" />
                Enviar por Email
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
