'use client'

import { useEffect, useRef, useState } from 'react'
import { Plus, Edit, Eye, Search, Upload, X, DollarSign } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { EMPLOYEE_PROFILE_KEY, apiFetch } from '@/lib/api'
import { formatCurrency } from '@rentaldrivego/types'
import { useDashboardI18n } from '@/components/I18nProvider'
import LocationDropdownField from '@/components/LocationDropdownField'
import { getMoroccanCityOptions } from '@/lib/moroccanCities'

interface Vehicle {
  id: string
  make: string
  model: string
  year: number
  category: string
  status: 'AVAILABLE' | 'RESERVED' | 'READY' | 'RENTED' | 'RETURNED' | 'NEEDS_CLEANING' | 'MAINTENANCE' | 'DAMAGE_REVIEW' | 'OUT_OF_SERVICE'
  dailyRate: number
  isPublished: boolean
  primaryPhoto: string | null
  licensePlate: string
  vin?: string | null
  pickupLocations?: string[]
  allowDifferentDropoff?: boolean
  dropoffLocations?: string[]
}

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

type EmployeeRole = 'OWNER' | 'MANAGER' | 'AGENT'

const ALL_STATUSES: Vehicle['status'][] = [
  'AVAILABLE', 'RESERVED', 'READY', 'RENTED',
  'RETURNED', 'NEEDS_CLEANING', 'MAINTENANCE', 'DAMAGE_REVIEW', 'OUT_OF_SERVICE',
]

interface MaintenanceModalProps {
  vehicleId: string
  vehicleName: string
  open: boolean
  onClose: () => void
  onSaved: () => void
}

function MaintenanceModal({ vehicleId, vehicleName, open, onClose, onSaved }: MaintenanceModalProps) {
  const { dict } = useDashboardI18n()
  const f = dict.fleet
  const today = new Date().toISOString().slice(0, 10)
  const [form, setForm] = useState({ type: '', description: '', cost: '', mileage: '', performedAt: today, nextDueAt: '' })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const reset = () => {
    setForm({ type: '', description: '', cost: '', mileage: '', performedAt: today, nextDueAt: '' })
    setError(null)
  }

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.type) { setError(f.maintenanceTypeRequired); return }
    setLoading(true)
    setError(null)
    try {
      await apiFetch(`/vehicles/${vehicleId}/maintenance`, {
        method: 'POST',
        body: JSON.stringify({
          type: form.type,
          description: form.description || undefined,
          cost: form.cost ? Math.round(parseFloat(form.cost) * 100) : undefined,
          mileage: form.mileage ? parseInt(form.mileage) : undefined,
          performedAt: new Date(form.performedAt).toISOString(),
          nextDueAt: form.nextDueAt ? new Date(form.nextDueAt).toISOString() : undefined,
        }),
      })
      onSaved()
      handleClose()
    } catch (err: any) {
      setError(err.message ?? f.failedToSave)
    } finally {
      setLoading(false)
    }
  }

  if (!open) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-blue-950/40" onClick={(e) => { if (e.target === e.currentTarget) handleClose() }}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-md mx-4 p-6">
        <h2 className="text-lg font-semibold text-slate-900 mb-1">{f.logMaintenance}</h2>
        <p className="text-sm text-slate-500 mb-5">{f.maintenanceSubtitle(vehicleName)}</p>
        {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">
          <div>
            <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.typeLabel}</label>
            <input className="input-field" placeholder={f.typePlaceholder} value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} autoFocus />
          </div>
          <div>
            <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.description}</label>
            <textarea className="input-field resize-none" rows={2} placeholder={f.descriptionPlaceholder} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.date}</label>
              <input type="date" className="input-field" value={form.performedAt} onChange={(e) => setForm({ ...form, performedAt: e.target.value })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.nextDueDate}</label>
              <input type="date" className="input-field" value={form.nextDueAt} onChange={(e) => setForm({ ...form, nextDueAt: e.target.value })} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.cost}</label>
              <input type="number" className="input-field" placeholder="0.00" min="0" step="0.01" value={form.cost} onChange={(e) => setForm({ ...form, cost: e.target.value })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.odometer}</label>
              <input type="number" className="input-field" placeholder="e.g. 52000" min="0" value={form.mileage} onChange={(e) => setForm({ ...form, mileage: e.target.value })} />
            </div>
          </div>
          <div className="flex gap-3 pt-1">
            <button type="button" onClick={handleClose} className="btn-secondary flex-1">{f.skip}</button>
            <button type="submit" disabled={loading} className="btn-primary flex-1">{loading ? f.saving : f.saveLog}</button>
          </div>
        </form>
      </div>
    </div>
  )
}

