import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import {
  Wrench,
  Plus,
  Search,
  Filter,
  Clock,
  AlertCircle,
  CheckCircle2,
  Truck,
  Calendar,
  LayoutGrid,
} from 'lucide-react';
import { serviceOrdersApi } from '../services/api/serviceOrders';
import type { ServiceOrder, ServiceOrderFilters } from '../services/api/serviceOrders';
import type { ServiceOrderStatus } from '../types';

const STATUS_CONFIG: Record<ServiceOrderStatus, { label: string; color: string; icon: typeof Clock }> = {
  received: { label: 'Recibido', color: 'bg-blue-100 text-blue-800', icon: Clock },
  diagnosing: { label: 'Diagnosticando', color: 'bg-purple-100 text-purple-800', icon: AlertCircle },
  quoted: { label: 'Cotizado', color: 'bg-yellow-100 text-yellow-800', icon: Clock },
  approved: { label: 'Aprobado', color: 'bg-green-100 text-green-800', icon: CheckCircle2 },
  in_repair: { label: 'En Reparación', color: 'bg-orange-100 text-orange-800', icon: Wrench },
  waiting_parts: { label: 'Esperando Partes', color: 'bg-red-100 text-red-800', icon: Clock },
  ready: { label: 'Listo', color: 'bg-emerald-100 text-emerald-800', icon: CheckCircle2 },
  delivered: { label: 'Entregado', color: 'bg-gray-100 text-gray-800', icon: Truck },
  cancelled: { label: 'Cancelado', color: 'bg-gray-100 text-gray-500', icon: AlertCircle },
};

const PRIORITY_CONFIG = {
  low: { label: 'Baja', color: 'text-gray-500' },
  medium: { label: 'Media', color: 'text-blue-500' },
  high: { label: 'Alta', color: 'text-orange-500' },
  urgent: { label: 'Urgente', color: 'text-red-500' },
};

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

  const { data, isLoading, error } = useQuery({
    queryKey: ['service-orders', filters],
    queryFn: () => serviceOrdersApi.list(filters),
  });

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

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Órdenes de Servicio</h1>
          <p className="text-sm text-gray-500">Gestiona las órdenes de trabajo del taller</p>
        </div>
        <div className="flex items-center gap-2">
          <Link
            to="/orders/kanban"
            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"
          >
            <LayoutGrid className="h-4 w-4" />
            Vista Kanban
          </Link>
          <Link
            to="/orders/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 Orden
          </Link>
        </div>
      </div>

      {/* Status summary cards */}
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6">
        {(['received', 'in_repair', 'waiting_parts', 'ready', 'delivered'] as ServiceOrderStatus[]).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-4 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-500">{config.label}</span>
                </div>
                <p className="mt-1 text-2xl font-bold text-gray-900">-</p>
              </button>
            );
          }
        )}
      </div>

      {/* 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 número de orden, cliente o vehículo..."
              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 className="flex items-center gap-2">
          <Filter className="h-4 w-4 text-gray-400" />
          <select
            value={filters.status || ''}
            onChange={(e) => handleStatusFilter((e.target.value as ServiceOrderStatus) || undefined)}
            className="rounded-lg border border-gray-300 py-2 pl-3 pr-8 text-sm focus:border-diesel-500 focus:outline-none"
          >
            <option value="">Todos los estados</option>
            {Object.entries(STATUS_CONFIG).map(([key, config]) => (
              <option key={key} value={key}>
                {config.label}
              </option>
            ))}
          </select>

          <select
            value={filters.priority || ''}
            onChange={(e) =>
              setFilters({ ...filters, priority: e.target.value || undefined, page: 1 })
            }
            className="rounded-lg border border-gray-300 py-2 pl-3 pr-8 text-sm focus:border-diesel-500 focus:outline-none"
          >
            <option value="">Todas las prioridades</option>
            {Object.entries(PRIORITY_CONFIG).map(([key, config]) => (
              <option key={key} value={key}>
                {config.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Orders Table */}
      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
        {isLoading ? (
          <div className="flex h-64 items-center justify-center">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-diesel-600 border-t-transparent" />
          </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 órdenes</p>
            <p className="text-sm">Verifica que el servidor esté activo</p>
          </div>
        ) : !data?.data?.data?.length ? (
          <div className="flex h-64 flex-col items-center justify-center text-gray-500">
            <Wrench className="mb-2 h-8 w-8" />
            <p>No hay órdenes de servicio</p>
            <Link
              to="/orders/new"
              className="mt-2 text-sm text-diesel-600 hover:text-diesel-700"
            >
              Crear primera orden
            </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">
                  Orden
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                  Cliente / Vehículo
                </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">
                  Prioridad
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                  Fecha
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">
                  Total
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {data.data.data.map((order: ServiceOrder) => {
                const statusConfig = STATUS_CONFIG[order.status as ServiceOrderStatus] || STATUS_CONFIG.received;
                const priorityConfig = PRIORITY_CONFIG[order.priority as keyof typeof PRIORITY_CONFIG] || PRIORITY_CONFIG.medium;

                return (
                  <tr key={order.id} className="hover:bg-gray-50">
                    <td className="whitespace-nowrap px-6 py-4">
                      <Link
                        to={`/orders/${order.id}`}
                        className="font-medium text-diesel-600 hover:text-diesel-700"
                      >
                        {order.order_number}
                      </Link>
                    </td>
                    <td className="px-6 py-4">
                      <div>
                        <div className="font-medium text-gray-900">{order.customer_name}</div>
                        <div className="text-sm text-gray-500">{order.vehicle_info}</div>
                      </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">
                      <span className={`text-sm font-medium ${priorityConfig.color}`}>
                        {priorityConfig.label}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                      <div className="flex items-center gap-1">
                        <Calendar className="h-4 w-4" />
                        {new Date(order.received_at).toLocaleDateString('es-MX', {
                          day: '2-digit',
                          month: 'short',
                        })}
                      </div>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-right text-sm font-medium text-gray-900">
                      ${order.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}

        {/* Pagination */}
        {data?.data && data.data.data.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">
              Página {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}
                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>
  );
}
