import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  ArrowLeft,
  Truck,
  User,
  Calendar,
  Clock,
  Wrench,
  Package,
  AlertCircle,
  CheckCircle2,
  Play,
  Pause,
  FileText,
  Edit2,
  Loader2,
  DollarSign,
} from 'lucide-react';
import { serviceOrdersApi } from '../services/api/serviceOrders';
import type { ServiceOrder, ServiceOrderItem } from '../services/api/serviceOrders';
import type { ServiceOrderStatus } from '../types';

const STATUS_CONFIG: Record<ServiceOrderStatus, { label: string; color: string; bgColor: string }> = {
  received: { label: 'Recibido', color: 'text-blue-700', bgColor: 'bg-blue-100' },
  diagnosing: { label: 'Diagnosticando', color: 'text-purple-700', bgColor: 'bg-purple-100' },
  quoted: { label: 'Cotizado', color: 'text-yellow-700', bgColor: 'bg-yellow-100' },
  approved: { label: 'Aprobado', color: 'text-green-700', bgColor: 'bg-green-100' },
  in_repair: { label: 'En Reparacion', color: 'text-orange-700', bgColor: 'bg-orange-100' },
  waiting_parts: { label: 'Esperando Partes', color: 'text-red-700', bgColor: 'bg-red-100' },
  ready: { label: 'Listo', color: 'text-emerald-700', bgColor: 'bg-emerald-100' },
  delivered: { label: 'Entregado', color: 'text-gray-700', bgColor: 'bg-gray-100' },
  cancelled: { label: 'Cancelado', color: 'text-gray-500', bgColor: 'bg-gray-100' },
};

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

