import { useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import {
  ArrowLeft,
  Truck,
  Edit,
  Trash2,
  Save,
  X,
  Loader2,
  AlertCircle,
  Calendar,
  Gauge,
  User,
  FileText,
  Wrench,
  Clock,
  CheckCircle2,
  Settings,
  Hash,
} from 'lucide-react';
import { vehiclesApi } from '../services/api/vehicles';
import { customersApi } from '../services/api/customers';
import { serviceOrdersApi, type ServiceOrder } from '../services/api/serviceOrders';
import { ConfirmModal } from '../components/ui';
import type { Vehicle, VehicleType, VehicleStatus } from '../types';

const VEHICLE_TYPE_LABELS: Record<VehicleType, string> = {
  truck: 'Camion',
  trailer: 'Trailer',
  bus: 'Autobus',
  pickup: 'Pickup',
  other: 'Otro',
};

const VEHICLE_STATUS_CONFIG: Record<VehicleStatus, { label: string; color: string }> = {
  active: { label: 'Activo', color: 'bg-green-100 text-green-800' },
  inactive: { label: 'Inactivo', color: 'bg-gray-100 text-gray-800' },
  sold: { label: 'Vendido', color: 'bg-red-100 text-red-800' },
};

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

interface EditVehicleForm {
  licensePlate: string;
  economicNumber: string;
  make: string;
  model: string;
  year: number;
  color: string;
  vehicleType: VehicleType;
  vin: string;
  currentOdometer: number;
  notes: string;
  status: VehicleStatus;
}

export function VehicleDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [isEditing, setIsEditing] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);

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

  const vehicle: Vehicle | undefined = vehicleData?.data;

  // Fetch customer data
  const { data: customerData } = useQuery({
    queryKey: ['customer', vehicle?.customerId],
    queryFn: () => customersApi.getById(vehicle!.customerId),
    enabled: !!vehicle?.customerId,
  });

  const customer = customerData?.data;

  // Fetch service history
  const { data: historyData } = useQuery({
    queryKey: ['vehicle-history', id],
    queryFn: () => serviceOrdersApi.getHistory(id!),
    enabled: !!id,
  });

  const serviceHistory: ServiceOrder[] = historyData?.data || [];

  // Form setup
  const { register, handleSubmit, reset, formState: { isDirty } } = useForm<EditVehicleForm>();

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: (data: EditVehicleForm) => vehiclesApi.update(id!, {
      licensePlate: data.licensePlate,
      economicNumber: data.economicNumber || undefined,
      make: data.make,
      model: data.model,
      year: data.year,
      color: data.color || undefined,
      vehicleType: data.vehicleType,
      vin: data.vin || undefined,
      currentOdometer: data.currentOdometer || undefined,
      notes: data.notes || undefined,
      status: data.status,
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vehicle', id] });
      setIsEditing(false);
    },
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: () => vehiclesApi.delete(id!),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      navigate('/vehicles');
    },
  });

  const handleEdit = () => {
    if (vehicle) {
      reset({
        licensePlate: vehicle.licensePlate,
        economicNumber: vehicle.economicNumber || '',
        make: vehicle.make,
        model: vehicle.model,
        year: vehicle.year,
        color: vehicle.color || '',
        vehicleType: vehicle.vehicleType,
        vin: vehicle.vin || '',
        currentOdometer: vehicle.currentOdometer || 0,
        notes: vehicle.notes || '',
        status: vehicle.status,
      });
      setIsEditing(true);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    reset();
  };

  const onSubmit = (data: EditVehicleForm) => {
    updateMutation.mutate(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 || !vehicle) {
    return (
      <div className="flex h-64 flex-col items-center justify-center text-gray-500">
        <AlertCircle className="mb-2 h-8 w-8" />
        <p>Vehiculo no encontrado</p>
        <Link to="/vehicles" className="mt-2 text-diesel-600 hover:text-diesel-700">
          Volver a vehiculos
        </Link>
      </div>
    );
  }

  const statusConfig = VEHICLE_STATUS_CONFIG[vehicle.status];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            to="/vehicles"
            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">
                {vehicle.make} {vehicle.model} {vehicle.year}
              </h1>
              <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${statusConfig.color}`}>
                {statusConfig.label}
              </span>
            </div>
            <p className="text-sm text-gray-500">{vehicle.licensePlate}</p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {!isEditing ? (
            <>
              <button
                onClick={handleEdit}
                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"
              >
                <Edit className="h-4 w-4" />
                Editar
              </button>
              <button
                onClick={() => setShowDeleteModal(true)}
                className="flex items-center gap-2 rounded-lg border border-red-300 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50"
              >
                <Trash2 className="h-4 w-4" />
                Eliminar
              </button>
            </>
          ) : (
            <>
              <button
                onClick={handleCancel}
                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"
              >
                <X className="h-4 w-4" />
                Cancelar
              </button>
              <button
                onClick={handleSubmit(onSubmit)}
                disabled={!isDirty || updateMutation.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"
              >
                {updateMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Save className="h-4 w-4" />
                )}
                Guardar
              </button>
            </>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Vehicle Info */}
        <div className="space-y-6 lg:col-span-2">
          {/* Main Info Card */}
          <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" />
              Informacion del Vehiculo
            </h2>

            {isEditing ? (
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Placas</label>
                  <input
                    {...register('licensePlate', { required: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">No. Economico</label>
                  <input
                    {...register('economicNumber')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Marca</label>
                  <input
                    {...register('make', { required: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Modelo</label>
                  <input
                    {...register('model', { required: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Ano</label>
                  <input
                    type="number"
                    {...register('year', { required: true, valueAsNumber: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Color</label>
                  <input
                    {...register('color')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Tipo</label>
                  <select
                    {...register('vehicleType')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  >
                    {Object.entries(VEHICLE_TYPE_LABELS).map(([key, label]) => (
                      <option key={key} value={key}>{label}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Estado</label>
                  <select
                    {...register('status')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  >
                    {Object.entries(VEHICLE_STATUS_CONFIG).map(([key, config]) => (
                      <option key={key} value={key}>{config.label}</option>
                    ))}
                  </select>
                </div>
                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">VIN</label>
                  <input
                    {...register('vin')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Odometro Actual</label>
                  <input
                    type="number"
                    {...register('currentOdometer', { valueAsNumber: true })}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="mb-1.5 block text-sm font-medium text-gray-700">Notas</label>
                  <textarea
                    {...register('notes')}
                    rows={3}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
                  />
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
                <div>
                  <p className="text-xs font-medium text-gray-500">Placas</p>
                  <p className="text-sm font-medium text-gray-900">{vehicle.licensePlate}</p>
                </div>
                {vehicle.economicNumber && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">No. Economico</p>
                    <p className="text-sm font-medium text-gray-900">{vehicle.economicNumber}</p>
                  </div>
                )}
                <div>
                  <p className="text-xs font-medium text-gray-500">Tipo</p>
                  <p className="text-sm font-medium text-gray-900">{VEHICLE_TYPE_LABELS[vehicle.vehicleType]}</p>
                </div>
                {vehicle.color && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Color</p>
                    <p className="text-sm font-medium text-gray-900">{vehicle.color}</p>
                  </div>
                )}
                {vehicle.vin && (
                  <div className="col-span-2">
                    <p className="text-xs font-medium text-gray-500">VIN</p>
                    <p className="text-sm font-mono text-gray-900">{vehicle.vin}</p>
                  </div>
                )}
                {vehicle.currentOdometer && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Odometro</p>
                    <p className="text-sm font-medium text-gray-900">
                      {vehicle.currentOdometer.toLocaleString()} km
                    </p>
                  </div>
                )}
                <div>
                  <p className="text-xs font-medium text-gray-500">Registrado</p>
                  <p className="text-sm text-gray-900">
                    {new Date(vehicle.createdAt).toLocaleDateString('es-MX')}
                  </p>
                </div>
                {vehicle.notes && (
                  <div className="col-span-full">
                    <p className="text-xs font-medium text-gray-500">Notas</p>
                    <p className="text-sm text-gray-600">{vehicle.notes}</p>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Service History */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="flex items-center gap-2 text-lg font-semibold text-gray-900">
                <Wrench className="h-5 w-5 text-diesel-600" />
                Historial de Servicio
              </h2>
              <Link
                to={`/orders/new?vehicleId=${vehicle.id}`}
                className="flex items-center gap-2 rounded-lg bg-diesel-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-diesel-700"
              >
                Nueva Orden
              </Link>
            </div>

            {serviceHistory.length === 0 ? (
              <div className="flex h-32 flex-col items-center justify-center text-gray-400">
                <FileText className="mb-2 h-8 w-8" />
                <p className="text-sm">Sin historial de servicio</p>
              </div>
            ) : (
              <div className="divide-y divide-gray-100">
                {serviceHistory.map((order) => {
                  const statusConfig = ORDER_STATUS_CONFIG[order.status] || ORDER_STATUS_CONFIG.received;
                  return (
                    <Link
                      key={order.id}
                      to={`/orders/${order.id}`}
                      className="flex items-center justify-between py-3 hover:bg-gray-50 -mx-2 px-2 rounded-lg"
                    >
                      <div className="flex items-center gap-3">
                        <div className="flex h-10 w-10 items-center justify-center rounded-full bg-diesel-50">
                          <Wrench className="h-5 w-5 text-diesel-600" />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-900">{order.order_number}</p>
                          <p className="text-xs text-gray-500 line-clamp-1">{order.symptoms}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3 text-right">
                        <div>
                          <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${statusConfig.color}`}>
                            {statusConfig.label}
                          </span>
                          <p className="mt-1 text-xs text-gray-500">
                            {new Date(order.received_at).toLocaleDateString('es-MX', {
                              day: '2-digit',
                              month: 'short',
                              year: 'numeric',
                            })}
                          </p>
                        </div>
                        <p className="text-sm font-medium text-gray-900">
                          ${order.grand_total.toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                        </p>
                      </div>
                    </Link>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Owner Card */}
          <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" />
              Propietario
            </h2>

            {customer ? (
              <div className="space-y-3">
                <div>
                  <p className="text-xs font-medium text-gray-500">Cliente</p>
                  <Link
                    to={`/customers?id=${customer.id}`}
                    className="text-sm font-medium text-diesel-600 hover:text-diesel-700"
                  >
                    {customer.name}
                  </Link>
                </div>
                {customer.contact_name && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Contacto</p>
                    <p className="text-sm text-gray-900">{customer.contact_name}</p>
                  </div>
                )}
                {customer.contact_phone && (
                  <div>
                    <p className="text-xs font-medium text-gray-500">Telefono</p>
                    <p className="text-sm text-gray-900">{customer.contact_phone}</p>
                  </div>
                )}
              </div>
            ) : (
              <p className="text-sm text-gray-500">Cargando...</p>
            )}
          </div>

          {/* Quick Stats */}
          <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">
              <Settings className="h-5 w-5 text-diesel-600" />
              Resumen
            </h2>

            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="flex items-center gap-2 text-sm text-gray-500">
                  <Hash className="h-4 w-4" />
                  Total Ordenes
                </span>
                <span className="text-sm font-medium text-gray-900">{serviceHistory.length}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="flex items-center gap-2 text-sm text-gray-500">
                  <CheckCircle2 className="h-4 w-4" />
                  Completadas
                </span>
                <span className="text-sm font-medium text-gray-900">
                  {serviceHistory.filter(o => o.status === 'delivered').length}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="flex items-center gap-2 text-sm text-gray-500">
                  <Clock className="h-4 w-4" />
                  En Proceso
                </span>
                <span className="text-sm font-medium text-gray-900">
                  {serviceHistory.filter(o => !['delivered', 'cancelled'].includes(o.status)).length}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="flex items-center gap-2 text-sm text-gray-500">
                  <Gauge className="h-4 w-4" />
                  Odometro
                </span>
                <span className="text-sm font-medium text-gray-900">
                  {vehicle.currentOdometer ? `${vehicle.currentOdometer.toLocaleString()} km` : '-'}
                </span>
              </div>
              {vehicle.odometerUpdatedAt && (
                <div className="flex items-center justify-between">
                  <span className="flex items-center gap-2 text-sm text-gray-500">
                    <Calendar className="h-4 w-4" />
                    Ultima Lectura
                  </span>
                  <span className="text-sm text-gray-900">
                    {new Date(vehicle.odometerUpdatedAt).toLocaleDateString('es-MX')}
                  </span>
                </div>
              )}
            </div>

            {/* Total Spent */}
            <div className="mt-4 border-t border-gray-100 pt-4">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-gray-700">Total Invertido</span>
                <span className="text-lg font-bold text-diesel-600">
                  ${serviceHistory.reduce((sum, o) => sum + (o.status === 'delivered' ? o.grand_total : 0), 0).toLocaleString('es-MX', { minimumFractionDigits: 2 })}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      <ConfirmModal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        onConfirm={() => deleteMutation.mutate()}
        title="Eliminar Vehiculo"
        message={`¿Estas seguro de eliminar el vehiculo ${vehicle.make} ${vehicle.model} (${vehicle.licensePlate})? Esta accion no se puede deshacer.`}
        confirmText="Eliminar"
        variant="danger"
        isLoading={deleteMutation.isPending}
      />
    </div>
  );
}
