'use client'

import { useEffect, useRef, useState } from 'react'
import { useParams, useRouter, useSearchParams } from 'next/navigation'
import Image from 'next/image'
import { ArrowLeft, Edit, X, Check, Upload, Trash2, CalendarDays, DollarSign, Info, Wrench, Plus, ChevronDown, ChevronUp } from 'lucide-react'
import { formatCurrency } from '@rentaldrivego/types'
import { apiFetch } from '@/lib/api'
import VehicleCalendar from '@/components/VehicleCalendar'
import VehiclePricingManager from '@/components/VehiclePricingManager'
import { useDashboardI18n } from '@/components/I18nProvider'
import LocationDropdownField from '@/components/LocationDropdownField'
import { getMoroccanCityOptions } from '@/lib/moroccanCities'

interface VehicleDetail {
  id: string
  make: string
  model: string
  year: number
  category: string
  dailyRate: number
  status: string
  color: string
  transmission: string
  fuelType: string
  seats: number
  mileage: number | null
  licensePlate: string
  vin: string | null
  photos: string[]
  notes: string | null
  isPublished: boolean
  pickupLocations: string[]
  allowDifferentDropoff: boolean
  dropoffLocations: string[]
}

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 Array.isArray(values) ? values.join(', ') : ''
}

function initMakeSelect(make: string) {
  return PRESET_MAKES.includes(make) ? make : (make ? 'custom' : '')
}
function initModelSelect(make: string, model: string) {
  const presets = MODELS_BY_MAKE[make]
  if (!presets) return model ? 'custom' : ''
  return presets.includes(model) ? model : (model ? 'custom' : '')
}
function initColorSelect(color: string) {
  return PRESET_COLORS.includes(color) ? color : (color ? 'custom' : '')
}

interface MaintenanceLog {
  id: string
  type: string
  description: string | null
  cost: number | null
  mileage: number | null
  performedAt: string
  nextDueAt: string | null
  nextDueMileage: number | null
}

const ROUTINE_TYPES = [
  { key: 'Oil Change',            intervalMonths: 6  },
  { key: 'Technical Inspection',  intervalMonths: 12 },
  { key: 'Vehicle Registration',  intervalMonths: 12 },
  { key: 'Car Tax',               intervalMonths: 12 },
  { key: 'Tire Rotation',         intervalMonths: 6  },
  { key: 'Brake Inspection',      intervalMonths: 12 },
  { key: 'Air Filter',            intervalMonths: 12 },
  { key: 'Cabin Filter',          intervalMonths: 12 },
  { key: 'Battery Check',         intervalMonths: 12 },
  { key: 'Belt / Chain Service',  intervalMonths: 24 },
  { key: 'Coolant Flush',         intervalMonths: 24 },
  { key: 'Transmission Service',  intervalMonths: 24 },
]

function serviceStatus(log: MaintenanceLog | undefined, currentMileage: number | null): 'none' | 'overdue' | 'due-soon' | 'ok' {
  if (!log) return 'none'
  const now = new Date()
  let worstLevel: 'ok' | 'due-soon' | 'overdue' = 'ok'

  if (log.nextDueAt) {
    const diffDays = (new Date(log.nextDueAt).getTime() - now.getTime()) / (1000 * 60 * 60 * 24)
    if (diffDays < 0) return 'overdue'
    if (diffDays <= 30) worstLevel = 'due-soon'
  }

  if (log.nextDueMileage != null && currentMileage != null) {
    const kmLeft = log.nextDueMileage - currentMileage
    if (kmLeft <= 0) return 'overdue'
    if (kmLeft <= 500) worstLevel = 'due-soon'
  }

  return worstLevel
}

function StatusPill({ status }: { status: ReturnType<typeof serviceStatus> }) {
  const { dict } = useDashboardI18n()
  const vd = dict.vehicleDetail
  if (status === 'none')     return <span className="badge-gray text-xs">{vd.statusNone}</span>
  if (status === 'overdue')  return <span className="badge-red text-xs">{vd.statusOverdue}</span>
  if (status === 'due-soon') return <span className="badge-amber text-xs">{vd.statusDueSoon}</span>
  return <span className="badge-green text-xs">{vd.statusOk}</span>
}

