'use client'

import { useState } from 'react'
import { marketplacePost } from '@/lib/api'
import { useMarketplacePreferences } from '@/components/MarketplaceShell'

type Props = {
  vehicleId: string
  companySlug: string
  dailyRate: number
  pickupLocations: string[]
  allowDifferentDropoff: boolean
  dropoffLocations: string[]
}

const copy = {
  en: {
    title: 'Reserve this vehicle',
    renterIdentity: 'Renter identity',
    firstName: 'First name',
    lastName: 'Last name',
    dateOfBirth: 'Date of birth',
    nationality: 'Nationality',
    identityDocumentNumber: 'CIN / Passport number',
    fullAddress: 'Full address',
    driverLicenseSection: 'Driver license',
    email: 'Email',
    phone: 'Phone',
    driverLicense: 'License number',
    licenseIssuedAt: 'Issue date',
    licenseExpiry: 'Expiry date',
    licenseCountry: 'Country of issue',
    licenseCategory: 'License category',
    internationalLicenseNumber: 'International permit number (optional)',
    pickupLocation: 'Pick-up location',
    returnLocation: 'Drop-off location',
    sameDropoff: 'Same drop-off',
    differentDropoff: 'Different drop-off',
    sameAsPickup: 'Return to the same location',
    startDate: 'Pick-up date',
    endDate: 'Return date',
    notes: 'Notes (optional)',
    submit: 'Request reservation',
    submitting: 'Sending…',
    successTitle: 'Request received!',
    successBody: 'Your reservation request has been sent. The company will review it and contact you shortly.',
    invalidDates: 'Return date must be after pick-up date.',
    required: 'Please fill in all required fields.',
    perDay: '/ day',
    estimatedTotal: 'Estimated total',
    days: 'day(s)',
    genericError: 'Something went wrong. Please try again.',
    locationRequired: 'Please select the required pick-up and drop-off locations.',
  },
  fr: {
    title: 'Réserver ce véhicule',
    renterIdentity: 'Identité du locataire',
    firstName: 'Prénom',
    lastName: 'Nom',
    dateOfBirth: 'Date de naissance',
    nationality: 'Nationalité',
    identityDocumentNumber: 'N° CIN / passeport',
    fullAddress: 'Adresse complète',
    driverLicenseSection: 'Permis de conduire',
    email: 'E-mail',
    phone: 'Téléphone',
    driverLicense: 'Numéro du permis',
    licenseIssuedAt: 'Date de délivrance',
    licenseExpiry: 'Date d’expiration',
    licenseCountry: 'Pays de délivrance',
    licenseCategory: 'Catégorie du permis',
    internationalLicenseNumber: 'N° de permis international (optionnel)',
    pickupLocation: 'Lieu de départ',
    returnLocation: 'Lieu de retour',
    sameDropoff: 'Même retour',
    differentDropoff: 'Retour différent',
    sameAsPickup: 'Retour au même lieu',
    startDate: 'Date de départ',
    endDate: 'Date de retour',
    notes: 'Notes (optionnelles)',
    submit: 'Demander une réservation',
    submitting: 'Envoi…',
    successTitle: 'Demande reçue !',
    successBody: "Votre demande de réservation a été envoyée. L’entreprise va l’examiner et vous contactera prochainement.",
    invalidDates: 'La date de retour doit être après la date de départ.',
    required: 'Veuillez remplir tous les champs obligatoires.',
    perDay: '/ jour',
    estimatedTotal: 'Total estimé',
    days: 'jour(s)',
    genericError: 'Une erreur est survenue. Veuillez réessayer.',
    locationRequired: 'Veuillez sélectionner les lieux de départ et de retour requis.',
  },
  ar: {
    title: 'احجز هذه السيارة',
    renterIdentity: 'بيانات المستأجر',
    firstName: 'الاسم الأول',
    lastName: 'اسم العائلة',
    dateOfBirth: 'تاريخ الميلاد',
    nationality: 'الجنسية',
    identityDocumentNumber: 'رقم البطاقة الوطنية / جواز السفر',
    fullAddress: 'العنوان الكامل',
    driverLicenseSection: 'رخصة القيادة',
    email: 'البريد الإلكتروني',
    phone: 'الهاتف',
    driverLicense: 'رقم الرخصة',
    licenseIssuedAt: 'تاريخ الإصدار',
    licenseExpiry: 'تاريخ الانتهاء',
    licenseCountry: 'بلد الإصدار',
    licenseCategory: 'فئة الرخصة',
    internationalLicenseNumber: 'رقم الرخصة الدولية (اختياري)',
    pickupLocation: 'موقع الاستلام',
    returnLocation: 'موقع الإرجاع',
    sameDropoff: 'نفس موقع الإرجاع',
    differentDropoff: 'موقع إرجاع مختلف',
    sameAsPickup: 'الإرجاع في نفس موقع الاستلام',
    startDate: 'تاريخ الاستلام',
    endDate: 'تاريخ الإرجاع',
    notes: 'ملاحظات (اختيارية)',
    submit: 'طلب حجز',
    submitting: 'جارٍ الإرسال…',
    successTitle: 'تم استلام الطلب!',
    successBody: 'تم إرسال طلب الحجز. ستراجعه الشركة وستتواصل معك قريباً.',
    invalidDates: 'يجب أن يكون تاريخ الإعادة بعد تاريخ الاستلام.',
    required: 'يرجى تعبئة جميع الحقول المطلوبة.',
    perDay: '/ يوم',
    estimatedTotal: 'الإجمالي التقديري',
    days: 'يوم',
    genericError: 'حدث خطأ ما. يرجى المحاولة مرة أخرى.',
    locationRequired: 'يرجى اختيار مواقع الاستلام والإرجاع المطلوبة.',
  },
} as const

