'use client'

import { useEffect, useState } from 'react'
import { useParams } from 'next/navigation'
import { formatCurrency } from '@rentaldrivego/types'
import { apiFetch } from '@/lib/api'
import { useDashboardI18n } from '@/components/I18nProvider'
import DamageInspectionCard, { DamageInspection } from '@/components/reservations/DamageInspectionCard'
import ReservationPhotoSection from '@/components/reservations/ReservationPhotoSection'

interface ReservationDetail {
  id: string
  status: string
  source: string
  startDate: string
  endDate: string
  totalAmount: number
  discountAmount: number
  insuranceTotal: number
  additionalDriverTotal: number
  pricingRulesTotal: number
  paymentStatus: string
  depositAmount: number
  pickupLocation: string | null
  returnLocation: string | null
  paymentMode: string | null
  notes: string | null
  contractNumber: string | null
  invoiceNumber: string | null
  damageChargeAmount: number | null
  damageChargeNote: string | null
  pricingRulesApplied: { name: string; amount: number; type: string }[] | null
  customer: {
    firstName: string
    lastName: string
    email: string
    phone: string | null
    driverLicense: string | null
    licenseImageUrl: string | null
    licenseValidationStatus: string
    flagged: boolean
  }
  vehicle: {
    make: string
    model: string
    licensePlate: string
  }
  insurances: { id: string; policyName: string; totalCharge: number }[]
  additionalDrivers: {
    id: string
    firstName: string
    lastName: string
    driverLicense: string
    totalCharge: number
    requiresApproval: boolean
    approvedAt: string | null
    approvalNote: string | null
  }[]
  workflow: {
    contractGenerated: boolean
    closed: boolean
    closedAt: string | null
    closedBy: string | null
    coreEditable: boolean
    returnEditable: boolean
    checkInInspectionEditable: boolean
    checkOutInspectionEditable: boolean
  }
  bookingRequest: {
    stage: string
    companyConfirmed: boolean
    documentsRequired: boolean
    paymentRequired: boolean
    documentsMissing: string[]
  }
}

type EditMode = 'booking' | 'return' | null

type ReservationFormState = {
  startDate: string
  endDate: string
  pickupLocation: string
  returnLocation: string
  depositAmount: string
  paymentMode: string
  notes: string
  damageChargeAmount: string
  damageChargeNote: string
}