function MaintenanceRow({ vehicleId, typeKey, intervalMonths, currentMileage, log, onLogged }: {
  vehicleId: string
  typeKey: string
  intervalMonths: number
  currentMileage: number | null
  log: MaintenanceLog | undefined
  onLogged: () => void
}) {
  const { dict } = useDashboardI18n()
  const vd = dict.vehicleDetail
  const [open, setOpen] = useState(false)
  const today = new Date().toISOString().slice(0, 10)
  const defaultNextDue = (() => {
    const d = new Date()
    d.setMonth(d.getMonth() + intervalMonths)
    return d.toISOString().slice(0, 10)
  })()
  const [form, setForm] = useState({
    description: '', cost: '', mileage: '', performedAt: today,
    nextDueAt: defaultNextDue, nextDueMileage: '',
  })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.performedAt) { setError(vd.dateRequired); return }
    setSaving(true)
    setError(null)
    try {
      await apiFetch(`/vehicles/${vehicleId}/maintenance`, {
        method: 'POST',
        body: JSON.stringify({
          type: typeKey,
          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,
          nextDueMileage: form.nextDueMileage ? parseInt(form.nextDueMileage) : undefined,
        }),
      })
      setForm({ description: '', cost: '', mileage: '', performedAt: today, nextDueAt: defaultNextDue, nextDueMileage: '' })
      setOpen(false)
      onLogged()
    } catch (err: any) {
      setError(err.message ?? vd.savingLabel)
    } finally {
      setSaving(false)
    }
  }

  const status = serviceStatus(log, currentMileage)
  const displayLabel = vd.routineTypes[typeKey] ?? typeKey

  const nextDueText = (() => {
    if (!log) return vd.noRecord
    const parts: string[] = [`${vd.lastPrefix} ${new Date(log.performedAt).toLocaleDateString()}`]
    if (log.mileage) parts.push(vd.atKm(log.mileage.toLocaleString()))
    const dueParts: string[] = []
    if (log.nextDueAt) dueParts.push(new Date(log.nextDueAt).toLocaleDateString())
    if (log.nextDueMileage != null) dueParts.push(`${log.nextDueMileage.toLocaleString()} km`)
    if (dueParts.length) parts.push(`${vd.duePrefix} ${dueParts.join(` ${vd.orSep} `)}`)
    if (currentMileage != null && log.nextDueMileage != null) {
      const kmLeft = log.nextDueMileage - currentMileage
      parts.push(`(${kmLeft > 0 ? vd.kmLeft(kmLeft.toLocaleString()) : vd.overdueByKm})`)
    }
    return parts.join(' ')
  })()

  return (
    <div className="rounded-xl border border-slate-100 overflow-hidden">
      <div className="flex items-center justify-between px-4 py-3 bg-white hover:bg-slate-50 transition-colors">
        <div className="flex items-center gap-3 min-w-0">
          <Wrench className="w-4 h-4 text-slate-400 flex-shrink-0" />
          <div className="min-w-0">
            <p className="text-sm font-medium text-slate-900">{displayLabel}</p>
            <p className="text-xs text-slate-400 mt-0.5 truncate">{nextDueText}</p>
          </div>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <StatusPill status={status} />
          <button
            onClick={() => setOpen((o) => !o)}
            className="flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700 px-2 py-1 rounded-lg hover:bg-blue-50 transition-colors"
          >
            <Plus className="w-3.5 h-3.5" />
            {vd.logBtn}
            {open ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
          </button>
        </div>
      </div>

      {open && (
        <form onSubmit={handleSubmit} className="border-t border-slate-100 bg-slate-50 px-4 py-4 space-y-3">
          {error && <p className="text-xs text-red-600">{error}</p>}

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1">{vd.serviceDateLabel}</label>
              <input type="date" className="input-field text-sm" value={form.performedAt} onChange={(e) => setForm({ ...form, performedAt: e.target.value })} required />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1">{vd.odometerAtService}</label>
              <input type="number" className="input-field text-sm" placeholder={currentMileage ? String(currentMileage) : 'e.g. 52000'} min="0" value={form.mileage} onChange={(e) => setForm({ ...form, mileage: e.target.value })} />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1">{vd.nextDueDateLabel}</label>
              <input type="date" className="input-field text-sm" value={form.nextDueAt} onChange={(e) => setForm({ ...form, nextDueAt: e.target.value })} />
            </div>
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1">{vd.nextDueKmLabel}</label>
              <input type="number" className="input-field text-sm" placeholder="e.g. 60000" min="0" value={form.nextDueMileage} onChange={(e) => setForm({ ...form, nextDueMileage: e.target.value })} />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-slate-500 mb-1">{vd.costLabel}</label>
              <input type="number" className="input-field text-sm" 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">{vd.maintenanceNotesLabel}</label>
              <input className="input-field text-sm" placeholder={vd.optional} value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
            </div>
          </div>

          <div className="flex justify-end gap-2">
            <button type="button" onClick={() => setOpen(false)} className="btn-secondary text-xs py-1.5 px-3">{vd.cancelBtn}</button>
            <button type="submit" disabled={saving} className="btn-primary text-xs py-1.5 px-3">{saving ? vd.savingLabel : vd.saveLabel}</button>
          </div>
        </form>
      )}
    </div>
  )
}

