import { bilingualPrimary } from '@/components/ui/BilingualInput'
import type { ReservationWizardCopy } from './reservationWizard.copy'
import type { Customer, ReservationDraft, Vehicle, WizardStepId } from './reservationWizard.types'

function display(value: string | null | undefined, fallback: string) {
  return value?.trim() ? value : fallback
}

export function ReservationReview({
  copy,
  draft,
  customers,
  vehicles,
  localeCode,
  onEdit,
}: {
  copy: ReservationWizardCopy
  draft: ReservationDraft
  customers: Customer[]
  vehicles: Vehicle[]
  localeCode: string
  onEdit: (step: WizardStepId) => void
}) {
  const selectedCustomer = customers.find((customer) => customer.id === draft.customer.selectedCustomerId)
  const selectedVehicle = vehicles.find((vehicle) => vehicle.id === draft.rental.vehicleId)
  const formatDateTime = (value: string) => value ? new Date(value).toLocaleString(localeCode, { dateStyle: 'medium', timeStyle: 'short' }) : copy.summaryEmpty
  const sections: Array<{ step: WizardStepId; title: string; rows: Array<[string, string]> }> = [
    {
      step: 'customer',
      title: copy.customer,
      rows: [
        [copy.customer, draft.customer.mode === 'existing' ? display(selectedCustomer ? `${selectedCustomer.firstName} ${selectedCustomer.lastName}` : '', copy.summaryEmpty) : `${bilingualPrimary(draft.customer.firstName)} ${bilingualPrimary(draft.customer.lastName)}`],
        [copy.email, display(draft.customer.email, copy.summaryEmpty)],
        [copy.phone, display(draft.customer.phone, copy.summaryEmpty)],
      ],
    },
    {
      step: 'identity',
      title: copy.identity,
      rows: [
        [copy.dateOfBirth, display(draft.identity.dateOfBirth, copy.summaryEmpty)],
        [copy.nationality, display(draft.identity.nationality, copy.summaryEmpty)],
        [copy.identityDocumentNumber, display(draft.identity.identityDocumentNumber, copy.summaryEmpty)],
        [copy.fullAddress, display(draft.identity.fullAddress, copy.summaryEmpty)],
        [copy.internationalLicenseNumber, display(draft.identity.internationalLicenseNumber, copy.summaryEmpty)],
      ],
    },
    {
      step: 'license',
      title: copy.license,
      rows: [
        [copy.driverLicenseNumber, display(draft.license.number, copy.summaryEmpty)],
        [copy.licenseCountry, display(draft.license.country, copy.summaryEmpty)],
        [copy.licenseIssuedAt, display(draft.license.issuedAt, copy.summaryEmpty)],
        [copy.licenseExpiry, display(draft.license.expiry, copy.summaryEmpty)],
        [copy.licenseCategory, display(draft.license.category, copy.summaryEmpty)],
        [copy.licenseImage, draft.license.newImageFile ? draft.license.newImageFile.name : draft.license.existingImageUrl ? copy.licenseImageCurrent : copy.noLicenseImage],
      ],
    },
    {
      step: 'rental',
      title: copy.rental,
      rows: [
        [copy.vehicle, selectedVehicle ? `${selectedVehicle.make} ${selectedVehicle.model} · ${selectedVehicle.licensePlate}` : copy.summaryEmpty],
        [copy.startDate, formatDateTime(draft.rental.startDate)],
        [copy.endDate, formatDateTime(draft.rental.endDate)],
        [copy.pickup, display(draft.rental.pickupLocation, copy.summaryEmpty)],
        [copy.return, display(draft.rental.returnLocation, copy.summaryEmpty)],
      ],
    },
    {
      step: 'payment',
      title: copy.payment,
      rows: [
        [copy.deposit, display(draft.payment.depositAmount, copy.summaryEmpty)],
        [copy.paymentMode, copy.paymentModes[draft.payment.paymentMode] ?? draft.payment.paymentMode],
        [copy.additionalDriverInfo, draft.additionalDrivers.length ? String(draft.additionalDrivers.length) : copy.summaryEmpty],
        [copy.notes, display(draft.payment.notes, copy.summaryEmpty)],
      ],
    },
  ]

  return (
    <div className="space-y-4">
      {sections.map((section) => (
        <section key={section.step} className="rounded-lg border border-slate-200 p-4">
          <div className="flex items-center justify-between gap-3">
            <h3 className="text-sm font-semibold text-slate-900">{section.title}</h3>
            <button type="button" className="text-sm font-semibold text-blue-700 hover:underline" onClick={() => onEdit(section.step)}>
              {copy.edit}
            </button>
          </div>
          <dl className="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2">
            {section.rows.map(([label, value]) => (
              <div key={`${section.step}-${label}`}>
                <dt className="text-xs font-medium text-slate-500">{label}</dt>
                <dd className="mt-0.5 text-sm text-slate-900">{value}</dd>
              </div>
            ))}
          </dl>
        </section>
      ))}
      {draft.additionalDrivers.map((driver, index) => (
        <section key={driver.id} className="rounded-lg border border-slate-200 p-4">
          <h3 className="text-sm font-semibold text-slate-900">
            {copy.additionalDriverInfo} {index + 1}
          </h3>
          <dl className="mt-3 grid grid-cols-1 gap-3 md:grid-cols-2">
            <div>
              <dt className="text-xs font-medium text-slate-500">{copy.firstName}</dt>
              <dd className="mt-0.5 text-sm text-slate-900">{display(bilingualPrimary(driver.firstName), copy.summaryEmpty)}</dd>
            </div>
            <div>
              <dt className="text-xs font-medium text-slate-500">{copy.lastName}</dt>
              <dd className="mt-0.5 text-sm text-slate-900">{display(bilingualPrimary(driver.lastName), copy.summaryEmpty)}</dd>
            </div>
            <div>
              <dt className="text-xs font-medium text-slate-500">{copy.driverLicenseNumber}</dt>
              <dd className="mt-0.5 text-sm text-slate-900">{display(driver.driverLicense, copy.summaryEmpty)}</dd>
            </div>
          </dl>
        </section>
      ))}
    </div>
  )
}