const detailCopy = {
  en: {
    editBooking: 'Edit booking',
    saveBooking: 'Save booking',
    editReturn: 'Edit return',
    saveReturn: 'Save return',
    cancelEdit: 'Cancel',
    closeReservation: 'Close reservation',
    bookingDetails: 'Booking details',
    returnDetails: 'Return closing',
    startLabel: 'Start date & time',
    endLabel: 'End date & time',
    pickupLabel: 'Pickup location',
    returnLabel: 'Return location',
    depositLabel: 'Deposit',
    paymentModeLabel: 'Payment mode',
    bookingNotesLabel: 'Booking notes',
    returnChargeLabel: 'Damage charge',
    returnChargeNoteLabel: 'Return note',
    paymentModeEmpty: 'Not set',
    noLocation: 'Not provided',
    failedSave: 'Failed to save reservation',
    failedClose: 'Failed to close reservation',
    contractLockMessage: 'Contract generated. Booking details are locked and remain view-only until the vehicle is returned.',
    activeLockMessage: 'Rental is in progress. Booking details are view-only until the vehicle is returned.',
    returnLockMessage: 'Vehicle returned. Only the return section and the check-out inspection can still be edited before closing the reservation.',
    closedLockMessage: 'Reservation closed. No further editing is allowed.',
    closedMeta: 'Closed',
    checkoutSummary: 'Check-out status',
    checkoutPending: 'Waiting for return edits',
    checkoutReady: 'Return section open',
    checkoutClosed: 'Reservation closed',
    checkInReadOnly: 'Check-in inspection is only editable after the reservation is confirmed and before return.',
    checkOutReadOnly: 'Check-out inspection becomes editable once the vehicle is returned.',
    inspectionClosed: 'This reservation is closed. Inspection edits are disabled.',
    licenseImageLabel: 'License image',
    bookingProgress: 'Booking progress',
    paymentPending: 'Payment or deposit still pending',
    stageLabels: {
      REQUEST_SENT: 'Waiting for company review',
      COMPANY_CONFIRMED: 'Availability confirmed',
      DOCUMENTS_REQUIRED: 'Driver documents missing',
      PAYMENT_REQUIRED: 'Payment or deposit pending',
      BOOKING_CONFIRMED: 'Ready to proceed',
      CANCELLED: 'Request closed',
    },
    missingItems: {
      DATE_OF_BIRTH: 'Date of birth',
      IDENTITY_DOCUMENT: 'Identity document',
      FULL_ADDRESS: 'Full address',
      DRIVER_LICENSE: 'Driver license number',
      LICENSE_IMAGE: 'License image',
      LICENSE_APPROVAL: 'License approval',
    },
    noLicenseImage: 'No license image uploaded.',
    pickupPhotosTitle: 'Pickup photos',
    dropoffPhotosTitle: 'Return photos',
    pickupPhotosReadOnly: 'Pickup photos can be added once the reservation is confirmed.',
    dropoffPhotosReadOnly: 'Return photos become available once the vehicle is checked out.',
    extendBtn: 'Extend rental',
    extendTitle: 'Extend rental',
    extendNewEnd: 'New return date & time',
    extendReason: 'Reason for extension',
    extendReasonPlaceholder: 'e.g. Customer requested 2 extra days',
    extendSubmit: 'Confirm extension',
    extendCancel: 'Cancel',
    extendFailed: 'Failed to extend reservation',
  },
  fr: {
    editBooking: 'Modifier la réservation',
    saveBooking: 'Enregistrer la réservation',
    editReturn: 'Modifier le retour',
    saveReturn: 'Enregistrer le retour',
    cancelEdit: 'Annuler',
    closeReservation: 'Clôturer la réservation',
    bookingDetails: 'Détails de la réservation',
    returnDetails: 'Clôture du retour',
    startLabel: 'Date et heure de départ',
    endLabel: 'Date et heure de retour',
    pickupLabel: 'Lieu de départ',
    returnLabel: 'Lieu de retour',
    depositLabel: 'Dépôt',
    paymentModeLabel: 'Mode de paiement',
    bookingNotesLabel: 'Notes de réservation',
    returnChargeLabel: 'Frais de dommage',
    returnChargeNoteLabel: 'Note de retour',
    paymentModeEmpty: 'Non défini',
    noLocation: 'Non renseigné',
    failedSave: 'Échec de la sauvegarde de la réservation',
    failedClose: 'Échec de la clôture de la réservation',
    contractLockMessage: 'Le contrat a été généré. Les détails de la réservation sont verrouillés jusqu’au retour du véhicule.',
    activeLockMessage: 'La location est en cours. Les détails de la réservation sont en lecture seule jusqu’au retour du véhicule.',
    returnLockMessage: 'Le véhicule est de retour. Seule la section de retour et l’inspection de retour peuvent encore être modifiées avant la clôture.',
    closedLockMessage: 'La réservation est clôturée. Aucune autre modification n’est autorisée.',
    closedMeta: 'Clôturée',
    checkoutSummary: 'Statut du retour',
    checkoutPending: 'En attente des modifications de retour',
    checkoutReady: 'Section retour ouverte',
    checkoutClosed: 'Réservation clôturée',
    checkInReadOnly: 'L’inspection de départ est modifiable après confirmation et avant le retour.',
    checkOutReadOnly: 'L’inspection de retour devient modifiable une fois le véhicule retourné.',
    inspectionClosed: 'Cette réservation est clôturée. Les modifications d’inspection sont désactivées.',
    licenseImageLabel: 'Image du permis',
    bookingProgress: 'Progression de la réservation',
    paymentPending: 'Paiement ou dépôt encore en attente',
    stageLabels: {
      REQUEST_SENT: 'En attente de validation',
      COMPANY_CONFIRMED: 'Disponibilité confirmée',
      DOCUMENTS_REQUIRED: 'Documents conducteur manquants',
      PAYMENT_REQUIRED: 'Paiement ou dépôt en attente',
      BOOKING_CONFIRMED: 'Prêt à avancer',
      CANCELLED: 'Demande clôturée',
    },
    missingItems: {
      DATE_OF_BIRTH: 'Date de naissance',
      IDENTITY_DOCUMENT: 'Pièce d’identité',
      FULL_ADDRESS: 'Adresse complète',
      DRIVER_LICENSE: 'Numéro du permis',
      LICENSE_IMAGE: 'Image du permis',
      LICENSE_APPROVAL: 'Validation du permis',
    },
    noLicenseImage: 'Aucune image de permis téléversée.',
    pickupPhotosTitle: 'Photos de départ',
    dropoffPhotosTitle: 'Photos de retour',
    pickupPhotosReadOnly: 'Les photos de départ sont disponibles après confirmation de la réservation.',
    dropoffPhotosReadOnly: 'Les photos de retour sont disponibles après la restitution du véhicule.',
    extendBtn: 'Prolonger la location',
    extendTitle: 'Prolonger la location',
    extendNewEnd: 'Nouvelle date de retour',
    extendReason: 'Motif de prolongation',
    extendReasonPlaceholder: 'ex. Le client a demandé 2 jours supplémentaires',
    extendSubmit: 'Confirmer la prolongation',
    extendCancel: 'Annuler',
    extendFailed: 'Échec de la prolongation',
  },
  ar: {
    editBooking: 'تعديل الحجز',
    saveBooking: 'حفظ الحجز',
    editReturn: 'تعديل الإرجاع',
    saveReturn: 'حفظ الإرجاع',
    cancelEdit: 'إلغاء',
    closeReservation: 'إغلاق الحجز',
    bookingDetails: 'تفاصيل الحجز',
    returnDetails: 'إقفال الإرجاع',
    startLabel: 'تاريخ ووقت البداية',
    endLabel: 'تاريخ ووقت النهاية',
    pickupLabel: 'موقع الاستلام',
    returnLabel: 'موقع الإرجاع',
    depositLabel: 'العربون',
    paymentModeLabel: 'طريقة الدفع',
    bookingNotesLabel: 'ملاحظات الحجز',
    returnChargeLabel: 'رسوم الأضرار',
    returnChargeNoteLabel: 'ملاحظة الإرجاع',
    paymentModeEmpty: 'غير محدد',
    noLocation: 'غير متوفر',
    failedSave: 'فشل حفظ الحجز',
    failedClose: 'فشل إغلاق الحجز',
    contractLockMessage: 'تم إنشاء العقد. تفاصيل الحجز مقفلة وتبقى للعرض فقط حتى عودة السيارة.',
    activeLockMessage: 'التأجير قيد التنفيذ. تفاصيل الحجز للعرض فقط حتى عودة السيارة.',
    returnLockMessage: 'تمت إعادة السيارة. يمكن تعديل قسم الإرجاع وفحص الإرجاع فقط قبل إغلاق الحجز.',
    closedLockMessage: 'تم إغلاق الحجز. لا يُسمح بأي تعديل إضافي.',
    closedMeta: 'مغلق',
    checkoutSummary: 'حالة الإرجاع',
    checkoutPending: 'بانتظار تعديلات الإرجاع',
    checkoutReady: 'قسم الإرجاع مفتوح',
    checkoutClosed: 'تم إغلاق الحجز',
    checkInReadOnly: 'يمكن تعديل فحص الاستلام بعد تأكيد الحجز وقبل الإرجاع فقط.',
    checkOutReadOnly: 'يصبح فحص الإرجاع قابلاً للتعديل بعد عودة السيارة.',
    inspectionClosed: 'هذا الحجز مغلق. تم تعطيل تعديل الفحص.',
    licenseImageLabel: 'صورة الرخصة',
    bookingProgress: 'تقدم الحجز',
    paymentPending: 'الدفع أو العربون ما زال معلقاً',
    stageLabels: {
      REQUEST_SENT: 'بانتظار مراجعة الشركة',
      COMPANY_CONFIRMED: 'تم تأكيد التوفر',
      DOCUMENTS_REQUIRED: 'وثائق السائق ناقصة',
      PAYMENT_REQUIRED: 'الدفع أو العربون معلق',
      BOOKING_CONFIRMED: 'جاهز للمتابعة',
      CANCELLED: 'تم إغلاق الطلب',
    },
    missingItems: {
      DATE_OF_BIRTH: 'تاريخ الميلاد',
      IDENTITY_DOCUMENT: 'وثيقة الهوية',
      FULL_ADDRESS: 'العنوان الكامل',
      DRIVER_LICENSE: 'رقم الرخصة',
      LICENSE_IMAGE: 'صورة الرخصة',
      LICENSE_APPROVAL: 'اعتماد الرخصة',
    },
    noLicenseImage: 'لم يتم رفع صورة الرخصة.',
    pickupPhotosTitle: 'صور الاستلام',
    dropoffPhotosTitle: 'صور الإرجاع',
    pickupPhotosReadOnly: 'تتوفر صور الاستلام بعد تأكيد الحجز.',
    dropoffPhotosReadOnly: 'تتوفر صور الإرجاع بعد إعادة السيارة.',
    extendBtn: 'تمديد التأجير',
    extendTitle: 'تمديد التأجير',
    extendNewEnd: 'تاريخ الإرجاع الجديد',
    extendReason: 'سبب التمديد',
    extendReasonPlaceholder: 'مثال: طلب العميل يومين إضافيين',
    extendSubmit: 'تأكيد التمديد',
    extendCancel: 'إلغاء',
    extendFailed: 'فشل تمديد الحجز',
  },
} as const