function StatusDropdown({ vehicleId, status, onStatusChange, disabled, disabledReason, onError }: {
  vehicleId: string
  status: Vehicle['status']
  onStatusChange: (id: string, status: Vehicle['status']) => void
  disabled?: boolean
  disabledReason?: string
  onError: (message: string) => void
}) {
  const { dict } = useDashboardI18n()
  const f = dict.fleet
  const [saving, setSaving] = useState(false)

  const select = async (next: Vehicle['status']) => {
    if (next === status) return
    setSaving(true)
    try {
      await apiFetch(`/vehicles/${vehicleId}/status`, { method: 'PATCH', body: JSON.stringify({ status: next }) })
      onStatusChange(vehicleId, next)
    } catch (err: any) {
      onError(err.message ?? 'Failed to update vehicle status')
    } finally {
      setSaving(false)
    }
  }

  return (
    <select
      value={status}
      disabled={disabled || saving}
      title={disabled ? disabledReason : undefined}
      onChange={(e) => void select(e.target.value as Vehicle['status'])}
      className={[
        'rounded-full border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 shadow-sm',
        disabled || saving ? 'cursor-not-allowed opacity-60' : 'cursor-pointer hover:border-slate-300',
      ].join(' ')}
    >
      {ALL_STATUSES.map((value) => (
        <option key={value} value={value}>
          {f.statusLabels[value]}
        </option>
      ))}
    </select>
  )
}

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 parseLocationInput(value: string) {
  return value
    .split(',')
    .map((entry) => entry.trim())
    .filter(Boolean)
}

function formatLocationInput(values: string[]) {
  return values.join(', ')
}