export default function BookingForm({
  vehicleId,
  companySlug,
  dailyRate,
  pickupLocations,
  allowDifferentDropoff,
  dropoffLocations,
}: Props) {
  const { language } = useMarketplacePreferences()

  const t = copy[language]
  const pickupOptions = Array.isArray(pickupLocations) ? pickupLocations : []
  const dropoffOptions = Array.isArray(dropoffLocations) ? dropoffLocations : []

  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [dateOfBirth, setDateOfBirth] = useState('')
  const [nationality, setNationality] = useState('')
  const [identityDocumentNumber, setIdentityDocumentNumber] = useState('')
  const [fullAddress, setFullAddress] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [driverLicense, setDriverLicense] = useState('')
  const [licenseIssuedAt, setLicenseIssuedAt] = useState('')
  const [licenseExpiry, setLicenseExpiry] = useState('')
  const [licenseCountry, setLicenseCountry] = useState('')
  const [licenseCategory, setLicenseCategory] = useState('')
  const [internationalLicenseNumber, setInternationalLicenseNumber] = useState('')
  const [pickupLocation, setPickupLocation] = useState(pickupOptions[0] ?? '')
  const [dropoffMode, setDropoffMode] = useState<'same' | 'different'>('same')
  const [returnLocation, setReturnLocation] = useState(dropoffOptions[0] ?? '')
  const [startDate, setStartDate] = useState('')
  const [endDate, setEndDate] = useState('')
  const [notes, setNotes] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState(false)

  const totalDays =
    startDate && endDate
      ? Math.max(0, Math.ceil((new Date(endDate).getTime() - new Date(startDate).getTime()) / 86_400_000))
      : 0

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)

    if (
      !firstName.trim() ||
      !lastName.trim() ||
      !dateOfBirth ||
      !nationality.trim() ||
      !identityDocumentNumber.trim() ||
      !fullAddress.trim() ||
      !email.trim() ||
      !phone.trim() ||
      !driverLicense.trim() ||
      !licenseIssuedAt ||
      !licenseExpiry ||
      !licenseCountry.trim() ||
      !licenseCategory.trim() ||
      !startDate ||
      !endDate
    ) {
      setError(t.required)
      return
    }
    if ((pickupOptions.length > 0 && !pickupLocation) || (dropoffMode === 'different' && dropoffOptions.length > 0 && !returnLocation)) {
      setError(t.locationRequired)
      return
    }

    const start = new Date(startDate)
    const end = new Date(endDate)
    if (end <= start) {
      setError(t.invalidDates)
      return
    }

    setSubmitting(true)
    try {
      await marketplacePost('/marketplace/reservations', {
        vehicleId,
        companySlug,
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        dateOfBirth: new Date(dateOfBirth).toISOString(),
        nationality: nationality.trim(),
        identityDocumentNumber: identityDocumentNumber.trim(),
        fullAddress: fullAddress.trim(),
        email: email.trim(),
        phone: phone.trim(),
        driverLicense: driverLicense.trim(),
        licenseIssuedAt: new Date(licenseIssuedAt).toISOString(),
        licenseExpiry: new Date(licenseExpiry).toISOString(),
        licenseCountry: licenseCountry.trim(),
        licenseCategory: licenseCategory.trim(),
        internationalLicenseNumber: internationalLicenseNumber.trim() || undefined,
        startDate: start.toISOString(),
        endDate: end.toISOString(),
        pickupLocation: pickupLocation || undefined,
        returnLocation: dropoffMode === 'different' ? (returnLocation || undefined) : (pickupLocation || undefined),
        notes: notes.trim() || undefined,
        language,
      })
      setSuccess(true)
    } catch (err: any) {
      setError(err.message ?? t.genericError)
    } finally {
      setSubmitting(false)
    }
  }

  if (success) {
    return (
      <div className="rounded-2xl border border-green-200 bg-green-50 p-6 dark:border-green-800 dark:bg-green-950/40">
        <p className="text-base font-semibold text-green-800 dark:text-green-300">{t.successTitle}</p>
        <p className="mt-2 text-sm text-green-700 dark:text-green-400">{t.successBody}</p>
      </div>
    )
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <p className="text-sm font-semibold text-stone-900 dark:text-stone-100">{t.title}</p>

      {error ? (
        <p className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-800 dark:bg-red-950/40 dark:text-red-400">
          {error}
        </p>
      ) : null}

      <div className="space-y-4 rounded-2xl border border-stone-200 bg-stone-50 p-4 dark:border-blue-800 dark:bg-blue-950">
        <p className="text-sm font-semibold text-stone-900 dark:text-stone-100">{t.renterIdentity}</p>
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.firstName} <span className="text-red-500">*</span></label>
            <input
              required
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.lastName} <span className="text-red-500">*</span></label>
            <input
              required
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.dateOfBirth} <span className="text-red-500">*</span></label>
            <input
              required
              type="date"
              value={dateOfBirth}
              onChange={(e) => setDateOfBirth(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.nationality} <span className="text-red-500">*</span></label>
            <input
              required
              value={nationality}
              onChange={(e) => setNationality(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
        </div>

        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.identityDocumentNumber} <span className="text-red-500">*</span></label>
          <input
            required
            value={identityDocumentNumber}
            onChange={(e) => setIdentityDocumentNumber(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          />
        </div>

        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.fullAddress} <span className="text-red-500">*</span></label>
          <textarea
            required
            value={fullAddress}
            onChange={(e) => setFullAddress(e.target.value)}
            rows={3}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          />
        </div>
      </div>

      <div className="space-y-1">
        <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.email} <span className="text-red-500">*</span></label>
        <input
          required
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
        />
      </div>

      <div className="space-y-4 rounded-2xl border border-stone-200 bg-stone-50 p-4 dark:border-blue-800 dark:bg-blue-950">
        <p className="text-sm font-semibold text-stone-900 dark:text-stone-100">{t.driverLicenseSection}</p>
        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.driverLicense} <span className="text-red-500">*</span></label>
          <input
            required
            value={driverLicense}
            onChange={(e) => setDriverLicense(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.licenseIssuedAt} <span className="text-red-500">*</span></label>
            <input
              required
              type="date"
              value={licenseIssuedAt}
              onChange={(e) => setLicenseIssuedAt(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.licenseExpiry} <span className="text-red-500">*</span></label>
            <input
              required
              type="date"
              value={licenseExpiry}
              onChange={(e) => setLicenseExpiry(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.licenseCountry} <span className="text-red-500">*</span></label>
            <input
              required
              value={licenseCountry}
              onChange={(e) => setLicenseCountry(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.licenseCategory} <span className="text-red-500">*</span></label>
            <input
              required
              value={licenseCategory}
              onChange={(e) => setLicenseCategory(e.target.value)}
              className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
            />
          </div>
        </div>

        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.internationalLicenseNumber}</label>
          <input
            value={internationalLicenseNumber}
            onChange={(e) => setInternationalLicenseNumber(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          />
        </div>
      </div>

      <div className="space-y-1">
        <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.phone} <span className="text-red-500">*</span></label>
        <input
          required
          type="tel"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
        />
      </div>

      {pickupOptions.length > 0 ? (
        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.pickupLocation} <span className="text-red-500">*</span></label>
          <select
            value={pickupLocation}
            onChange={(e) => setPickupLocation(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          >
            {pickupOptions.map((location) => (
              <option key={location} value={location}>{location}</option>
            ))}
          </select>
        </div>
      ) : null}

      {allowDifferentDropoff ? (
        <div className="space-y-3 rounded-2xl border border-stone-200 bg-stone-50 p-4 dark:border-blue-800 dark:bg-blue-950">
          <div className="inline-flex rounded-full border border-stone-200 dark:border-blue-800 bg-white dark:bg-blue-900/30 p-1">
            <button
              type="button"
              onClick={() => setDropoffMode('same')}
              className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
                dropoffMode === 'same'
                  ? 'bg-blue-900 text-white dark:bg-orange-400 dark:text-white'
                  : 'text-stone-500 dark:text-stone-400'
              }`}
            >
              {t.sameDropoff}
            </button>
            <button
              type="button"
              onClick={() => setDropoffMode('different')}
              className={`rounded-full px-3 py-1.5 text-xs font-semibold transition ${
                dropoffMode === 'different'
                  ? 'bg-blue-900 text-white dark:bg-orange-400 dark:text-white'
                  : 'text-stone-500 dark:text-stone-400'
              }`}
            >
              {t.differentDropoff}
            </button>
          </div>

          {dropoffMode === 'different' && dropoffOptions.length > 0 ? (
            <div className="space-y-1">
              <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.returnLocation} <span className="text-red-500">*</span></label>
              <select
                value={returnLocation}
                onChange={(e) => setReturnLocation(e.target.value)}
                className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
              >
                {dropoffOptions.map((location) => (
                  <option key={location} value={location}>{location}</option>
                ))}
              </select>
            </div>
          ) : (
            <p className="text-sm text-stone-500 dark:text-stone-400">{pickupLocation || t.sameAsPickup}</p>
          )}
        </div>
      ) : null}

      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.startDate} <span className="text-red-500">*</span></label>
          <input
            required
            type="date"
            value={startDate}
            min={new Date().toISOString().slice(0, 10)}
            onChange={(e) => setStartDate(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          />
        </div>
        <div className="space-y-1">
          <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.endDate} <span className="text-red-500">*</span></label>
          <input
            required
            type="date"
            value={endDate}
            min={startDate || new Date().toISOString().slice(0, 10)}
            onChange={(e) => setEndDate(e.target.value)}
            className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
          />
        </div>
      </div>

      {totalDays > 0 ? (
        <p className="text-sm text-stone-600 dark:text-stone-400">
          {t.estimatedTotal}:{' '}
          <strong className="text-stone-900 dark:text-stone-100">
            {(dailyRate * totalDays).toLocaleString()} MAD
          </strong>{' '}
          ({totalDays} {t.days})
        </p>
      ) : null}

      <div className="space-y-1">
        <label className="text-xs font-medium text-stone-600 dark:text-stone-400">{t.notes}</label>
        <textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={3}
          className="w-full rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm text-stone-900 outline-none focus:border-stone-400 dark:border-blue-800 dark:bg-blue-900/30 dark:text-stone-100 dark:focus:border-stone-500"
        />
      </div>

      <button
        type="submit"
        disabled={submitting}
        className="w-full rounded-full bg-orange-600 px-6 py-3 text-center text-sm font-semibold text-white transition hover:bg-orange-700 disabled:opacity-60 dark:bg-orange-400 dark:text-white dark:hover:bg-orange-300"
      >
        {submitting ? t.submitting : t.submit}
      </button>
    </form>
  )
}