type Tab = 'details' | 'maintenance' | 'calendar' | 'pricing'

export default function FleetDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const searchParams = useSearchParams()
  const { dict, language } = useDashboardI18n()
  const vd = dict.vehicleDetail
  const fl = dict.fleet
  const cityOptions = getMoroccanCityOptions(language)

  const [vehicle, setVehicle] = useState<VehicleDetail | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<Tab>('details')
  const [editing, setEditing] = useState(false)
  const [saving, setSaving] = useState(false)
  const [saveError, setSaveError] = useState<string | null>(null)

  const [form, setForm] = useState<{
    make: string; model: string; year: number; category: string
    dailyRate: string; licensePlate: string; vin: string; color: string
    seats: number; transmission: string; fuelType: string
    status: string; notes: string; mileage: string
    pickupLocations: string; allowDifferentDropoff: boolean; dropoffLocations: string
  } | null>(null)
  const [makeSelect, setMakeSelect] = useState('')
  const [modelSelect, setModelSelect] = useState('')
  const [colorSelect, setColorSelect] = useState('')

  const [maintenanceLogs, setMaintenanceLogs] = useState<MaintenanceLog[]>([])

  const fetchMaintenance = () => {
    apiFetch<MaintenanceLog[]>(`/vehicles/${params.id}/maintenance`)
      .then((logs) => setMaintenanceLogs(logs ?? []))
      .catch(() => {})
  }

  useEffect(() => { fetchMaintenance() }, [params.id])

  const [deletingPhotoIdx, setDeletingPhotoIdx] = useState<number | null>(null)
  const [newPhotoFiles, setNewPhotoFiles] = useState<File[]>([])
  const [newPhotoPreviews, setNewPhotoPreviews] = useState<string[]>([])
  const [uploadingPhotos, setUploadingPhotos] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    apiFetch<VehicleDetail>(`/vehicles/${params.id}`)
      .then(setVehicle)
      .catch((err) => setError(err.message))
  }, [params.id])

  useEffect(() => {
    if (searchParams.get('tab') === 'pricing') {
      setActiveTab('pricing')
    }
  }, [searchParams])

  const startEdit = () => {
    if (!vehicle) return
    setForm({
      make: vehicle.make, model: vehicle.model, year: vehicle.year,
      category: vehicle.category,
      dailyRate: (vehicle.dailyRate / 100).toFixed(2),
      licensePlate: vehicle.licensePlate,
      vin: vehicle.vin ?? '',
      color: vehicle.color ?? '', seats: vehicle.seats,
      transmission: vehicle.transmission, fuelType: vehicle.fuelType,
      status: vehicle.status, notes: vehicle.notes ?? '',
      mileage: vehicle.mileage != null ? String(vehicle.mileage) : '',
      pickupLocations: formatLocationInput(vehicle.pickupLocations),
      allowDifferentDropoff: vehicle.allowDifferentDropoff,
      dropoffLocations: formatLocationInput(vehicle.dropoffLocations),
    })
    setMakeSelect(initMakeSelect(vehicle.make))
    setModelSelect(initModelSelect(vehicle.make, vehicle.model))
    setColorSelect(initColorSelect(vehicle.color ?? ''))
    setSaveError(null)
    setEditing(true)
  }

  const cancelEdit = () => {
    newPhotoPreviews.forEach((p) => URL.revokeObjectURL(p))
    setNewPhotoFiles([])
    setNewPhotoPreviews([])
    setEditing(false)
    setForm(null)
    setSaveError(null)
  }

  const handleSave = async () => {
    if (!form || !vehicle) return
    if (!form.make)         { setSaveError(vd.makeRequired); return }
    if (!form.model)        { setSaveError(vd.modelRequired); return }
    if (!form.licensePlate) { setSaveError(vd.plateRequired); return }
    const rate = parseFloat(form.dailyRate)
    if (isNaN(rate) || rate < 0) { setSaveError(vd.rateInvalid); return }
    if (form.allowDifferentDropoff && parseLocationInput(form.dropoffLocations).length === 0) {
      setSaveError(fl.dropoffLocationsRequired)
      return
    }

    setSaving(true)
    setSaveError(null)
    try {
      const updated = await apiFetch<VehicleDetail>(`/vehicles/${vehicle.id}`, {
        method: 'PATCH',
        body: JSON.stringify({
          make: form.make, model: form.model, year: Number(form.year),
          category: form.category, dailyRate: Math.round(rate * 100),
          licensePlate: form.licensePlate, vin: form.vin.trim() || undefined, color: form.color,
          seats: Number(form.seats), transmission: form.transmission,
          fuelType: form.fuelType, status: form.status,
          notes: form.notes || undefined,
          mileage: form.mileage ? Number(form.mileage) : undefined,
          pickupLocations: parseLocationInput(form.pickupLocations),
          allowDifferentDropoff: form.allowDifferentDropoff,
          dropoffLocations: form.allowDifferentDropoff ? parseLocationInput(form.dropoffLocations) : [],
        }),
      })

      let finalVehicle = updated
      if (newPhotoFiles.length > 0) {
        setUploadingPhotos(true)
        const fd = new FormData()
        newPhotoFiles.forEach((f) => fd.append('photos', f))
        finalVehicle = await apiFetch<VehicleDetail>(`/vehicles/${vehicle.id}/photos`, { method: 'POST', body: fd })
        newPhotoPreviews.forEach((p) => URL.revokeObjectURL(p))
        setNewPhotoFiles([])
        setNewPhotoPreviews([])
        setUploadingPhotos(false)
      }

      setVehicle(finalVehicle)
      setEditing(false)
      setForm(null)
    } catch (err: any) {
      setSaveError(err.message ?? vd.failedSave)
      setUploadingPhotos(false)
    } finally {
      setSaving(false)
    }
  }

  const handleDeletePhoto = async (idx: number) => {
    if (!vehicle) return
    setDeletingPhotoIdx(idx)
    try {
      const updated = await apiFetch<VehicleDetail>(`/vehicles/${vehicle.id}/photos/${idx}`, { method: 'DELETE' })
      setVehicle(updated)
    } catch (err: any) {
      alert(err.message)
    } finally {
      setDeletingPhotoIdx(null)
    }
  }

  const handleNewPhotoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? [])
    if (!files.length) return
    const totalExisting = vehicle?.photos.length ?? 0
    const combined = [...newPhotoFiles, ...files].slice(0, 10 - totalExisting)
    setNewPhotoFiles(combined)
    setNewPhotoPreviews(combined.map((f) => URL.createObjectURL(f)))
    e.target.value = ''
  }

  const removeNewPhoto = (i: number) => {
    URL.revokeObjectURL(newPhotoPreviews[i])
    setNewPhotoFiles(newPhotoFiles.filter((_, idx) => idx !== i))
    setNewPhotoPreviews(newPhotoPreviews.filter((_, idx) => idx !== i))
  }

  if (error)    return <div className="card p-6 text-sm text-red-600">{error}</div>
  if (!vehicle) return <div className="card p-6 text-sm text-slate-500">{vd.loadingVehicle}</div>

  const presetModels = form && MODELS_BY_MAKE[form.make] ? MODELS_BY_MAKE[form.make] : null
  const totalPhotos = vehicle.photos.length + newPhotoFiles.length

  const categoryLabel = fl.categoryLabels[vehicle.category as keyof typeof fl.categoryLabels] ?? vehicle.category
  const statusLabel   = fl.statusLabels[vehicle.status as keyof typeof fl.statusLabels] ?? vehicle.status
  const fuelLabel     = fl.fuelTypeLabels[vehicle.fuelType as keyof typeof fl.fuelTypeLabels] ?? vehicle.fuelType
  const transLabel    = vehicle.transmission === 'MANUAL' ? fl.manual : fl.automatic
  const pricingTabLabel = language === 'fr' ? 'Tarifs' : language === 'ar' ? 'التسعير' : 'Pricing'

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={() => router.back()} className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors">
            <ArrowLeft className="w-4 h-4" />
          </button>
          <div>
            <h2 className="text-xl font-semibold text-slate-900">{vehicle.make} {vehicle.model}</h2>
            <p className="text-sm text-slate-500 mt-0.5">
              {vehicle.year} · {vehicle.licensePlate}
              {vehicle.vin ? ` · ${vehicle.vin}` : ''}
              {' · '}
              {statusLabel}
            </p>
          </div>
        </div>
        {!editing ? (
          <button onClick={startEdit} className="btn-secondary flex items-center gap-2">
            <Edit className="w-4 h-4" /> {vd.editBtn}
          </button>
        ) : (
          <div className="flex gap-2">
            <button onClick={cancelEdit} className="btn-secondary flex items-center gap-2">
              <X className="w-4 h-4" /> {vd.cancelBtn}
            </button>
            <button onClick={handleSave} disabled={saving} className="btn-primary flex items-center gap-2">
              <Check className="w-4 h-4" />
              {saving ? (uploadingPhotos ? vd.uploadingPhotosBtn : vd.savingBtn) : vd.saveBtn}
            </button>
          </div>
        )}
      </div>

      {saveError && (
        <div className="px-4 py-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">{saveError}</div>
      )}

      {/* Tab bar */}
      <div className="flex gap-1 border-b border-slate-200 dark:border-slate-800">
        {(['details', 'maintenance', 'calendar', 'pricing'] as Tab[]).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={[
              'flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors',
              activeTab === tab
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300',
            ].join(' ')}
          >
            {tab === 'details'      && <><Info className="w-4 h-4" /> {vd.tabDetails}</>}
            {tab === 'maintenance'  && (
              <>
                <Wrench className="w-4 h-4" /> {vd.tabMaintenance}
                {maintenanceLogs.length === 0 && <span className="ml-1 inline-flex h-4 w-4 items-center justify-center rounded-full bg-orange-100 text-orange-700 text-[10px] font-bold">!</span>}
              </>
            )}
            {tab === 'calendar'     && <><CalendarDays className="w-4 h-4" /> {vd.tabCalendar}</>}
            {tab === 'pricing'      && <><DollarSign className="w-4 h-4" /> {pricingTabLabel}</>}
          </button>
        ))}
      </div>

      {activeTab === 'details' && (
        <div className="grid gap-6 lg:grid-cols-[1.3fr_0.7fr]">
          {/* Photos */}
          <div className="card p-6">
            <h3 className="text-base font-semibold text-slate-900 mb-4">{vd.photosHeading}</h3>
            <div className="grid gap-4 sm:grid-cols-2">
              {vehicle.photos.map((photo, index) => (
                <div key={`${photo}-${index}`} className="relative h-48 rounded-xl overflow-hidden bg-slate-100 group">
                  <Image src={photo} alt={`${vehicle.make} ${vehicle.model} photo ${index + 1}`} fill className="object-cover" unoptimized={!photo.includes('res.cloudinary.com')} priority={index === 0} />
                  {editing && (
                    <button
                      onClick={() => handleDeletePhoto(index)}
                      disabled={deletingPhotoIdx === index}
                      className="absolute top-2 right-2 p-1.5 bg-red-600 text-white rounded-lg opacity-0 group-hover:opacity-100 transition-opacity disabled:opacity-60"
                    >
                      {deletingPhotoIdx === index
                        ? <div className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                        : <Trash2 className="w-3.5 h-3.5" />}
                    </button>
                  )}
                </div>
              ))}

              {editing && newPhotoPreviews.map((src, i) => (
                <div key={`new-${i}`} className="relative h-48 rounded-xl overflow-hidden bg-slate-100 group ring-2 ring-blue-400">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={src} alt={`new photo ${i + 1}`} className="object-cover w-full h-full" />
                  <button
                    onClick={() => removeNewPhoto(i)}
                    className="absolute top-2 right-2 p-1.5 bg-blue-950/60 text-white rounded-lg opacity-0 group-hover:opacity-100 transition-opacity"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                  <span className="absolute bottom-2 left-2 text-xs bg-blue-600 text-white px-2 py-0.5 rounded-full">{vd.newPhotoBadge}</span>
                </div>
              ))}

              {vehicle.photos.length === 0 && !editing && (
                <div className="text-sm text-slate-400">{vd.noPhotosYet}</div>
              )}
            </div>

            {editing && totalPhotos < 10 && (
              <div className="mt-4">
                <input ref={fileInputRef} type="file" accept="image/*" multiple className="hidden" onChange={handleNewPhotoChange} />
                <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" />
                  {totalPhotos === 0 ? vd.clickToAddPhotos : vd.addMorePhotos(totalPhotos)}
                </button>
              </div>
            )}
            {editing && totalPhotos >= 10 && (
              <p className="mt-3 text-xs text-slate-400 text-center">{vd.maxPhotosReached}</p>
            )}
          </div>

          {/* Details / Edit form */}
          <div className="card p-6">
            <h3 className="text-base font-semibold text-slate-900 mb-4">{vd.vehicleDetailsHeading}</h3>

            {!editing || !form ? (
              <dl className="space-y-3 text-sm">
                <div><dt className="text-slate-500">{vd.labelCategory}</dt><dd className="text-slate-900">{categoryLabel}</dd></div>
                <div><dt className="text-slate-500">{vd.labelDailyRate}</dt><dd className="text-slate-900">{formatCurrency(vehicle.dailyRate, 'MAD')}</dd></div>
                <div><dt className="text-slate-500">{vd.labelStatus}</dt><dd className="text-slate-900">{statusLabel}</dd></div>
                <div><dt className="text-slate-500">{vd.vinLabel}</dt><dd className="text-slate-900">{vehicle.vin || '—'}</dd></div>
                <div><dt className="text-slate-500">{vd.labelSeats}</dt><dd className="text-slate-900">{vehicle.seats}</dd></div>
                <div><dt className="text-slate-500">{vd.labelTransmission}</dt><dd className="text-slate-900">{transLabel}</dd></div>
                <div><dt className="text-slate-500">{vd.labelFuelType}</dt><dd className="text-slate-900">{fuelLabel}</dd></div>
                <div><dt className="text-slate-500">{vd.labelColor}</dt><dd className="text-slate-900">{vehicle.color || '—'}</dd></div>
                <div><dt className="text-slate-500">{vd.labelOdometer}</dt><dd className="text-slate-900">{vehicle.mileage != null ? `${vehicle.mileage.toLocaleString()} km` : '—'}</dd></div>
                <div><dt className="text-slate-500">{fl.pickupLocations}</dt><dd className="text-slate-900">{vehicle.pickupLocations.length > 0 ? vehicle.pickupLocations.join(', ') : '—'}</dd></div>
                <div><dt className="text-slate-500">{fl.allowDifferentDropoff}</dt><dd className="text-slate-900">{vehicle.allowDifferentDropoff ? fl.differentDropoffAvailable : fl.sameDropoffOnly}</dd></div>
                {vehicle.allowDifferentDropoff && (
                  <div><dt className="text-slate-500">{fl.dropoffLocations}</dt><dd className="text-slate-900">{vehicle.dropoffLocations.length > 0 ? vehicle.dropoffLocations.join(', ') : '—'}</dd></div>
                )}
                <div><dt className="text-slate-500">{vd.labelNotes}</dt><dd className="text-slate-900">{vehicle.notes ?? '—'}</dd></div>
              </dl>
            ) : (
              <div className="space-y-4 text-sm">
                {/* Make */}
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.makeLabel}</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="">{vd.selectMake}</option>
                    {PRESET_MAKES.map((m) => <option key={m} value={m}>{m}</option>)}
                    <option value="custom">{vd.other}</option>
                  </select>
                  {makeSelect === 'custom' && (
                    <input className="input-field mt-2" placeholder={vd.typeMake} value={form.make} onChange={(e) => setForm({ ...form, make: e.target.value })} />
                  )}
                </div>

                {/* Model */}
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.modelLabel}</label>
                  {!presetModels ? (
                    <input className="input-field" placeholder={vd.typeModel} 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="">{vd.selectModel}</option>
                        {presetModels.map((m) => <option key={m} value={m}>{m}</option>)}
                        <option value="custom">{vd.other}</option>
                      </select>
                      {modelSelect === 'custom' && (
                        <input className="input-field mt-2" placeholder={vd.typeModel} value={form.model} onChange={(e) => setForm({ ...form, model: e.target.value })} />
                      )}
                    </>
                  )}
                </div>

                {/* Year & Category */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.yearLabel}</label>
                    <input type="number" className="input-field" min="1990" max={new Date().getFullYear() + 1} 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">{vd.fuelTypeLabel.replace('Type', '').trim() !== '' ? vd.fuelTypeLabel : fl.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}>{fl.categoryLabels[c]}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Daily Rate, License Plate & VIN */}
                <div className="grid gap-3 sm:grid-cols-2">
                  <div>
                    <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.dailyRateLabel}</label>
                    <input type="number" className="input-field" min="0" step="0.01" 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">{vd.licensePlateLabel}</label>
                    <input className="input-field" value={form.licensePlate} onChange={(e) => setForm({ ...form, licensePlate: e.target.value })} />
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.vinLabel}</label>
                  <input className="input-field" placeholder="1HGCM82633A123456" value={form.vin} onChange={(e) => setForm({ ...form, vin: e.target.value })} />
                </div>

                {/* Status */}
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.statusLabel}</label>
                  <select className="input-field" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                    {(['AVAILABLE', 'RESERVED', 'READY', 'RENTED', 'RETURNED', 'NEEDS_CLEANING', 'MAINTENANCE', 'DAMAGE_REVIEW', 'OUT_OF_SERVICE'] as const).map((s) => (
                      <option key={s} value={s}>{fl.statusLabels[s]}</option>
                    ))}
                  </select>
                </div>

                {/* Color & Seats */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.colorLabel}</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="">{vd.selectColor}</option>
                      {PRESET_COLORS.map((c) => <option key={c} value={c}>{c}</option>)}
                      <option value="custom">{vd.other}</option>
                    </select>
                    {colorSelect === 'custom' && (
                      <input className="input-field mt-2" placeholder={vd.typeColor} value={form.color} onChange={(e) => setForm({ ...form, color: e.target.value })} />
                    )}
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.seatsLabel}</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>

                {/* Transmission & Fuel */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.transmissionLabel}</label>
                    <select className="input-field" value={form.transmission} onChange={(e) => setForm({ ...form, transmission: e.target.value })}>
                      <option value="MANUAL">{fl.manual}</option>
                      <option value="AUTOMATIC">{fl.automatic}</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.fuelTypeLabel}</label>
                    <select className="input-field" value={form.fuelType} onChange={(e) => setForm({ ...form, fuelType: e.target.value })}>
                      {(['GASOLINE', 'DIESEL', 'ELECTRIC', 'HYBRID'] as const).map((f) => (
                        <option key={f} value={f}>{fl.fuelTypeLabels[f]}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Odometer */}
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.odometerLabel}</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 className="space-y-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
                  <LocationDropdownField
                    label={fl.pickupLocations}
                    placeholder={fl.pickupLocationsPlaceholder}
                    hint={fl.locationHint}
                    addCustomLabel={fl.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>{fl.allowDifferentDropoff}</span>
                  </label>
                  {form.allowDifferentDropoff && (
                    <LocationDropdownField
                      label={fl.dropoffLocations}
                      placeholder={fl.dropoffLocationsPlaceholder}
                      hint={fl.locationHint}
                      addCustomLabel={fl.addCustomLocation}
                      options={cityOptions}
                      value={parseLocationInput(form.dropoffLocations)}
                      onChange={(locations) => setForm({ ...form, dropoffLocations: formatLocationInput(locations) })}
                    />
                  )}
                </div>

                {/* Notes */}
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">{vd.notesLabel}</label>
                  <textarea className="input-field resize-none" rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} placeholder={vd.optionalNotes} />
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {activeTab === 'maintenance' && (
        <div className="space-y-3">
          <p className="text-sm text-slate-500">{vd.maintenanceIntro}</p>
          {ROUTINE_TYPES.map(({ key, intervalMonths }) => {
            const latest = maintenanceLogs
              .filter((l) => l.type === key)
              .sort((a, b) => new Date(b.performedAt).getTime() - new Date(a.performedAt).getTime())[0]
            return (
              <MaintenanceRow
                key={key}
                vehicleId={params.id}
                typeKey={key}
                intervalMonths={intervalMonths}
                currentMileage={vehicle.mileage}
                log={latest}
                onLogged={fetchMaintenance}
              />
            )
          })}
        </div>
      )}

      {activeTab === 'calendar' && (
        <VehicleCalendar vehicleId={params.id} />
      )}

      {activeTab === 'pricing' && (
        <VehiclePricingManager vehicleId={params.id} />
      )}
    </div>
  )
}