function AddVehicleModal({ open, onClose, onSaved }: AddVehicleModalProps) {
  const { dict, language } = useDashboardI18n()
  const f = dict.fleet
  const cityOptions = getMoroccanCityOptions(language)
  const [form, setForm] = useState({
    make: '', model: '', year: new Date().getFullYear(), category: 'ECONOMY',
    licensePlate: '', vin: '', color: '', seats: 5, transmission: 'MANUAL',
    fuelType: 'GASOLINE', mileage: '', pickupLocations: '', allowDifferentDropoff: false, dropoffLocations: '',
  })
  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((file) => URL.createObjectURL(file)))
    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',
      licensePlate: '', vin: '', color: '', seats: 5, transmission: 'MANUAL',
      fuelType: 'GASOLINE', mileage: '', pickupLocations: '', allowDifferentDropoff: false, dropoffLocations: '',
    })
    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(f.makeMissing); return }
    if (!form.model)        { setError(f.modelMissing); return }
    if (!form.licensePlate) { setError(f.plateMissing); return }
    if (form.allowDifferentDropoff && parseLocationInput(form.dropoffLocations).length === 0) {
      setError(f.dropoffLocationsRequired)
      return
    }
    setLoading(true)
    setError(null)
    try {
      const vehicle = await apiFetch<{ id: string }>('/vehicles', {
        method: 'POST',
        body: JSON.stringify({
          ...form,
          year: Number(form.year),
          seats: Number(form.seats),
          vin: form.vin.trim() || undefined,
          mileage: form.mileage ? Number(form.mileage) : undefined,
          pickupLocations: parseLocationInput(form.pickupLocations),
          allowDifferentDropoff: form.allowDifferentDropoff,
          dropoffLocations: form.allowDifferentDropoff ? parseLocationInput(form.dropoffLocations) : [],
        }),
      })
      if (photoFiles.length > 0) {
        const fd = new FormData()
        photoFiles.forEach((file) => fd.append('photos', file))
        await apiFetch(`/vehicles/${vehicle.id}/photos`, { method: 'POST', body: fd })
      }
      onSaved()
      handleClose()
    } catch (err: any) {
      setError(err.message ?? f.failedToAdd)
    } 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-blue-950/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">{f.addNewVehicle}</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">{f.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="">{f.selectMake}</option>
                {PRESET_MAKES.map((m) => <option key={m} value={m}>{m}</option>)}
                <option value="custom">{f.other}</option>
              </select>
              {makeSelect === 'custom' && (
                <input className="input-field mt-2" placeholder={f.typeMake} 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">{f.model}</label>
              {!presetModels ? (
                <input className="input-field" placeholder={f.typeModel} 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="">{f.selectModel}</option>
                    {presetModels.map((m) => <option key={m} value={m}>{m}</option>)}
                    <option value="custom">{f.other}</option>
                  </select>
                  {modelSelect === 'custom' && (
                    <input className="input-field mt-2" placeholder={f.typeModel} 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">{f.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">{f.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'] as const).map((c) => (
                  <option key={c} value={c}>{f.categoryLabels[c]}</option>
                ))}
              </select>
            </div>
          </div>

          {/* License Plate & VIN */}
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.licensePlate}</label>
              <input className="input-field" placeholder="AB-1234-CD" required value={form.licensePlate} onChange={(e) => setForm({ ...form, licensePlate: e.target.value })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.vin}</label>
              <input className="input-field" placeholder="1HGCM82633A123456" value={form.vin} onChange={(e) => setForm({ ...form, vin: 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">{f.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="">{f.select}</option>
                {PRESET_COLORS.map((c) => <option key={c} value={c}>{c}</option>)}
                <option value="custom">{f.other}</option>
              </select>
              {colorSelect === 'custom' && (
                <input className="input-field mt-2" placeholder={f.typeColor} 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">{f.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">{f.transmission}</label>
              <select className="input-field" value={form.transmission} onChange={(e) => setForm({ ...form, transmission: e.target.value })}>
                <option value="MANUAL">{f.manual}</option>
                <option value="AUTOMATIC">{f.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">{f.fuelType}</label>
              <select className="input-field" value={form.fuelType} onChange={(e) => setForm({ ...form, fuelType: e.target.value })}>
                {(['GASOLINE', 'DIESEL', 'ELECTRIC', 'HYBRID'] as const).map((fuel) => (
                  <option key={fuel} value={fuel}>{f.fuelTypeLabels[fuel]}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.odometer}</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>

          <div className="space-y-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
            <LocationDropdownField
              label={f.pickupLocations}
              placeholder={f.pickupLocationsPlaceholder}
              hint={f.locationHint}
              addCustomLabel={f.addCustomLocation}
              options={cityOptions}
              value={parseLocationInput(form.pickupLocations)}
              onChange={(locations) => setForm({ ...form, pickupLocations: formatLocationInput(locations) })}
            />
            <label className="flex items-center gap-3 rounded-lg border border-slate-200 bg-white px-3 py-3 text-sm font-medium text-slate-700">
              <input
                type="checkbox"
                checked={form.allowDifferentDropoff}
                onChange={(e) => setForm({
                  ...form,
                  allowDifferentDropoff: e.target.checked,
                  dropoffLocations: e.target.checked ? form.dropoffLocations : '',
                })}
                className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
              />
              <span>{f.allowDifferentDropoff}</span>
            </label>
            {form.allowDifferentDropoff && (
              <LocationDropdownField
                label={f.dropoffLocations}
                placeholder={f.dropoffLocationsPlaceholder}
                hint={f.locationHint}
                addCustomLabel={f.addCustomLocation}
                options={cityOptions}
                value={parseLocationInput(form.dropoffLocations)}
                onChange={(locations) => setForm({ ...form, dropoffLocations: formatLocationInput(locations) })}
              />
            )}
          </div>

          {/* Photos */}
          <div>
            <label className="block text-xs font-medium text-slate-500 mb-1.5">{f.photosLabel}</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-blue-950/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 ? f.clickToAddPhotos : f.addMorePhotos}
                </button>
              </>
            )}
          </div>

          <div className="flex gap-3 pt-2">
            <button type="button" onClick={handleClose} className="btn-secondary flex-1">{f.cancel}</button>
            <button type="submit" disabled={loading} className="btn-primary flex-1">
              {loading ? f.adding : f.addVehicle}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

export default function FleetPage() {
  const { dict, language } = useDashboardI18n()
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const f = dict.fleet
  const managerRequiredMessage =
    language === 'fr'
      ? 'Cette action nécessite le rôle Gestionnaire ou supérieur.'
      : language === 'ar'
        ? 'يتطلب هذا الإجراء دور المدير أو أعلى.'
        : 'This action requires the Manager role or higher.'
  const [vehicles, setVehicles] = useState<Vehicle[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [actionError, setActionError] = useState<string | null>(null)
  const [showAddModal, setShowAddModal] = useState(false)
  const [employeeRole, setEmployeeRole] = useState<EmployeeRole | null>(null)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [categoryFilter, setCategoryFilter] = useState('')
  const [publishedFilter, setPublishedFilter] = useState('')
  const [maintenanceModal, setMaintenanceModal] = useState<{ vehicleId: string; vehicleName: string } | null>(null)

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

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

  useEffect(() => {
    const cached = window.localStorage.getItem(EMPLOYEE_PROFILE_KEY)
    if (cached) {
      try {
        const profile = JSON.parse(cached) as { role?: EmployeeRole }
        if (profile.role) setEmployeeRole(profile.role)
      } catch {}
    }

    let cancelled = false

    apiFetch<{ employee: { role: EmployeeRole } }>('/auth/employee/me')
      .then(({ employee }) => {
        if (cancelled) return
        setEmployeeRole(employee.role)
      })
      .catch(() => {})

    return () => { cancelled = true }
  }, [])

  useEffect(() => {
    if (searchParams.get('modal') === 'add-car') {
      setShowAddModal(true)
    }
  }, [searchParams])

  const canManageFleet = employeeRole === 'OWNER' || employeeRole === 'MANAGER'

  function closeAddModal() {
    setShowAddModal(false)
    if (searchParams.get('modal') === 'add-car') {
      const params = new URLSearchParams(searchParams.toString())
      params.delete('modal')
      router.replace(params.toString() ? `${pathname}?${params.toString()}` : pathname)
    }
  }

  const togglePublished = async (id: string, current: boolean) => {
    setActionError(null)
    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) {
      setActionError(err.statusCode === 403 ? managerRequiredMessage : (err.message ?? 'Failed to update publication status'))
    }
  }

  const PUBLISHED = new Set<Vehicle['status']>(['AVAILABLE', 'RESERVED', 'READY', 'RENTED'])

  const changeStatus = (id: string, status: Vehicle['status']) => {
    const isPublished = PUBLISHED.has(status)
    setVehicles((prev) => prev.map((v) => v.id === id ? { ...v, status, isPublished } : v))
    setStatusFilter('')
    if (status === 'MAINTENANCE') {
      const vehicle = vehicles.find((v) => v.id === id)
      if (vehicle) setMaintenanceModal({ vehicleId: id, vehicleName: `${vehicle.make} ${vehicle.model}` })
    }
  }

  const filtered = vehicles.filter((v) => {
    if (search && !`${v.make} ${v.model} ${v.licensePlate} ${v.vin ?? ''}`.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">{f.heading}</h2>
          <p className="text-sm text-slate-500 mt-0.5">{f.vehicleCount(vehicles.length)}</p>
        </div>
        <button onClick={() => setShowAddModal(true)} className="btn-primary" disabled={!canManageFleet} title={!canManageFleet ? managerRequiredMessage : undefined}>
          <Plus className="w-4 h-4" /> {f.addVehicle}
        </button>
      </div>

      {actionError ? <div className="card p-4 text-sm text-red-600">{actionError}</div> : null}

      {/* 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={f.searchPlaceholder}
            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="">{f.allStatuses}</option>
          {ALL_STATUSES.map((s) => (
            <option key={s} value={s}>{f.statusLabels[s]}</option>
          ))}
        </select>
        <select className="input-field w-36" value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)}>
          <option value="">{f.allCategories}</option>
          {(['ECONOMY', 'COMPACT', 'MIDSIZE', 'FULLSIZE', 'SUV', 'LUXURY', 'VAN', 'TRUCK'] as const).map((c) => (
            <option key={c} value={c}>{f.categoryLabels[c]}</option>
          ))}
        </select>
        <select className="input-field w-36" value={publishedFilter} onChange={(e) => setPublishedFilter(e.target.value)}>
          <option value="">{f.allVisibility}</option>
          <option value="published">{f.published}</option>
          <option value="unpublished">{f.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-start px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{f.colVehicle}</th>
                  <th className="text-start px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{f.colCategory}</th>
                  <th className="text-start px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{f.colStatus}</th>
                  <th className="text-start px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{f.colDailyRate}</th>
                  <th className="text-start px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{f.colPublished}</th>
                  <th className="text-end px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">{f.colActions}</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>
                        <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}
                          {vehicle.vin ? ` · ${vehicle.vin}` : ''}
                        </p>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className="badge-gray">{f.categoryLabels[vehicle.category as keyof typeof f.categoryLabels] ?? vehicle.category}</span>
                    </td>
                    <td className="px-6 py-4">
                      <StatusDropdown
                        vehicleId={vehicle.id}
                        status={vehicle.status}
                        onStatusChange={changeStatus}
                        disabled={!canManageFleet}
                        disabledReason={managerRequiredMessage}
                        onError={setActionError}
                      />
                    </td>
                    <td className="px-6 py-4 text-sm font-medium text-slate-900">
                      {formatCurrency(vehicle.dailyRate, 'MAD')}{f.perDay}
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center">
                        <button
                          onClick={() => togglePublished(vehicle.id, vehicle.isPublished)}
                          disabled={!canManageFleet}
                          title={!canManageFleet ? managerRequiredMessage : undefined}
                          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',
                            !canManageFleet ? 'cursor-not-allowed opacity-60' : '',
                            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 ? 'ltr:translate-x-5 rtl:-translate-x-5' : 'translate-x-0',
                            ].join(' ')}
                          />
                        </button>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center justify-end gap-2 rtl:justify-start">
                        <Link href={`/fleet/${vehicle.id}?tab=pricing`} title="Manage pricing" aria-label="Manage pricing" className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors">
                          <DollarSign className="w-4 h-4" />
                        </Link>
                        <Link href={`/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={`/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 ? f.noVehicles : f.noMatch}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <AddVehicleModal open={showAddModal} onClose={closeAddModal} onSaved={fetchVehicles} />
      {maintenanceModal && (
        <MaintenanceModal
          vehicleId={maintenanceModal.vehicleId}
          vehicleName={maintenanceModal.vehicleName}
          open={true}
          onClose={() => setMaintenanceModal(null)}
          onSaved={() => setMaintenanceModal(null)}
        />
      )}
    </div>
  )
}
