'use client'

import { useEffect, useRef, useState } from 'react'
import { Plus, Edit, Eye, Search, Upload, X } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import { apiFetch } from '@/lib/api'
import { formatCurrency } from '@rentaldrivego/types'

interface Vehicle {
  id: string
  make: string
  model: string
  year: number
  category: string
  status: 'AVAILABLE' | 'RENTED' | 'MAINTENANCE' | 'OUT_OF_SERVICE'
  dailyRate: number
  isPublished: boolean
  primaryPhoto: string | null
  licensePlate: string
}

interface AddVehicleModalProps {
  open: boolean
  onClose: () => void
  onSaved: () => void
}

const STATUS_BADGE: Record<Vehicle['status'], string> = {
  AVAILABLE: 'badge-green',
  RENTED: 'badge-blue',
  MAINTENANCE: 'badge-amber',
  OUT_OF_SERVICE: 'badge-red',
}

const PRESET_COLORS = ['White', 'Black', 'Silver', 'Gray', 'Red', 'Blue', 'Green', 'Yellow', 'Orange', 'Brown', 'Beige', 'Gold']
const PRESET_MAKES = ['Audi', 'BMW', 'Chevrolet', 'Citroën', 'Dacia', 'Fiat', 'Ford', 'Honda', 'Hyundai', 'Kia', 'Mazda', 'Mercedes-Benz', 'Nissan', 'Opel', 'Peugeot', 'Renault', 'Seat', 'Skoda', 'Suzuki', 'Toyota', 'Volkswagen', 'Volvo']
const MODELS_BY_MAKE: Record<string, string[]> = {
  'Audi':          ['A1', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'Q2', 'Q3', 'Q5', 'Q7', 'Q8', 'TT'],
  'BMW':           ['116i', '118i', '120i', '218i', '316i', '318i', '320i', '325i', 'X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7'],
  'Chevrolet':     ['Aveo', 'Captiva', 'Cruze', 'Malibu', 'Spark', 'Trax'],
  'Citroën':       ['Berlingo', 'C1', 'C3', 'C3 Aircross', 'C4', 'C4 Cactus', 'C5', 'C5 Aircross', 'Jumpy', 'SpaceTourer'],
  'Dacia':         ['Dokker', 'Duster', 'Jogger', 'Lodgy', 'Logan', 'Sandero', 'Spring'],
  'Fiat':          ['500', '500X', 'Bravo', 'Doblo', 'Ducato', 'Panda', 'Punto', 'Tipo'],
  'Ford':          ['B-Max', 'C-Max', 'EcoSport', 'Edge', 'Explorer', 'Fiesta', 'Focus', 'Fusion', 'Kuga', 'Mondeo', 'Mustang', 'Puma', 'Ranger', 'S-Max', 'Transit'],
  'Honda':         ['Accord', 'Civic', 'CR-V', 'HR-V', 'Jazz', 'Pilot'],
  'Hyundai':       ['Accent', 'Creta', 'Elantra', 'i10', 'i20', 'i30', 'ix35', 'Kona', 'Santa Fe', 'Sonata', 'Tucson'],
  'Kia':           ['Carnival', 'Ceed', 'Niro', 'Optima', 'Picanto', 'Rio', 'Sorento', 'Soul', 'Sportage', 'Stinger'],
  'Mazda':         ['2', '3', '6', 'CX-3', 'CX-5', 'CX-9', 'MX-5'],
  'Mercedes-Benz': ['A-Class', 'B-Class', 'C-Class', 'CLA', 'E-Class', 'GLA', 'GLB', 'GLC', 'GLE', 'GLS', 'S-Class', 'Sprinter', 'Vito'],
  'Nissan':        ['Juke', 'Leaf', 'Micra', 'Murano', 'Navara', 'Note', 'Pathfinder', 'Patrol', 'Pulsar', 'Qashqai', 'X-Trail'],
  'Opel':          ['Astra', 'Corsa', 'Crossland', 'Grandland', 'Insignia', 'Meriva', 'Mokka', 'Zafira'],
  'Peugeot':       ['108', '208', '2008', '3008', '308', '4008', '408', '5008', '508', 'Boxer', 'Expert', 'Partner', 'Traveller'],
  'Renault':       ['Arkana', 'Captur', 'Clio', 'Duster', 'Espace', 'Grand Scenic', 'Kadjar', 'Kangoo', 'Koleos', 'Laguna', 'Master', 'Megane', 'Scenic', 'Talisman', 'Trafic', 'Twingo', 'Zoe'],
  'Seat':          ['Arona', 'Arosa', 'Ateca', 'Ibiza', 'Leon', 'Tarraco', 'Toledo'],
  'Skoda':         ['Fabia', 'Karoq', 'Kodiaq', 'Octavia', 'Rapid', 'Scala', 'Superb', 'Yeti'],
  'Suzuki':        ['Alto', 'Baleno', 'Celerio', 'Ignis', 'Jimny', 'S-Cross', 'Swift', 'Vitara'],
  'Toyota':        ['Auris', 'Avensis', 'Aygo', 'Camry', 'Corolla', 'C-HR', 'Fortuner', 'Hilux', 'Land Cruiser', 'Prius', 'RAV4', 'Rush', 'Urban Cruiser', 'Yaris'],
  'Volkswagen':    ['Amarok', 'Arteon', 'Caddy', 'Golf', 'ID.3', 'ID.4', 'Passat', 'Polo', 'Sharan', 'T-Cross', 'T-Roc', 'Tiguan', 'Touareg', 'Touran', 'Transporter', 'Up'],
  'Volvo':         ['S60', 'S90', 'V40', 'V60', 'V90', 'XC40', 'XC60', 'XC90'],
}

