'use client'

import { useEffect, useRef, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Image from 'next/image'
import { ArrowLeft, Edit, X, Check, Upload, Trash2, CalendarDays, Info } from 'lucide-react'
import { formatCurrency } from '@rentaldrivego/types'
import { apiFetch } from '@/lib/api'
import VehicleCalendar from '@/components/VehicleCalendar'

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
  photos: string[]
  notes: string | null
  isPublished: boolean
}

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 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' : '')
}

type Tab = 'details' | 'calendar'

export default function FleetDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  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)

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

  // photo management
  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])

  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,
      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) : '',
    })
    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('Make is required.'); return }
    if (!form.model)        { setSaveError('Model is required.'); return }
    if (!form.licensePlate) { setSaveError('License plate is required.'); return }
    const rate = parseFloat(form.dailyRate)
    if (isNaN(rate) || rate < 0) { setSaveError('Please enter a valid daily rate.'); 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,
          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,
        }),
      })

      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 ?? 'Failed to save changes.')
      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">Loading vehicle…</div>

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

  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.status}</p>
          </div>
        </div>
        {!editing ? (
          <button onClick={startEdit} className="btn-secondary flex items-center gap-2">
            <Edit className="w-4 h-4" /> Edit
          </button>
        ) : (
          <div className="flex gap-2">
            <button onClick={cancelEdit} className="btn-secondary flex items-center gap-2">
              <X className="w-4 h-4" /> Cancel
            </button>
            <button onClick={handleSave} disabled={saving} className="btn-primary flex items-center gap-2">
              <Check className="w-4 h-4" />
              {saving ? (uploadingPhotos ? 'Uploading photos…' : 'Saving…') : 'Save'}
            </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">
        <button
          onClick={() => setActiveTab('details')}
          className={[
            'flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors',
            activeTab === 'details'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300',
          ].join(' ')}
        >
          <Info className="w-4 h-4" /> Details
        </button>
        <button
          onClick={() => setActiveTab('calendar')}
          className={[
            'flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors',
            activeTab === 'calendar'
              ? 'border-blue-500 text-blue-600'
              : 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300',
          ].join(' ')}
        >
          <CalendarDays className="w-4 h-4" /> Calendar
        </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">Photos</h3>
          <div className="grid gap-4 sm:grid-cols-2">
            {/* Existing photos */}
            {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>
            ))}

            {/* New photo previews (edit mode) */}
            {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-black/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">New</span>
              </div>
            ))}

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

          {/* Upload new photos (edit mode) */}
          {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 ? 'Click to add photos' : `Add more photos (${totalPhotos}/10)`}
              </button>
            </div>
          )}
          {editing && totalPhotos >= 10 && (
            <p className="mt-3 text-xs text-slate-400 text-center">Maximum 10 photos reached.</p>
          )}
        </div>

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

          {!editing || !form ? (
            <dl className="space-y-3 text-sm">
              <div><dt className="text-slate-500">Category</dt><dd className="text-slate-900">{vehicle.category}</dd></div>
              <div><dt className="text-slate-500">Daily rate</dt><dd className="text-slate-900">{formatCurrency(vehicle.dailyRate, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">Status</dt><dd className="text-slate-900">{vehicle.status}</dd></div>
              <div><dt className="text-slate-500">Seats</dt><dd className="text-slate-900">{vehicle.seats}</dd></div>
              <div><dt className="text-slate-500">Transmission</dt><dd className="text-slate-900">{vehicle.transmission}</dd></div>
              <div><dt className="text-slate-500">Fuel type</dt><dd className="text-slate-900">{vehicle.fuelType}</dd></div>
              <div><dt className="text-slate-500">Color</dt><dd className="text-slate-900">{vehicle.color || '—'}</dd></div>
              <div><dt className="text-slate-500">Odometer</dt><dd className="text-slate-900">{vehicle.mileage != null ? `${vehicle.mileage.toLocaleString()} km` : '—'}</dd></div>
              <div><dt className="text-slate-500">Notes</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">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…" 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">Model *</label>
                {!presetModels ? (
                  <input className="input-field" placeholder="Model" 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…" 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">Year *</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">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-3">
                <div>
                  <label className="block text-xs font-medium text-slate-500 mb-1.5">Daily Rate (MAD) *</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">License Plate *</label>
                  <input className="input-field" value={form.licensePlate} onChange={(e) => setForm({ ...form, licensePlate: e.target.value })} />
                </div>
              </div>

              {/* Status */}
              <div>
                <label className="block text-xs font-medium text-slate-500 mb-1.5">Status</label>
                <select className="input-field" value={form.status} onChange={(e) => setForm({ ...form, status: e.target.value })}>
                  {['AVAILABLE', 'RENTED', 'MAINTENANCE', 'OUT_OF_SERVICE'].map((s) => (
                    <option key={s} value={s}>{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">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 color…</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 })} />
                  )}
                </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>

              {/* Transmission & Fuel */}
              <div className="grid grid-cols-2 gap-3">
                <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>
                  <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>

              {/* Odometer */}
              <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>

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

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