import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery } from '@tanstack/react-query';
import {
  ArrowLeft,
  Stethoscope,
  Truck,
  Search,
  Cpu,
  Gauge,
  Cog,
  Loader2,
  Plus,
  Trash2,
  CheckCircle2,
  XCircle,
  AlertTriangle,
} from 'lucide-react';
import { diagnosticsApi } from '../services/api/diagnostics';
import { vehiclesApi } from '../services/api/vehicles';
import type { DiagnosticResult } from '../services/api/diagnostics';
import type { DiagnosticType, Vehicle } from '../types';

const diagnosticSchema = z.object({
  vehicle_id: z.string().min(1, 'Seleccione un vehiculo'),
  order_id: z.string().optional(),
  diagnostic_type: z.enum(['obd_scanner', 'injector_bench', 'pump_bench', 'measurements']),
  equipment: z.string().optional(),
  summary: z.string().optional(),
});

type DiagnosticFormData = z.infer<typeof diagnosticSchema>;

interface DiagnosticItemForm {
  component: string;
  test_name: string;
  value: string;
  unit: string;
  min_value: string;
  max_value: string;
  result: DiagnosticResult;
  notes: string;
}

const DIAGNOSTIC_TYPES: { value: DiagnosticType; label: string; description: string; icon: typeof Cpu }[] = [
  { value: 'obd_scanner', label: 'Scanner OBD', description: 'Lectura de codigos de falla', icon: Cpu },
  { value: 'injector_bench', label: 'Banco Inyectores', description: 'Prueba de inyectores diesel', icon: Gauge },
  { value: 'pump_bench', label: 'Banco Bomba', description: 'Prueba de bomba de inyeccion', icon: Cog },
  { value: 'measurements', label: 'Mediciones', description: 'Mediciones electricas y mecanicas', icon: Stethoscope },
];

const RESULT_OPTIONS: { value: DiagnosticResult; label: string; color: string; icon: typeof CheckCircle2 }[] = [
  { value: 'pass', label: 'Aprobado', color: 'bg-green-100 text-green-700 border-green-300', icon: CheckCircle2 },
  { value: 'fail', label: 'Fallo', color: 'bg-red-100 text-red-700 border-red-300', icon: XCircle },
  { value: 'needs_attention', label: 'Atencion', color: 'bg-yellow-100 text-yellow-700 border-yellow-300', icon: AlertTriangle },
];

const EMPTY_ITEM: DiagnosticItemForm = {
  component: '',
  test_name: '',
  value: '',
  unit: '',
  min_value: '',
  max_value: '',
  result: 'pass',
  notes: '',
};

