import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  FileText,
  Plus,
  Search,
  Clock,
  CheckCircle2,
  XCircle,
  Send,
  Eye,
  ArrowRight,
  Loader2,
  AlertCircle,
  Calendar,
} from 'lucide-react';
import { quotesApi } from '../services/api/quotes';
import type { Quote, QuoteFilters } from '../services/api/quotes';
import type { QuoteStatus } from '../types';

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

export function QuotesPage() {
  const queryClient = useQueryClient();
  const [filters, setFilters] = useState<QuoteFilters>({ page: 1, pageSize: 20 });
  const [searchTerm, setSearchTerm] = useState('');

  // Fetch quotes
  const { data, isLoading, error } = useQuery({
    queryKey: ['quotes', filters],
    queryFn: () => quotesApi.list(filters),
  });

  // Convert to order mutation
  const convertMutation = useMutation({
    mutationFn: (quoteId: string) => quotesApi.convertToOrder(quoteId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['quotes'] });
    },
  });

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

  const quotes = data?.data?.data || [];

  const handleSearch = () => {
    setFilters({ ...filters, search: searchTerm, page: 1 });
  };

  const handleStatusFilter = (status: QuoteStatus | undefined) => {
    setFilters({ ...filters, status, page: 1 });
  };

  const isExpired = (validUntil: string) => {
    return new Date(validUntil) < new Date();
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Cotizaciones</h1>
          <p className="text-sm text-gray-500">Gestiona las cotizaciones para clientes</p>
        </div>
        <Link
          to="/quotes/new"
          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"
        >
          <Plus className="h-4 w-4" />
          Nueva Cotizacion
        </Link>
      </div>

      {/* Status summary */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-7">
        {(Object.keys(STATUS_CONFIG) as QuoteStatus[]).map((status) => {
          const config = STATUS_CONFIG[status];
          const Icon = config.icon;
          return (
            <button
              key={status}
              onClick={() => handleStatusFilter(filters.status === status ? undefined : status)}
              className={`rounded-lg border p-3 text-left transition-colors ${
                filters.status === status
                  ? 'border-diesel-500 bg-diesel-50'
                  : 'border-gray-200 bg-white hover:border-gray-300'
              }`}
            >
              <div className="flex items-center gap-2">
                <Icon className={`h-4 w-4 ${filters.status === status ? 'text-diesel-600' : 'text-gray-400'}`} />
                <span className="text-xs font-medium text-gray-600">{config.label}</span>
              </div>
            </button>
          );
        })}
      </div>

      {/* Search & Filters */}
      <div className="flex flex-wrap items-center gap-4">
        <div className="flex flex-1 items-center gap-2">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              placeholder="Buscar por numero, cliente..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
              className="w-full rounded-lg border border-gray-300 py-2 pl-10 pr-4 text-sm focus:border-diesel-500 focus:outline-none focus:ring-1 focus:ring-diesel-500"
            />
          </div>
          <button
            onClick={handleSearch}
            className="rounded-lg bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200"
          >
            Buscar
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
        {isLoading ? (
          <div className="flex h-64 items-center justify-center">
            <Loader2 className="h-8 w-8 animate-spin text-diesel-600" />
          </div>
        ) : error ? (
          <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 cotizaciones</p>
          </div>
        ) : quotes.length === 0 ? (
          <div className="flex h-64 flex-col items-center justify-center text-gray-500">
            <FileText className="mb-2 h-8 w-8" />
            <p>No hay cotizaciones</p>
            <Link
              to="/quotes/new"
              className="mt-2 text-sm text-diesel-600 hover:text-diesel-700"
            >
              Crear primera cotizacion
            </Link>
          </div>
        ) : (
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                  Cotizacion
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                  Cliente / Vehiculo
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                  Estado
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                  Vigencia
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">
                  Total
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">
                  Acciones
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {quotes.map((quote: Quote) => {
                const statusConfig = STATUS_CONFIG[quote.status as QuoteStatus] || STATUS_CONFIG.draft;
                const expired = isExpired(quote.valid_until);

                return (
                  <tr key={quote.id} className="hover:bg-gray-50">
                    <td className="whitespace-nowrap px-6 py-4">
                      <Link
                        to={`/quotes/${quote.id}`}
                        className="font-medium text-diesel-600 hover:text-diesel-700"
                      >
                        {quote.quote_number}
                      </Link>
                      <p className="text-xs text-gray-500">
                        {new Date(quote.created_at).toLocaleDateString('es-MX')}
                      </p>
                    </td>
                    <td className="px-6 py-4">
                      <div>
                        <p className="font-medium text-gray-900">{quote.customer_name}</p>
                        <p className="text-sm text-gray-500">{quote.vehicle_info}</p>
                      </div>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4">
                      <span className={`inline-flex rounded-full px-2 py-1 text-xs font-medium ${statusConfig.color}`}>
                        {statusConfig.label}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm">
                      <div className={`flex items-center gap-1 ${expired && quote.status !== 'converted' ? 'text-red-500' : 'text-gray-500'}`}>
                        <Calendar className="h-4 w-4" />
                        {new Date(quote.valid_until).toLocaleDateString('es-MX', {
                          day: '2-digit',
                          month: 'short',
                        })}
                        {expired && quote.status !== 'converted' && (
                          <span className="ml-1 text-xs">(vencida)</span>
                        )}
                      </div>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-right font-medium text-gray-900">
                      ${quote.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-right">
                      <div className="flex justify-end gap-2">
                        {quote.status === 'draft' && (
                          <button
                            onClick={() => sendMutation.mutate(quote.id)}
                            disabled={sendMutation.isPending}
                            className="rounded p-1.5 text-blue-600 hover:bg-blue-50"
                            title="Enviar"
                          >
                            <Send className="h-4 w-4" />
                          </button>
                        )}
                        {quote.status === 'approved' && (
                          <button
                            onClick={() => convertMutation.mutate(quote.id)}
                            disabled={convertMutation.isPending}
                            className="rounded p-1.5 text-green-600 hover:bg-green-50"
                            title="Convertir a Orden"
                          >
                            <ArrowRight className="h-4 w-4" />
                          </button>
                        )}
                        <Link
                          to={`/quotes/${quote.id}`}
                          className="rounded p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
                        >
                          <Eye className="h-4 w-4" />
                        </Link>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}

        {/* Pagination */}
        {data?.data && quotes.length > 0 && (
          <div className="flex items-center justify-between border-t border-gray-200 bg-gray-50 px-6 py-3">
            <div className="text-sm text-gray-500">
              Pagina {data.data.page} de {data.data.totalPages}
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setFilters({ ...filters, page: (filters.page || 1) - 1 })}
                disabled={(filters.page || 1) <= 1}
                className="rounded-lg border border-gray-300 px-3 py-1 text-sm disabled:opacity-50"
              >
                Anterior
              </button>
              <button
                onClick={() => setFilters({ ...filters, page: (filters.page || 1) + 1 })}
                disabled={(filters.page || 1) >= data.data.totalPages}
                className="rounded-lg border border-gray-300 px-3 py-1 text-sm disabled:opacity-50"
              >
                Siguiente
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
