import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { useState } from 'react';
import { Loading } from '@/components/Loading';
import { Car, Plus, Edit2, Trash2, CheckCircle, XCircle, Wrench } from 'lucide-react';

interface Vehicle {
  id: string;
  name: string;
  type: string;
  licensePlate: string | null;
  seatCapacity: number;
  status: string;
  currentDriver: {
    id: string;
    name: string;
  } | null;
  events: any[];
  notes: string | null;
  createdAt: string;
}

const VEHICLE_TYPES = [
  { value: 'VAN', label: 'Van (7-15 seats)' },
  { value: 'SUV', label: 'SUV (5-8 seats)' },
  { value: 'SEDAN', label: 'Sedan (4-5 seats)' },
  { value: 'BUS', label: 'Bus (15+ seats)' },
  { value: 'GOLF_CART', label: 'Golf Cart (2-6 seats)' },
  { value: 'TRUCK', label: 'Truck' },
];

const VEHICLE_STATUS = [
  { value: 'AVAILABLE', label: 'Available', color: 'green' },
  { value: 'IN_USE', label: 'In Use', color: 'blue' },
  { value: 'MAINTENANCE', label: 'Maintenance', color: 'orange' },
  { value: 'RESERVED', label: 'Reserved', color: 'yellow' },
];