export function DiagnosticsNewPage() {
  const navigate = useNavigate();
  const [vehicleSearch, setVehicleSearch] = useState('');
  const [showVehicleSearch, setShowVehicleSearch] = useState(false);
  const [selectedVehicle, setSelectedVehicle] = useState<{ id: string; info: string } | null>(null);
  const [items, setItems] = useState<DiagnosticItemForm[]>([{ ...EMPTY_ITEM }]);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<DiagnosticFormData>({
    resolver: zodResolver(diagnosticSchema),
    defaultValues: {
      diagnostic_type: 'obd_scanner',
    },
  });

  const selectedType = watch('diagnostic_type');

  // Search vehicles
  const { data: vehiclesData, isLoading: searchingVehicles } = useQuery({
    queryKey: ['vehicles-search', vehicleSearch],
    queryFn: () => vehiclesApi.list({ search: vehicleSearch, pageSize: 10 }),
    enabled: vehicleSearch.length >= 2,
  });

  const vehicles = vehiclesData?.data?.data || [];

  // Create mutation
  const createMutation = useMutation({
    mutationFn: async (data: DiagnosticFormData) => {
      // First create the diagnostic
      const response = await diagnosticsApi.create({
        vehicle_id: data.vehicle_id,
        order_id: data.order_id,
        diagnostic_type: data.diagnostic_type,
        equipment: data.equipment,
        summary: data.summary,
      });

      const diagnosticId = response.data?.id;

      // Then add items if we have them
      if (diagnosticId && items.some(item => item.component && item.test_name)) {
        for (const item of items) {
          if (item.component && item.test_name) {
            await diagnosticsApi.addItem(diagnosticId, {
              component: item.component,
              test_name: item.test_name,
              value: item.value,
              unit: item.unit || null,
              min_value: item.min_value ? parseFloat(item.min_value) : null,
              max_value: item.max_value ? parseFloat(item.max_value) : null,
              result: item.result,
              notes: item.notes || null,
            });
          }
        }
      }

      return response;
    },
    onSuccess: (response) => {
      const id = response.data?.id;
      if (id) {
        navigate(`/diagnostics/${id}`);
      } else {
        navigate('/diagnostics');
      }
    },
  });

  const onSubmit = (data: DiagnosticFormData) => {
    createMutation.mutate(data);
  };

  const selectVehicle = (vehicle: Vehicle) => {
    setSelectedVehicle({
      id: vehicle.id,
      info: `${vehicle.licensePlate} - ${vehicle.make} ${vehicle.model} ${vehicle.year}`,
    });
    setValue('vehicle_id', vehicle.id);
    setShowVehicleSearch(false);
    setVehicleSearch('');
  };

  const addItem = () => {
    setItems([...items, { ...EMPTY_ITEM }]);
  };

  const removeItem = (index: number) => {
    if (items.length > 1) {
      setItems(items.filter((_, i) => i !== index));
    }
  };

  const updateItem = (index: number, field: keyof DiagnosticItemForm, value: string) => {
    const newItems = [...items];
    newItems[index] = { ...newItems[index], [field]: value };
    setItems(newItems);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Link
          to="/diagnostics"
          className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600"
        >
          <ArrowLeft className="h-5 w-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Nuevo Diagnostico</h1>
          <p className="text-sm text-gray-500">Registre pruebas y analisis del vehiculo</p>
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Main Content */}
        <div className="space-y-6 lg:col-span-2">
          {/* Vehicle Selection */}
          <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>

            {selectedVehicle ? (
              <div className="flex items-center justify-between rounded-lg border border-diesel-200 bg-diesel-50 p-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-diesel-100">
                    <Truck className="h-5 w-5 text-diesel-600" />
                  </div>
                  <span className="font-medium text-gray-900">{selectedVehicle.info}</span>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    setSelectedVehicle(null);
                    setValue('vehicle_id', '');
                  }}
                  className="text-sm text-diesel-600 hover:text-diesel-700"
                >
                  Cambiar
                </button>
              </div>
            ) : (
              <div className="relative">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                  <input
                    type="text"
                    value={vehicleSearch}
                    onChange={(e) => {
                      setVehicleSearch(e.target.value);
                      setShowVehicleSearch(true);
                    }}
                    onFocus={() => setShowVehicleSearch(true)}
                    placeholder="Buscar por placas, marca o modelo..."
                    className="w-full rounded-lg border border-gray-300 py-3 pl-10 pr-4 focus:border-diesel-500 focus:outline-none"
                  />
                </div>

                {showVehicleSearch && vehicleSearch.length >= 2 && (
                  <div className="absolute z-10 mt-1 w-full rounded-lg border border-gray-200 bg-white shadow-lg">
                    {searchingVehicles ? (
                      <div className="flex items-center justify-center p-4">
                        <Loader2 className="h-5 w-5 animate-spin text-diesel-600" />
                      </div>
                    ) : vehicles.length > 0 ? (
                      <div className="max-h-60 overflow-y-auto p-2">
                        {vehicles.map((vehicle) => (
                          <button
                            key={vehicle.id}
                            type="button"
                            onClick={() => selectVehicle(vehicle)}
                            className="flex w-full items-center gap-3 rounded-lg p-3 text-left hover:bg-gray-50"
                          >
                            <Truck className="h-5 w-5 text-gray-400" />
                            <div>
                              <p className="font-medium text-gray-900">
                                {vehicle.licensePlate} - {vehicle.make} {vehicle.model}
                              </p>
                              <p className="text-sm text-gray-500">
                                {vehicle.year} | {vehicle.vehicleType}
                              </p>
                            </div>
                          </button>
                        ))}
                      </div>
                    ) : (
                      <div className="p-4 text-center text-sm text-gray-500">
                        No se encontraron vehiculos
                      </div>
                    )}
                  </div>
                )}

                {errors.vehicle_id && (
                  <p className="mt-1 text-sm text-red-600">{errors.vehicle_id.message}</p>
                )}
              </div>
            )}
          </div>

          {/* Diagnostic Type */}
          <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">
              <Stethoscope className="h-5 w-5 text-diesel-600" />
              Tipo de Diagnostico
            </h2>

            <div className="grid grid-cols-2 gap-3">
              {DIAGNOSTIC_TYPES.map((type) => {
                const Icon = type.icon;
                const isSelected = selectedType === type.value;
                return (
                  <label
                    key={type.value}
                    className={`flex cursor-pointer items-start gap-3 rounded-lg border p-4 transition-colors ${
                      isSelected
                        ? 'border-diesel-500 bg-diesel-50'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <input
                      type="radio"
                      {...register('diagnostic_type')}
                      value={type.value}
                      className="sr-only"
                    />
                    <Icon className={`h-5 w-5 ${isSelected ? 'text-diesel-600' : 'text-gray-400'}`} />
                    <div>
                      <p className={`font-medium ${isSelected ? 'text-diesel-700' : 'text-gray-700'}`}>
                        {type.label}
                      </p>
                      <p className="text-sm text-gray-500">{type.description}</p>
                    </div>
                  </label>
                );
              })}
            </div>

            <div className="mt-4">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">
                Equipo Utilizado (opcional)
              </label>
              <input
                {...register('equipment')}
                placeholder="Ej: Scanner LAUNCH X431, Banco Asnu GDI..."
                className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-diesel-500 focus:outline-none"
              />
            </div>
          </div>

          {/* Diagnostic Items */}
          <div className="rounded-xl border border-gray-200 bg-white p-6">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-900">Pruebas Realizadas</h2>
              <button
                type="button"
                onClick={addItem}
                className="flex items-center gap-1 text-sm text-diesel-600 hover:text-diesel-700"
              >
                <Plus className="h-4 w-4" />
                Agregar Prueba
              </button>
            </div>

            <div className="space-y-4">
              {items.map((item, index) => (
                <div key={index} className="rounded-lg border border-gray-200 p-4">
                  <div className="mb-3 flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-700">Prueba {index + 1}</span>
                    {items.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeItem(index)}
                        className="text-red-500 hover:text-red-600"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    )}
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="mb-1 block text-xs font-medium text-gray-600">Componente</label>
                      <input
                        value={item.component}
                        onChange={(e) => updateItem(index, 'component', e.target.value)}
                        placeholder="Ej: Inyector 1"
                        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 block text-xs font-medium text-gray-600">Prueba</label>
                      <input
                        value={item.test_name}
                        onChange={(e) => updateItem(index, 'test_name', e.target.value)}
                        placeholder="Ej: Caudal Retorno"
                        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 block text-xs font-medium text-gray-600">Valor</label>
                      <input
                        value={item.value}
                        onChange={(e) => updateItem(index, 'value', e.target.value)}
                        placeholder="Ej: 85"
                        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 block text-xs font-medium text-gray-600">Unidad</label>
                      <input
                        value={item.unit}
                        onChange={(e) => updateItem(index, 'unit', e.target.value)}
                        placeholder="Ej: ml/min"
                        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 block text-xs font-medium text-gray-600">Valor Min</label>
                      <input
                        type="number"
                        value={item.min_value}
                        onChange={(e) => updateItem(index, 'min_value', e.target.value)}
                        placeholder="Ej: 70"
                        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 block text-xs font-medium text-gray-600">Valor Max</label>
                      <input
                        type="number"
                        value={item.max_value}
                        onChange={(e) => updateItem(index, 'max_value', e.target.value)}
                        placeholder="Ej: 100"
                        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="col-span-2">
                      <label className="mb-1 block text-xs font-medium text-gray-600">Resultado</label>
                      <div className="flex gap-2">
                        {RESULT_OPTIONS.map((option) => {
                          const Icon = option.icon;
                          return (
                            <button
                              key={option.value}
                              type="button"
                              onClick={() => updateItem(index, 'result', option.value)}
                              className={`flex flex-1 items-center justify-center gap-1 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
                                item.result === option.value
                                  ? option.color
                                  : 'border-gray-200 text-gray-500 hover:border-gray-300'
                              }`}
                            >
                              <Icon className="h-4 w-4" />
                              {option.label}
                            </button>
                          );
                        })}
                      </div>
                    </div>
                    <div className="col-span-2">
                      <label className="mb-1 block text-xs font-medium text-gray-600">Notas</label>
                      <input
                        value={item.notes}
                        onChange={(e) => updateItem(index, 'notes', e.target.value)}
                        placeholder="Observaciones adicionales..."
                        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>
              ))}
            </div>
          </div>
        </div>

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

            <div className="space-y-4">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-gray-700">
                  Observaciones Generales
                </label>
                <textarea
                  {...register('summary')}
                  rows={4}
                  placeholder="Describa hallazgos, recomendaciones..."
                  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">
                  Orden de Servicio (opcional)
                </label>
                <input
                  {...register('order_id')}
                  placeholder="ID de orden relacionada"
                  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>

          {/* Actions */}
          <div className="space-y-3">
            <button
              type="submit"
              disabled={createMutation.isPending}
              className="flex w-full items-center justify-center gap-2 rounded-lg bg-diesel-600 px-4 py-3 font-medium text-white hover:bg-diesel-700 disabled:opacity-50"
            >
              {createMutation.isPending ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Guardando...
                </>
              ) : (
                <>
                  <Stethoscope className="h-4 w-4" />
                  Guardar Diagnostico
                </>
              )}
            </button>

            <Link
              to="/diagnostics"
              className="block w-full rounded-lg border border-gray-300 px-4 py-3 text-center font-medium text-gray-700 hover:bg-gray-50"
            >
              Cancelar
            </Link>
          </div>

          {createMutation.error && (
            <div className="rounded-lg bg-red-50 p-4 text-sm text-red-600">
              Error al crear el diagnostico. Intente nuevamente.
            </div>
          )}
        </div>
      </form>
    </div>
  );
}