function toDateTimeInputValue(iso: string) {
  const date = new Date(iso)
  const offset = date.getTimezoneOffset()
  return new Date(date.getTime() - offset * 60_000).toISOString().slice(0, 16)
}

function toFormState(reservation: ReservationDetail): ReservationFormState {
  return {
    startDate: toDateTimeInputValue(reservation.startDate),
    endDate: toDateTimeInputValue(reservation.endDate),
    pickupLocation: reservation.pickupLocation ?? '',
    returnLocation: reservation.returnLocation ?? '',
    depositAmount: String(reservation.depositAmount ?? 0),
    paymentMode: reservation.paymentMode ?? '',
    notes: reservation.notes ?? '',
    damageChargeAmount: reservation.damageChargeAmount !== null && reservation.damageChargeAmount !== undefined ? String(reservation.damageChargeAmount) : '',
    damageChargeNote: reservation.damageChargeNote ?? '',
  }
}

function toIsoString(value: string) {
  return new Date(value).toISOString()
}

export default function ReservationDetailPage() {
  const params = useParams<{ id: string }>()
  const { dict, language } = useDashboardI18n()
  const r = dict.reservations
  const copy = detailCopy[language]
  const localeCode = language === 'fr' ? 'fr-FR' : language === 'ar' ? 'ar-MA' : 'en-US'

  const [reservation, setReservation] = useState<ReservationDetail | null>(null)
  const [inspections, setInspections] = useState<DamageInspection[]>([])
  const [form, setForm] = useState<ReservationFormState | null>(null)
  const [editMode, setEditMode] = useState<EditMode>(null)
  const [error, setError] = useState<string | null>(null)
  const [actionError, setActionError] = useState<string | null>(null)
  const [acting, setActing] = useState(false)
  const [showExtend, setShowExtend] = useState(false)
  const [extendForm, setExtendForm] = useState({ newEndDate: '', reason: '' })
  const [extendError, setExtendError] = useState<string | null>(null)

  async function loadReservation() {
    try {
      const [reservationData, inspectionData] = await Promise.all([
        apiFetch<ReservationDetail>(`/reservations/${params.id}`),
        apiFetch<DamageInspection[]>(`/reservations/${params.id}/inspections`),
      ])
      setReservation(reservationData)
      setInspections(inspectionData)
      setForm(toFormState(reservationData))
      setEditMode(null)
      setError(null)
    } catch (err: any) {
      setError(err.message ?? r.failedToLoad)
    }
  }

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

  async function runAction(action: 'confirm' | 'checkin' | 'checkout') {
    setActing(true)
    setActionError(null)
    const errorMsg = action === 'confirm' ? r.failedConfirm : action === 'checkin' ? r.failedCheckIn : r.failedCheckOut
    try {
      await apiFetch(`/reservations/${params.id}/${action}`, {
        method: 'POST',
        body: JSON.stringify({}),
      })
      await loadReservation()
    } catch (err: any) {
      setActionError(err.message ?? errorMsg)
    } finally {
      setActing(false)
    }
  }

  async function saveReservation(mode: Exclude<EditMode, null>) {
    if (!form) return

    setActing(true)
    setActionError(null)
    try {
      const payload = mode === 'booking'
        ? {
            startDate: toIsoString(form.startDate),
            endDate: toIsoString(form.endDate),
            pickupLocation: form.pickupLocation || null,
            returnLocation: form.returnLocation || null,
            depositAmount: Number(form.depositAmount || 0),
            paymentMode: form.paymentMode || null,
            notes: form.notes || null,
          }
        : {
            returnLocation: form.returnLocation || null,
            damageChargeAmount: form.damageChargeAmount ? Number(form.damageChargeAmount) : 0,
            damageChargeNote: form.damageChargeNote || null,
          }

      await apiFetch(`/reservations/${params.id}`, {
        method: 'PATCH',
        body: JSON.stringify(payload),
      })
      await loadReservation()
    } catch (err: any) {
      setActionError(err.message ?? copy.failedSave)
    } finally {
      setActing(false)
    }
  }

  async function closeReservation() {
    setActing(true)
    setActionError(null)
    try {
      await apiFetch(`/reservations/${params.id}/close`, {
        method: 'POST',
        body: JSON.stringify({}),
      })
      await loadReservation()
    } catch (err: any) {
      setActionError(err.message ?? copy.failedClose)
    } finally {
      setActing(false)
    }
  }

  async function approveDriver(driverId: string) {
    setActing(true)
    setActionError(null)
    try {
      await apiFetch(`/reservations/${params.id}/additional-drivers/${driverId}/approval`, {
        method: 'PATCH',
        body: JSON.stringify({ approved: true }),
      })
      await loadReservation()
    } catch (err: any) {
      setActionError(err.message ?? r.failedApproveDriver)
    } finally {
      setActing(false)
    }
  }

  async function submitExtend() {
    if (!extendForm.newEndDate || !extendForm.reason.trim()) return
    setActing(true)
    setExtendError(null)
    try {
      await apiFetch(`/reservations/${params.id}/extend`, {
        method: 'POST',
        body: JSON.stringify({ newEndDate: new Date(extendForm.newEndDate).toISOString(), reason: extendForm.reason }),
      })
      setShowExtend(false)
      setExtendForm({ newEndDate: '', reason: '' })
      await loadReservation()
    } catch (err: any) {
      setExtendError(err.message ?? copy.extendFailed)
    } finally {
      setActing(false)
    }
  }

  const formatDate = (iso: string) =>
    new Date(iso).toLocaleDateString(localeCode, { month: 'short', day: 'numeric', year: 'numeric' })

  if (error) return <div className="card p-6 text-sm text-red-600">{error}</div>
  if (!reservation || !form) return <div className="card p-6 text-sm text-slate-500">{r.loadingReservation}</div>

  const checkinInspection = inspections.find((inspection) => inspection.type === 'CHECKIN')
  const checkoutInspection = inspections.find((inspection) => inspection.type === 'CHECKOUT')
  const bookingInputsDisabled = editMode !== 'booking'
  const returnInputsDisabled = editMode !== 'return'

  let workflowMessage = ''
  if (reservation.workflow.closed) workflowMessage = copy.closedLockMessage
  else if (reservation.workflow.returnEditable) workflowMessage = copy.returnLockMessage
  else if (reservation.workflow.contractGenerated) workflowMessage = copy.contractLockMessage
  else if (reservation.status === 'ACTIVE') workflowMessage = copy.activeLockMessage

  const checkInReadOnlyMessage = reservation.workflow.closed
    ? copy.inspectionClosed
    : copy.checkInReadOnly
  const checkOutReadOnlyMessage = reservation.workflow.closed
    ? copy.inspectionClosed
    : copy.checkOutReadOnly

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h2 className="text-xl font-semibold text-slate-900">Reservation {reservation.id.slice(-8).toUpperCase()}</h2>
          <p className="mt-1 text-sm text-slate-500">{reservation.source} · {reservation.status} · {reservation.paymentStatus}</p>
          {reservation.workflow.closedAt && (
            <p className="mt-2 text-xs text-slate-500">
              {copy.closedMeta} {formatDate(reservation.workflow.closedAt)}{reservation.workflow.closedBy ? ` · ${reservation.workflow.closedBy}` : ''}
            </p>
          )}
        </div>
        <div className="flex flex-wrap gap-3">
          {editMode === null && reservation.workflow.coreEditable && (
            <button disabled={acting} onClick={() => setEditMode('booking')} className="btn-secondary">
              {copy.editBooking}
            </button>
          )}
          {editMode === 'booking' && (
            <>
              <button disabled={acting} onClick={() => saveReservation('booking')} className="btn-primary">
                {acting ? r.working : copy.saveBooking}
              </button>
              <button disabled={acting} onClick={() => { setForm(toFormState(reservation)); setEditMode(null) }} className="btn-secondary">
                {copy.cancelEdit}
              </button>
            </>
          )}
          {editMode === null && reservation.workflow.returnEditable && (
            <>
              <button disabled={acting} onClick={() => setEditMode('return')} className="btn-secondary">
                {copy.editReturn}
              </button>
              <button disabled={acting} onClick={closeReservation} className="btn-primary">
                {acting ? r.working : copy.closeReservation}
              </button>
            </>
          )}
          {editMode === 'return' && (
            <>
              <button disabled={acting} onClick={() => saveReservation('return')} className="btn-primary">
                {acting ? r.working : copy.saveReturn}
              </button>
              <button disabled={acting} onClick={() => { setForm(toFormState(reservation)); setEditMode(null) }} className="btn-secondary">
                {copy.cancelEdit}
              </button>
            </>
          )}
          {reservation.status === 'DRAFT' && (
            <button disabled={acting} onClick={() => runAction('confirm')} className="btn-primary">
              {acting ? r.working : r.confirmReservation}
            </button>
          )}
          {reservation.status === 'CONFIRMED' && (
            <button disabled={acting} onClick={() => runAction('checkin')} className="btn-primary">
              {acting ? r.working : r.checkInVehicle}
            </button>
          )}
          {reservation.status === 'ACTIVE' && (
            <button disabled={acting} onClick={() => runAction('checkout')} className="btn-primary">
              {acting ? r.working : r.checkOutVehicle}
            </button>
          )}
          {['CONFIRMED', 'ACTIVE'].includes(reservation.status) && !reservation.workflow.closed && (
            <button disabled={acting} onClick={() => { setShowExtend(true); setExtendError(null) }} className="btn-secondary">
              {copy.extendBtn}
            </button>
          )}
        </div>
      </div>

      {showExtend && (
        <div className="card border border-blue-200 bg-blue-50 p-5 space-y-4">
          <h4 className="text-sm font-semibold text-slate-900">{copy.extendTitle}</h4>
          <div className="grid gap-4 sm:grid-cols-2">
            <div>
              <label className="mb-1.5 block text-xs font-medium text-slate-700">{copy.extendNewEnd}</label>
              <input
                type="datetime-local"
                className="input-field"
                value={extendForm.newEndDate}
                onChange={(e) => setExtendForm((f) => ({ ...f, newEndDate: e.target.value }))}
              />
            </div>
            <div>
              <label className="mb-1.5 block text-xs font-medium text-slate-700">{copy.extendReason}</label>
              <input
                className="input-field"
                placeholder={copy.extendReasonPlaceholder}
                value={extendForm.reason}
                onChange={(e) => setExtendForm((f) => ({ ...f, reason: e.target.value }))}
              />
            </div>
          </div>
          {extendError && <p className="text-xs text-red-600">{extendError}</p>}
          <div className="flex gap-3">
            <button disabled={acting} onClick={submitExtend} className="btn-primary text-sm">
              {acting ? r.working : copy.extendSubmit}
            </button>
            <button onClick={() => { setShowExtend(false); setExtendForm({ newEndDate: '', reason: '' }) }} className="btn-secondary text-sm">
              {copy.extendCancel}
            </button>
          </div>
        </div>
      )}

      {workflowMessage && (
        <div className="card border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700">
          {workflowMessage}
        </div>
      )}

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

      {reservation.source === 'CARPLACE' ? (
        <div className="card p-6">
          <h3 className="mb-4 text-base font-semibold text-slate-900">{copy.bookingProgress}</h3>
          <div className="flex flex-wrap items-center gap-2">
            <span className="badge-gray">
              {copy.stageLabels[reservation.bookingRequest.stage as keyof typeof copy.stageLabels] ?? reservation.bookingRequest.stage}
            </span>
            {reservation.bookingRequest.paymentRequired ? (
              <span className="rounded-full bg-purple-100 px-2.5 py-1 text-xs font-semibold text-purple-800">
                {copy.paymentPending}
              </span>
            ) : null}
          </div>
          {reservation.bookingRequest.documentsMissing.length > 0 ? (
            <div className="mt-4 flex flex-wrap gap-2">
              {reservation.bookingRequest.documentsMissing.map((item) => (
                <span key={item} className="rounded-full bg-amber-100 px-2.5 py-1 text-xs font-semibold text-amber-800">
                  {copy.missingItems[item as keyof typeof copy.missingItems] ?? item}
                </span>
              ))}
            </div>
          ) : null}
        </div>
      ) : null}

      <div className="grid gap-6 lg:grid-cols-2">
        <div className="card p-6">
          <h3 className="mb-4 text-base font-semibold text-slate-900">{r.sectionCustomer}</h3>
          <div className="space-y-2 text-sm">
            <p className="font-medium text-slate-900">{reservation.customer.firstName} {reservation.customer.lastName}</p>
            <p className="text-slate-600">{reservation.customer.email}</p>
            <p className="text-slate-600">{reservation.customer.phone ?? r.noPhone}</p>
            <p className="text-slate-600">{r.licenseLabel} {reservation.customer.driverLicense ?? r.notCaptured}</p>
            <div className="pt-2">
              <p className="text-slate-600">{copy.licenseImageLabel}</p>
              {reservation.customer.licenseImageUrl ? (
                <a href={reservation.customer.licenseImageUrl} target="_blank" rel="noreferrer" className="mt-2 block max-w-sm">
                  <img
                    src={reservation.customer.licenseImageUrl}
                    alt="Driver license"
                    className="h-40 w-full rounded-xl border border-slate-200 object-cover"
                  />
                </a>
              ) : (
                <p className="text-xs text-slate-500">{copy.noLicenseImage}</p>
              )}
            </div>
            <div className="flex flex-wrap gap-2 pt-2">
              <span className="badge-gray">{reservation.customer.licenseValidationStatus}</span>
              {reservation.customer.flagged && <span className="badge-red">{r.flaggedBadge}</span>}
            </div>
          </div>
        </div>

        <div className="card p-6">
          <h3 className="mb-4 text-base font-semibold text-slate-900">{r.sectionVehicle}</h3>
          <div className="space-y-2 text-sm text-slate-600">
            <p className="font-medium text-slate-900">{reservation.vehicle.make} {reservation.vehicle.model}</p>
            <p>{reservation.vehicle.licensePlate}</p>
            <p>{formatDate(reservation.startDate)} - {formatDate(reservation.endDate)}</p>
            <p>{copy.paymentModeLabel}: <span className="font-medium text-slate-900">{reservation.paymentMode || copy.paymentModeEmpty}</span></p>
          </div>
        </div>
      </div>

      <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
        <div className="space-y-6">
          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">{copy.bookingDetails}</h3>
            <div className="grid gap-4 md:grid-cols-2">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.startLabel}</label>
                <input
                  type="datetime-local"
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.startDate}
                  disabled={bookingInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, startDate: e.target.value } : current)}
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.endLabel}</label>
                <input
                  type="datetime-local"
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.endDate}
                  disabled={bookingInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, endDate: e.target.value } : current)}
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.pickupLabel}</label>
                <input
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.pickupLocation}
                  disabled={bookingInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, pickupLocation: e.target.value } : current)}
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.returnLabel}</label>
                <input
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.returnLocation}
                  disabled={bookingInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, returnLocation: e.target.value } : current)}
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.depositLabel}</label>
                <input
                  type="number"
                  min="0"
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.depositAmount}
                  disabled={bookingInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, depositAmount: e.target.value } : current)}
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.paymentModeLabel}</label>
                <input
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.paymentMode}
                  disabled={bookingInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, paymentMode: e.target.value } : current)}
                />
              </div>
            </div>
            <div className="mt-4">
              <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.bookingNotesLabel}</label>
              <textarea
                className="input-field min-h-24 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                value={form.notes}
                disabled={bookingInputsDisabled}
                onChange={(e) => setForm((current) => current ? { ...current, notes: e.target.value } : current)}
              />
            </div>
          </div>

          <ReservationPhotoSection
            reservationId={reservation.id}
            type="PICKUP"
            editable={reservation.workflow.checkInInspectionEditable}
            title={copy.pickupPhotosTitle}
            readOnlyMessage={copy.pickupPhotosReadOnly}
          />

          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">{copy.returnDetails}</h3>
            <div className="grid gap-4 md:grid-cols-2">
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.returnLabel}</label>
                <input
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.returnLocation}
                  disabled={returnInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, returnLocation: e.target.value } : current)}
                />
              </div>
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.returnChargeLabel}</label>
                <input
                  type="number"
                  min="0"
                  className="input-field disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                  value={form.damageChargeAmount}
                  disabled={returnInputsDisabled}
                  onChange={(e) => setForm((current) => current ? { ...current, damageChargeAmount: e.target.value } : current)}
                />
              </div>
            </div>
            <div className="mt-4">
              <label className="mb-1.5 block text-sm font-medium text-slate-700">{copy.returnChargeNoteLabel}</label>
              <textarea
                className="input-field min-h-24 disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500"
                value={form.damageChargeNote}
                disabled={returnInputsDisabled}
                onChange={(e) => setForm((current) => current ? { ...current, damageChargeNote: e.target.value } : current)}
              />
            </div>
            <div className="mt-4 rounded-2xl border border-slate-200 px-4 py-3 text-sm text-slate-600">
              <span className="font-medium text-slate-900">{copy.checkoutSummary}:</span>{' '}
              {reservation.workflow.closed
                ? copy.checkoutClosed
                : reservation.workflow.returnEditable
                ? copy.checkoutReady
                : copy.checkoutPending}
            </div>
          </div>

          <ReservationPhotoSection
            reservationId={reservation.id}
            type="DROPOFF"
            editable={reservation.workflow.checkOutInspectionEditable}
            title={copy.dropoffPhotosTitle}
            readOnlyMessage={copy.dropoffPhotosReadOnly}
          />

          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">{r.sectionCharges}</h3>
            <dl className="grid gap-3 text-sm sm:grid-cols-2">
              <div><dt className="text-slate-500">{r.chargeDiscount}</dt><dd className="text-slate-900">{formatCurrency(reservation.discountAmount, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">{r.chargeInsurance}</dt><dd className="text-slate-900">{formatCurrency(reservation.insuranceTotal, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">{r.chargeAdditionalDrivers}</dt><dd className="text-slate-900">{formatCurrency(reservation.additionalDriverTotal, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">{r.chargePricingAdjustments}</dt><dd className="text-slate-900">{formatCurrency(reservation.pricingRulesTotal, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">{r.chargeGrandTotal}</dt><dd className="font-semibold text-slate-900">{formatCurrency(reservation.totalAmount, 'MAD')}</dd></div>
              <div><dt className="text-slate-500">{copy.returnChargeLabel}</dt><dd className="text-slate-900">{formatCurrency(reservation.damageChargeAmount ?? 0, 'MAD')}</dd></div>
            </dl>

            {reservation.insurances.length > 0 && (
              <div className="mt-5">
                <p className="mb-2 text-sm font-semibold text-slate-900">{r.appliedInsurance}</p>
                <div className="space-y-2">
                  {reservation.insurances.map((insurance) => (
                    <div key={insurance.id} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3 text-sm">
                      <span className="text-slate-700">{insurance.policyName}</span>
                      <span className="font-semibold text-slate-900">{formatCurrency(insurance.totalCharge, 'MAD')}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {reservation.pricingRulesApplied && reservation.pricingRulesApplied.length > 0 && (
              <div className="mt-5">
                <p className="mb-2 text-sm font-semibold text-slate-900">{r.pricingRulesApplied}</p>
                <div className="space-y-2">
                  {reservation.pricingRulesApplied.map((rule) => (
                    <div key={`${rule.name}-${rule.amount}`} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3 text-sm">
                      <span className="text-slate-700">{rule.name}</span>
                      <span className={rule.amount < 0 ? 'font-semibold text-emerald-700' : 'font-semibold text-orange-700'}>
                        {rule.amount < 0 ? '-' : '+'}{formatCurrency(Math.abs(rule.amount), 'MAD')}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          <DamageInspectionCard
            reservationId={reservation.id}
            type="CHECKIN"
            initialInspection={checkinInspection}
            editable={reservation.workflow.checkInInspectionEditable}
            readOnlyMessage={checkInReadOnlyMessage}
            onSaved={(inspection) => setInspections((current) => [...current.filter((item) => item.type !== inspection.type), inspection])}
          />
          <DamageInspectionCard
            reservationId={reservation.id}
            type="CHECKOUT"
            initialInspection={checkoutInspection}
            comparisonPoints={checkinInspection?.damagePoints ?? []}
            editable={reservation.workflow.checkOutInspectionEditable}
            readOnlyMessage={checkOutReadOnlyMessage}
            onSaved={(inspection) => setInspections((current) => [...current.filter((item) => item.type !== inspection.type), inspection])}
          />
        </div>

        <div className="space-y-6">
          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">{r.sectionAdditionalDrivers}</h3>
            <div className="space-y-3">
              {reservation.additionalDrivers.map((driver) => (
                <div key={driver.id} className="rounded-2xl border border-slate-200 p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="font-medium text-slate-900">{driver.firstName} {driver.lastName}</p>
                      <p className="text-sm text-slate-500">{r.driverLicenseLabel} {driver.driverLicense}</p>
                      <p className="mt-1 text-sm text-slate-600">{r.driverChargeLabel} {formatCurrency(driver.totalCharge, 'MAD')}</p>
                    </div>
                    {driver.requiresApproval && !driver.approvedAt ? (
                      <button onClick={() => approveDriver(driver.id)} disabled={acting} className="rounded-full bg-orange-600 px-4 py-2 text-xs font-semibold text-white">
                        {r.approveBtn}
                      </button>
                    ) : (
                      <span className={driver.approvedAt ? 'badge-green' : 'badge-gray'}>
                        {driver.approvedAt ? r.approvedBadge : r.noApprovalNeeded}
                      </span>
                    )}
                  </div>
                  {driver.approvalNote && <p className="mt-2 text-xs text-orange-700">{driver.approvalNote}</p>}
                </div>
              ))}
              {reservation.additionalDrivers.length === 0 && (
                <div className="text-sm text-slate-400">{r.noAdditionalDrivers}</div>
              )}
            </div>
          </div>

          <div className="card p-6">
            <h3 className="mb-4 text-base font-semibold text-slate-900">{r.sectionInspectionSummary}</h3>
            <div className="space-y-3 text-sm">
              <div className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <span className="text-slate-600">{r.checkInInspectionLabel}</span>
                <span className={checkinInspection ? 'badge-green' : 'badge-gray'}>{checkinInspection ? r.savedBadge : r.pendingBadge}</span>
              </div>
              <div className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <span className="text-slate-600">{r.checkOutInspectionLabel}</span>
                <span className={checkoutInspection ? 'badge-green' : 'badge-gray'}>{checkoutInspection ? r.savedBadge : r.pendingBadge}</span>
              </div>
              <div className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <span className="text-slate-600">{copy.returnLabel}</span>
                <span className="font-medium text-slate-900">{reservation.returnLocation ?? copy.noLocation}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