function AddVehicleModal({ open, onClose, onSaved }: AddVehicleModalProps) {
  const [form, setForm] = useState({
    make: '', model: '', year: new Date().getFullYear(), category: 'ECONOMY',
    dailyRate: '', licensePlate: '', color: '', seats: 5, transmission: 'MANUAL',
    fuelType: 'GASOLINE', mileage: '',
  })
  const [colorSelect, setColorSelect] = useState('')
  const [makeSelect, setMakeSelect] = useState('')
  const [modelSelect, setModelSelect] = useState('')
  const [photoFiles, setPhotoFiles] = useState<File[]>([])
  const [photoPreviews, setPhotoPreviews] = useState<string[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handlePhotoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? [])
    if (!files.length) return
    const combined = [...photoFiles, ...files].slice(0, 10)
    setPhotoFiles(combined)
    setPhotoPreviews(combined.map((f) => URL.createObjectURL(f)))
    e.target.value = ''
  }

  const removePhoto = (index: number) => {
    URL.revokeObjectURL(photoPreviews[index])
    const files = photoFiles.filter((_, i) => i !== index)
    const previews = photoPreviews.filter((_, i) => i !== index)
    setPhotoFiles(files)
    setPhotoPreviews(previews)
  }

  const reset = () => {
    setForm({ make: '', model: '', year: new Date().getFullYear(), category: 'ECONOMY', dailyRate: '', licensePlate: '', color: '', seats: 5, transmission: 'MANUAL', fuelType: 'GASOLINE', mileage: '' })
    setColorSelect('')
    setMakeSelect('')
    setModelSelect('')
    photoPreviews.forEach((p) => URL.revokeObjectURL(p))
    setPhotoFiles([])
    setPhotoPreviews([])
    setError(null)
  }

  const handleClose = () => { reset(); onClose() }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.make)         { setError('Please select or enter a make.'); return }
    if (!form.model)        { setError('Please select or enter a model.'); return }
    if (!form.licensePlate) { setError('Please enter a license plate.'); return }
    if (!form.dailyRate || isNaN(parseFloat(form.dailyRate))) { setError('Please enter a valid daily rate.'); return }
    setLoading(true)
    setError(null)
    try {
      const vehicle = await apiFetch<{ id: string }>('/vehicles', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          dailyRate: Math.round(parseFloat(form.dailyRate) * 100),
          year: Number(form.year),
          seats: Number(form.seats),
          mileage: form.mileage ? Number(form.mileage) : undefined,
        }),
      })
      if (photoFiles.length > 0) {
        const fd = new FormData()
        photoFiles.forEach((f) => fd.append('photos', f))
        await apiFetch(`/vehicles/${vehicle.id}/photos`, { method: 'POST', body: fd })
      }
      onSaved()
      handleClose()
    } catch (err: any) {
      setError(err.message ?? 'Failed to add vehicle. Please check all fields and try again.')
    } finally {
      setLoading(false)
    }
  }

  if (!open) return null

  const presetModels = form.make && MODELS_BY_MAKE[form.make] ? MODELS_BY_MAKE[form.make] : null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={(e) => { if (e.target === e.currentTarget) handleClose() }}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 p-6 max-h-[90vh] overflow-y-auto">
        <h2 className="text-lg font-semibold text-slate-900 mb-5">Add New Vehicle</h2>
        {error && (
          <div className="px-3 py-2 mb-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">{error}</div>
        )}
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Make & Model */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Make *</label>
              <select
                className="input-field"
                value={makeSelect}
                onChange={(e) => {
                  setMakeSelect(e.target.value)
                  setModelSelect('')
                  if (e.target.value !== 'custom') setForm({ ...form, make: e.target.value, model: '' })
                  else setForm({ ...form, make: '', model: '' })
                }}
              >
                <option value="">Select make…</option>
                {PRESET_MAKES.map((m) => <option key={m} value={m}>{m}</option>)}
                <option value="custom">Other…</option>
              </select>
              {makeSelect === 'custom' && (
                <input className="input-field mt-2" placeholder="Type make…" required value={form.make} onChange={(e) => setForm({ ...form, make: e.target.value })} autoFocus />
              )}
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Model *</label>
              {!presetModels ? (
                <input className="input-field" placeholder="Model" required value={form.model} onChange={(e) => setForm({ ...form, model: e.target.value })} />
              ) : (
                <>
                  <select
                    className="input-field"
                    value={modelSelect}
                    onChange={(e) => {
                      setModelSelect(e.target.value)
                      if (e.target.value !== 'custom') setForm({ ...form, model: e.target.value })
                      else setForm({ ...form, model: '' })
                    }}
                  >
                    <option value="">Select model…</option>
                    {presetModels.map((m) => <option key={m} value={m}>{m}</option>)}
                    <option value="custom">Other…</option>
                  </select>
                  {modelSelect === 'custom' && (
                    <input className="input-field mt-2" placeholder="Type model…" required value={form.model} onChange={(e) => setForm({ ...form, model: e.target.value })} autoFocus />
                  )}
                </>
              )}
            </div>
          </div>

          {/* Year & Category */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Year *</label>
              <input type="number" className="input-field" min="1990" max={new Date().getFullYear() + 1} required value={form.year} onChange={(e) => setForm({ ...form, year: Number(e.target.value) })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Category</label>
              <select className="input-field" value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
                {['ECONOMY', 'COMPACT', 'MIDSIZE', 'FULLSIZE', 'SUV', 'LUXURY', 'VAN', 'TRUCK'].map((c) => (
                  <option key={c} value={c}>{c}</option>
                ))}
              </select>
            </div>
          </div>

          {/* Daily Rate & License Plate */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Daily Rate (MAD) *</label>
              <input type="number" className="input-field" placeholder="350.00" min="0" step="0.01" required value={form.dailyRate} onChange={(e) => setForm({ ...form, dailyRate: e.target.value })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">License Plate *</label>
              <input className="input-field" placeholder="AB-1234-CD" required value={form.licensePlate} onChange={(e) => setForm({ ...form, licensePlate: e.target.value })} />
            </div>
          </div>

          {/* Color, Seats, Transmission */}
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Color</label>
              <select
                className="input-field"
                value={colorSelect}
                onChange={(e) => {
                  setColorSelect(e.target.value)
                  if (e.target.value !== 'custom') setForm({ ...form, color: e.target.value })
                  else setForm({ ...form, color: '' })
                }}
              >
                <option value="">Select…</option>
                {PRESET_COLORS.map((c) => <option key={c} value={c}>{c}</option>)}
                <option value="custom">Other…</option>
              </select>
              {colorSelect === 'custom' && (
                <input className="input-field mt-2" placeholder="Type color…" value={form.color} onChange={(e) => setForm({ ...form, color: e.target.value })} autoFocus />
              )}
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Seats</label>
              <input type="number" className="input-field" min="2" max="15" value={form.seats} onChange={(e) => setForm({ ...form, seats: Number(e.target.value) })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Transmission</label>
              <select className="input-field" value={form.transmission} onChange={(e) => setForm({ ...form, transmission: e.target.value })}>
                <option value="MANUAL">Manual</option>
                <option value="AUTOMATIC">Automatic</option>
              </select>
            </div>
          </div>

          {/* Fuel Type & Odometer */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Fuel Type</label>
              <select className="input-field" value={form.fuelType} onChange={(e) => setForm({ ...form, fuelType: e.target.value })}>
                {['GASOLINE', 'DIESEL', 'ELECTRIC', 'HYBRID'].map((f) => (
                  <option key={f} value={f}>{f}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">Odometer (km)</label>
              <input
                type="number"
                className="input-field"
                placeholder="e.g. 45000"
                min="0"
                value={form.mileage}
                onChange={(e) => setForm({ ...form, mileage: e.target.value })}
              />
            </div>
          </div>

          {/* Photos */}
          <div>
            <label className="block text-xs font-medium text-slate-500 mb-1.5">Photos (up to 10)</label>
            {photoPreviews.length > 0 && (
              <div className="grid grid-cols-3 gap-2 mb-3">
                {photoPreviews.map((src, i) => (
                  <div key={i} className="relative h-24 rounded-lg overflow-hidden bg-slate-100 group">
                    <Image src={src} alt={`preview ${i + 1}`} fill className="object-cover" unoptimized />
                    <button
                      type="button"
                      onClick={() => removePhoto(i)}
                      className="absolute top-1 right-1 p-0.5 bg-black/60 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </div>
                ))}
              </div>
            )}
            {photoFiles.length < 10 && (
              <>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  multiple
                  className="hidden"
                  onChange={handlePhotoChange}
                />
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="w-full flex items-center justify-center gap-2 px-4 py-3 border-2 border-dashed border-slate-200 rounded-xl text-sm text-slate-500 hover:border-slate-300 hover:text-slate-700 transition-colors"
                >
                  <Upload className="w-4 h-4" />
                  {photoFiles.length === 0 ? 'Click to add photos' : 'Add more photos'}
                </button>
              </>
            )}
          </div>

          <div className="flex gap-3 pt-2">
            <button type="button" onClick={handleClose} className="btn-secondary flex-1">Cancel</button>
            <button type="submit" disabled={loading} className="btn-primary flex-1">
              {loading ? 'Adding…' : 'Add Vehicle'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

export default function FleetPage() {
  const [vehicles, setVehicles] = useState<Vehicle[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showAddModal, setShowAddModal] = useState(false)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [categoryFilter, setCategoryFilter] = useState('')
  const [publishedFilter, setPublishedFilter] = useState('')

  const fetchVehicles = () => {
    setLoading(true)
    apiFetch<Vehicle[]>('/vehicles?pageSize=100')
      .then((result) => setVehicles(result ?? []))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }

  useEffect(() => { fetchVehicles() }, [])

  const togglePublished = async (id: string, current: boolean) => {
    try {
      await apiFetch(`/vehicles/${id}`, { method: 'PATCH', body: JSON.stringify({ isPublished: !current }) })
      setVehicles((prev) => prev.map((v) => v.id === id ? { ...v, isPublished: !current } : v))
    } catch (err: any) {
      alert(err.message)
    }
  }

  const filtered = vehicles.filter((v) => {
    if (search && !`${v.make} ${v.model} ${v.licensePlate}`.toLowerCase().includes(search.toLowerCase())) return false
    if (statusFilter && v.status !== statusFilter) return false
    if (categoryFilter && v.category !== categoryFilter) return false
    if (publishedFilter === 'published' && !v.isPublished) return false
    if (publishedFilter === 'unpublished' && v.isPublished) return false
    return true
  })

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold text-slate-900">Fleet</h2>
          <p className="text-sm text-slate-500 mt-0.5">{vehicles.length} vehicle{vehicles.length !== 1 ? 's' : ''} total</p>
        </div>
        <button onClick={() => setShowAddModal(true)} className="btn-primary">
          <Plus className="w-4 h-4" /> Add Vehicle
        </button>
      </div>

      {/* Filters */}
      <div className="card p-4 flex flex-wrap gap-3">
        <div className="flex items-center gap-2 flex-1 min-w-48">
          <Search className="w-4 h-4 text-slate-400" />
          <input
            className="flex-1 text-sm outline-none placeholder:text-slate-400"
            placeholder="Search make, model, plate…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <select className="input-field w-36" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
          <option value="">All statuses</option>
          {['AVAILABLE', 'RENTED', 'MAINTENANCE', 'OUT_OF_SERVICE'].map((s) => (
            <option key={s} value={s}>{s}</option>
          ))}
        </select>
        <select className="input-field w-36" value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)}>
          <option value="">All categories</option>
          {['ECONOMY', 'COMPACT', 'MIDSIZE', 'FULLSIZE', 'SUV', 'LUXURY', 'VAN', 'TRUCK'].map((c) => (
            <option key={c} value={c}>{c}</option>
          ))}
        </select>
        <select className="input-field w-36" value={publishedFilter} onChange={(e) => setPublishedFilter(e.target.value)}>
          <option value="">All visibility</option>
          <option value="published">Published</option>
          <option value="unpublished">Unpublished</option>
        </select>
      </div>

      {/* Table */}
      <div className="card overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center h-48">
            <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : error ? (
          <div className="p-8 text-center">
            <p className="text-red-600 font-medium">{error}</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 bg-slate-50">
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Vehicle</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Category</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Status</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Daily Rate</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Published</th>
                  <th className="text-right px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.map((vehicle) => (
                  <tr key={vehicle.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-10 rounded-lg bg-slate-100 overflow-hidden flex-shrink-0">
                          {vehicle.primaryPhoto ? (
                            <Image src={vehicle.primaryPhoto} alt={`${vehicle.make} ${vehicle.model}`} width={48} height={40} className="w-full h-full object-cover" unoptimized={!vehicle.primaryPhoto.includes('res.cloudinary.com')} />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-slate-400 text-xs">No photo</div>
                          )}
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-slate-900">{vehicle.make} {vehicle.model}</p>
                          <p className="text-xs text-slate-400">{vehicle.year} · {vehicle.licensePlate}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className="badge-gray">{vehicle.category}</span>
                    </td>
                    <td className="px-6 py-4">
                      <span className={STATUS_BADGE[vehicle.status]}>{vehicle.status}</span>
                    </td>
                    <td className="px-6 py-4 text-sm font-medium text-slate-900">
                      {formatCurrency(vehicle.dailyRate, 'MAD')}/day
                    </td>
                    <td className="px-6 py-4">
                      <button
                        onClick={() => togglePublished(vehicle.id, vehicle.isPublished)}
                        className={[
                          'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none',
                          vehicle.isPublished ? 'bg-blue-600' : 'bg-slate-200',
                        ].join(' ')}
                      >
                        <span
                          className={[
                            'pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform transition duration-200',
                            vehicle.isPublished ? 'translate-x-5' : 'translate-x-0',
                          ].join(' ')}
                        />
                      </button>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center justify-end gap-2">
                        <Link href={`/dashboard/fleet/${vehicle.id}`} className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors">
                          <Eye className="w-4 h-4" />
                        </Link>
                        <Link href={`/dashboard/fleet/${vehicle.id}`} className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors">
                          <Edit className="w-4 h-4" />
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr>
                    <td colSpan={6} className="px-6 py-12 text-center text-sm text-slate-400">
                      {vehicles.length === 0 ? 'No vehicles yet. Add your first vehicle to get started.' : 'No vehicles match your filters.'}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <AddVehicleModal open={showAddModal} onClose={() => setShowAddModal(false)} onSaved={fetchVehicles} />
    </div>
  )
}