export function VehicleList() {
  const queryClient = useQueryClient();
  const [showForm, setShowForm] = useState(false);
  const [editingVehicle, setEditingVehicle] = useState<Vehicle | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    type: 'VAN' as string,
    licensePlate: '',
    seatCapacity: 8,
    status: 'AVAILABLE' as string,
    notes: '',
  });

  const { data: vehicles, isLoading } = useQuery<Vehicle[]>({
    queryKey: ['vehicles'],
    queryFn: async () => {
      const { data } = await api.get('/vehicles');
      return data;
    },
  });

  const createMutation = useMutation({
    mutationFn: async (vehicleData: any) => {
      await api.post('/vehicles', vehicleData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.success('Vehicle created successfully');
      resetForm();
    },
    onError: (error: any) => {
      console.error('[VEHICLES] Failed to create vehicle:', error);
      toast.error(error.response?.data?.message || 'Failed to create vehicle');
    },
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: any }) => {
      await api.patch(`/vehicles/${id}`, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.success('Vehicle updated successfully');
      resetForm();
    },
    onError: (error: any) => {
      console.error('[VEHICLES] Failed to update vehicle:', error);
      toast.error(error.response?.data?.message || 'Failed to update vehicle');
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      await api.delete(`/vehicles/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['vehicles'] });
      toast.success('Vehicle deleted successfully');
    },
    onError: (error: any) => {
      console.error('[VEHICLES] Failed to delete vehicle:', error);
      toast.error(error.response?.data?.message || 'Failed to delete vehicle');
    },
  });

  const resetForm = () => {
    setFormData({
      name: '',
      type: 'VAN',
      licensePlate: '',
      seatCapacity: 8,
      status: 'AVAILABLE',
      notes: '',
    });
    setEditingVehicle(null);
    setShowForm(false);
  };

  const handleEdit = (vehicle: Vehicle) => {
    setEditingVehicle(vehicle);
    setFormData({
      name: vehicle.name,
      type: vehicle.type,
      licensePlate: vehicle.licensePlate || '',
      seatCapacity: vehicle.seatCapacity,
      status: vehicle.status,
      notes: vehicle.notes || '',
    });
    setShowForm(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const vehicleData = {
      ...formData,
      licensePlate: formData.licensePlate || null,
      notes: formData.notes || null,
    };

    if (editingVehicle) {
      updateMutation.mutate({ id: editingVehicle.id, data: vehicleData });
    } else {
      createMutation.mutate(vehicleData);
    }
  };

  const handleDelete = (id: string, name: string) => {
    if (confirm(`Are you sure you want to delete ${name}?`)) {
      deleteMutation.mutate(id);
    }
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = VEHICLE_STATUS.find((s) => s.value === status);
    const colorClasses = {
      green: 'bg-green-100 text-green-800',
      blue: 'bg-blue-100 text-blue-800',
      orange: 'bg-orange-100 text-orange-800',
      yellow: 'bg-yellow-100 text-yellow-800',
    };

    return (
      <span className={`px-2 py-1 rounded text-xs font-medium ${colorClasses[statusConfig?.color as keyof typeof colorClasses] || 'bg-gray-100 text-gray-800'}`}>
        {statusConfig?.label || status}
      </span>
    );
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'AVAILABLE':
        return <CheckCircle className="h-4 w-4 text-green-600" />;
      case 'MAINTENANCE':
        return <Wrench className="h-4 w-4 text-orange-600" />;
      case 'IN_USE':
        return <Car className="h-4 w-4 text-blue-600" />;
      default:
        return <XCircle className="h-4 w-4 text-gray-600" />;
    }
  };

  if (isLoading) {
    return <Loading message="Loading vehicles..." />;
  }

  const availableVehicles = vehicles?.filter((v) => v.status === 'AVAILABLE') || [];
  const inUseVehicles = vehicles?.filter((v) => v.status === 'IN_USE') || [];
  const maintenanceVehicles = vehicles?.filter((v) => v.status === 'MAINTENANCE') || [];

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-foreground">Vehicle Management</h1>
        <button
          onClick={() => setShowForm(!showForm)}
          className="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-5 w-5 mr-2" />
          {showForm ? 'Cancel' : 'Add Vehicle'}
        </button>
      </div>

      {/* Stats Summary */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div className="bg-card border border-border p-4 rounded-lg shadow-soft">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Total Vehicles</p>
              <p className="text-2xl font-bold text-foreground">{vehicles?.length || 0}</p>
            </div>
            <Car className="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        <div className="bg-card border border-border p-4 rounded-lg shadow-soft">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Available</p>
              <p className="text-2xl font-bold text-green-600 dark:text-green-500">{availableVehicles.length}</p>
            </div>
            <CheckCircle className="h-8 w-8 text-green-500 dark:text-green-600" />
          </div>
        </div>
        <div className="bg-card border border-border p-4 rounded-lg shadow-soft">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">In Use</p>
              <p className="text-2xl font-bold text-blue-600 dark:text-blue-500">{inUseVehicles.length}</p>
            </div>
            <Car className="h-8 w-8 text-blue-500 dark:text-blue-600" />
          </div>
        </div>
        <div className="bg-card border border-border p-4 rounded-lg shadow-soft">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Maintenance</p>
              <p className="text-2xl font-bold text-orange-600 dark:text-orange-500">{maintenanceVehicles.length}</p>
            </div>
            <Wrench className="h-8 w-8 text-orange-500 dark:text-orange-600" />
          </div>
        </div>
      </div>

      {/* Add/Edit Form */}
      {showForm && (
        <div className="bg-card border border-border p-6 rounded-lg shadow-medium mb-6">
          <h2 className="text-xl font-semibold text-foreground mb-4">
            {editingVehicle ? 'Edit Vehicle' : 'Add New Vehicle'}
          </h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Vehicle Name *
                </label>
                <input
                  type="text"
                  required
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="e.g., Blue Van, Suburban #3"
                  className="w-full px-3 py-2 border border-input rounded-lg focus:ring-primary focus:border-primary bg-background text-foreground transition-colors"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Vehicle Type *
                </label>
                <select
                  required
                  value={formData.type}
                  onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                  className="w-full px-3 py-2 border border-input rounded-lg focus:ring-primary focus:border-primary bg-background text-foreground transition-colors"
                >
                  {VEHICLE_TYPES.map((type) => (
                    <option key={type.value} value={type.value}>
                      {type.label}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  License Plate
                </label>
                <input
                  type="text"
                  value={formData.licensePlate}
                  onChange={(e) => setFormData({ ...formData, licensePlate: e.target.value })}
                  placeholder="ABC-1234"
                  className="w-full px-3 py-2 border border-input rounded-lg focus:ring-primary focus:border-primary bg-background text-foreground transition-colors"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Seat Capacity *
                </label>
                <input
                  type="number"
                  required
                  min="1"
                  max="60"
                  value={formData.seatCapacity}
                  onChange={(e) => setFormData({ ...formData, seatCapacity: parseInt(e.target.value) })}
                  className="w-full px-3 py-2 border border-input rounded-lg focus:ring-primary focus:border-primary bg-background text-foreground transition-colors"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Status *
                </label>
                <select
                  required
                  value={formData.status}
                  onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                  className="w-full px-3 py-2 border border-input rounded-lg focus:ring-primary focus:border-primary bg-background text-foreground transition-colors"
                >
                  {VEHICLE_STATUS.map((status) => (
                    <option key={status.value} value={status.value}>
                      {status.label}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Notes
                </label>
                <input
                  type="text"
                  value={formData.notes}
                  onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                  placeholder="Optional notes"
                  className="w-full px-3 py-2 border border-input rounded-lg focus:ring-primary focus:border-primary bg-background text-foreground transition-colors"
                />
              </div>
            </div>
            <div className="flex gap-2">
              <button
                type="submit"
                disabled={createMutation.isPending || updateMutation.isPending}
                className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50 transition-colors"
              >
                {editingVehicle ? 'Update Vehicle' : 'Create Vehicle'}
              </button>
              <button
                type="button"
                onClick={resetForm}
                className="px-4 py-2 bg-muted text-foreground rounded-lg hover:bg-muted/80 transition-colors"
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Vehicle List */}
      <div className="bg-card border border-border shadow-medium rounded-lg overflow-hidden">
        <table className="min-w-full divide-y divide-border">
          <thead className="bg-muted/30">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Vehicle
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Type
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                License Plate
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Seats
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Status
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Current Driver
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Upcoming Trips
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="bg-card divide-y divide-border">
            {vehicles?.map((vehicle) => (
              <tr key={vehicle.id} className="hover:bg-accent transition-colors">
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    {getStatusIcon(vehicle.status)}
                    <span className="ml-2 text-sm font-medium text-foreground">
                      {vehicle.name}
                    </span>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vehicle.type.replace('_', ' ')}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vehicle.licensePlate || '-'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vehicle.seatCapacity}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  {getStatusBadge(vehicle.status)}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vehicle.currentDriver?.name || '-'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                  {vehicle.events?.length || 0}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm">
                  <div className="flex gap-2">
                    <button
                      onClick={() => handleEdit(vehicle)}
                      className="text-blue-600 hover:text-blue-800 dark:text-blue-500 dark:hover:text-blue-400 transition-colors"
                      title="Edit vehicle"
                    >
                      <Edit2 className="h-4 w-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(vehicle.id, vehicle.name)}
                      className="text-red-600 hover:text-red-800 dark:text-red-500 dark:hover:text-red-400 transition-colors"
                      title="Delete vehicle"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