// Status transitions
const STATUS_ACTIONS: Record<ServiceOrderStatus, { next: ServiceOrderStatus; label: string; icon: typeof Play }[]> = {
  received: [
    { next: 'diagnosing', label: 'Iniciar Diagnostico', icon: Play },
    { next: 'in_repair', label: 'Iniciar Reparacion', icon: Wrench },
  ],
  diagnosing: [
    { next: 'quoted', label: 'Crear Cotizacion', icon: FileText },
  ],
  quoted: [
    { next: 'approved', label: 'Aprobar', icon: CheckCircle2 },
  ],
  approved: [
    { next: 'in_repair', label: 'Iniciar Reparacion', icon: Wrench },
  ],
  in_repair: [
    { next: 'waiting_parts', label: 'Esperando Partes', icon: Pause },
    { next: 'ready', label: 'Marcar Listo', icon: CheckCircle2 },
  ],
  waiting_parts: [
    { next: 'in_repair', label: 'Continuar Reparacion', icon: Play },
  ],
  ready: [
    { next: 'delivered', label: 'Entregar', icon: Truck },
  ],
  delivered: [],
  cancelled: [],
};

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

  // Fetch order details
  const { data: orderData, isLoading, error } = useQuery({
    queryKey: ['service-order', id],
    queryFn: () => serviceOrdersApi.getById(id!),
    enabled: !!id,
  });

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

  // Status change mutation
  const statusMutation = useMutation({
    mutationFn: ({ status, notes }: { status: ServiceOrderStatus; notes?: string }) =>
      serviceOrdersApi.changeStatus(id!, status, notes),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['service-order', id] });
      queryClient.invalidateQueries({ queryKey: ['service-orders'] });
    },
  });

  const order: ServiceOrder | undefined = orderData?.data;
  const items: ServiceOrderItem[] = itemsData?.data || [];

  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 || !order) {
    return (
      <div className="flex h-64 flex-col items-center justify-center text-gray-500">
        <AlertCircle className="mb-2 h-8 w-8" />
        <p>Orden no encontrada</p>
        <Link to="/orders" className="mt-2 text-sm text-diesel-600 hover:text-diesel-700">
          Volver a ordenes
        </Link>
      </div>
    );
  }

  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;
  const actions = STATUS_ACTIONS[order.status as ServiceOrderStatus] || [];

  const laborItems = items.filter(i => i.item_type === 'service');
  const partItems = items.filter(i => i.item_type === 'part');

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

        {/* Status Actions */}
        {actions.length > 0 && (
          <div className="flex gap-2">
            {actions.map((action) => {
              const Icon = action.icon;
              return (
                <button
                  key={action.next}
                  onClick={() => statusMutation.mutate({ status: action.next })}
                  disabled={statusMutation.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 disabled:opacity-50"
                >
                  {statusMutation.isPending ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Icon className="h-4 w-4" />
                  )}
                  {action.label}
                </button>
              );
            })}
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Main Content */}
        <div className="space-y-6 lg:col-span-2">
          {/* Customer & Vehicle */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
              {/* Customer */}
              <div>
                <h3 className="mb-3 flex items-center gap-2 text-sm font-medium text-gray-500">
                  <User className="h-4 w-4" />
                  Cliente
                </h3>
                <p className="text-lg font-semibold text-gray-900">{order.customer_name}</p>
              </div>

              {/* Vehicle */}
              <div>
                <h3 className="mb-3 flex items-center gap-2 text-sm font-medium text-gray-500">
                  <Truck className="h-4 w-4" />
                  Vehiculo
                </h3>
                <p className="text-lg font-semibold text-gray-900">{order.vehicle_info}</p>
              </div>
            </div>
          </div>

          {/* Symptoms */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h3 className="mb-3 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <AlertCircle className="h-5 w-5 text-diesel-600" />
              Sintomas Reportados
            </h3>
            <p className="text-gray-700 whitespace-pre-wrap">
              {order.symptoms || 'Sin sintomas registrados'}
            </p>
          </div>

          {/* Items */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="flex items-center gap-2 text-lg font-semibold text-gray-900">
                <Package className="h-5 w-5 text-diesel-600" />
                Trabajos y Refacciones
              </h3>
              <button className="flex items-center gap-1 text-sm text-diesel-600 hover:text-diesel-700">
                <Edit2 className="h-4 w-4" />
                Editar
              </button>
            </div>

            {items.length === 0 ? (
              <p className="text-gray-500 text-center py-8">No hay items agregados</p>
            ) : (
              <div className="space-y-6">
                {/* Labor */}
                {laborItems.length > 0 && (
                  <div>
                    <h4 className="mb-2 flex items-center gap-2 text-sm font-medium text-gray-500">
                      <Wrench className="h-4 w-4" />
                      Mano de Obra
                    </h4>
                    <div className="divide-y divide-gray-100">
                      {laborItems.map((item) => (
                        <div key={item.id} className="flex items-center justify-between py-3">
                          <div>
                            <p className="font-medium text-gray-900">{item.description}</p>
                            {item.actual_hours && (
                              <p className="text-sm text-gray-500">{item.actual_hours} hrs</p>
                            )}
                          </div>
                          <p className="font-medium text-gray-900">
                            ${item.subtotal.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Parts */}
                {partItems.length > 0 && (
                  <div>
                    <h4 className="mb-2 flex items-center gap-2 text-sm font-medium text-gray-500">
                      <Package className="h-4 w-4" />
                      Refacciones
                    </h4>
                    <div className="divide-y divide-gray-100">
                      {partItems.map((item) => (
                        <div key={item.id} className="flex items-center justify-between py-3">
                          <div>
                            <p className="font-medium text-gray-900">{item.description}</p>
                            <p className="text-sm text-gray-500">
                              {item.quantity} x ${item.unit_price.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                            </p>
                          </div>
                          <p className="font-medium text-gray-900">
                            ${item.subtotal.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Notes */}
          {order.notes && (
            <div className="rounded-xl border border-gray-200 bg-white p-6">
              <h3 className="mb-3 text-lg font-semibold text-gray-900">Notas Internas</h3>
              <p className="text-gray-700 whitespace-pre-wrap">{order.notes}</p>
            </div>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Info Card */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h3 className="mb-4 text-lg font-semibold text-gray-900">Informacion</h3>

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-gray-500">Prioridad</span>
                <span className={`font-medium ${priorityConfig.color}`}>{priorityConfig.label}</span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-gray-500">Mecanico</span>
                <span className="font-medium text-gray-900">
                  {order.mechanic_name || 'Sin asignar'}
                </span>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-gray-500">Bahia</span>
                <span className="font-medium text-gray-900">
                  {order.bay_name || 'Sin asignar'}
                </span>
              </div>

              {order.promised_at && (
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-1 text-gray-500">
                    <Calendar className="h-4 w-4" />
                    Prometido
                  </span>
                  <span className="font-medium text-gray-900">
                    {new Date(order.promised_at).toLocaleDateString('es-MX', {
                      day: 'numeric',
                      month: 'short',
                    })}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Totals */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h3 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <DollarSign className="h-5 w-5 text-diesel-600" />
              Totales
            </h3>

            <div className="space-y-3">
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-500">Mano de Obra</span>
                <span className="text-gray-900">
                  ${order.labor_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>

              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-500">Refacciones</span>
                <span className="text-gray-900">
                  ${order.parts_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>

              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-500">IVA</span>
                <span className="text-gray-900">
                  ${order.tax.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>

              <div className="border-t border-gray-200 pt-3">
                <div className="flex items-center justify-between">
                  <span className="font-semibold text-gray-900">Total</span>
                  <span className="text-xl font-bold text-diesel-600">
                    ${order.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Timeline placeholder */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <h3 className="mb-4 flex items-center gap-2 text-lg font-semibold text-gray-900">
              <Clock className="h-5 w-5 text-diesel-600" />
              Historial
            </h3>
            <div className="space-y-3 text-sm text-gray-500">
              <div className="flex items-center gap-2">
                <div className="h-2 w-2 rounded-full bg-diesel-500" />
                <span>Orden creada</span>
                <span className="ml-auto">
                  {new Date(order.created_at).toLocaleDateString('es-MX', {
                    day: 'numeric',
                    month: 'short',
                  })}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
