'use client'

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

interface Vehicle {
  id: string
  make: string
  model: string
  year: number
  category: string
  dailyRate: number
  photos: string[]
  availability?: boolean | null
  availabilityStatus?: 'AVAILABLE' | 'RESERVED' | 'MAINTENANCE' | 'UNAVAILABLE'
  nextAvailableAt?: string | null
  company: {
    slug: string
    brand: {
      displayName: string
      logoUrl: string | null
      subdomain: string
      marketplaceRating: number | null
    } | null
  }
}

interface Dict {
  rentalCompany: string
  checkAvailability: string
  available: string
  reserved: string
  maintenance: string
  unavailableStatus: string
  from: string
  bookNow: string
  availableFrom: string
  reserveAfterDate: string
  unavailableNoDate: string
  details: string
  vehicleUnavailable: string
  listings: string
  availableVehicles: string
  // modal
  reserveVehicle: string
  pickupDate: string
  returnDate: string
  firstName: string
  lastName: string
  email: string
  phone: string
  notes: string
  cancel: string
  submitRequest: string
  submitting: string
  successTitle: string
  successBody: string
  close: string
  errorUnavailable: string
  errorGeneric: string
}

function formatCents(cents: number) {
  return `${(cents / 100).toLocaleString('fr-MA', { minimumFractionDigits: 2 })} MAD`
}

function daysBetween(start: string, end: string) {
  const ms = new Date(end).getTime() - new Date(start).getTime()
  return Math.max(1, Math.ceil(ms / 86_400_000))
}

function formatAvailabilityDate(value?: string | null) {
  if (!value) return null
  return new Date(value).toLocaleDateString('en-GB', { year: 'numeric', month: 'long', day: 'numeric' })
}

const today = () => new Date().toISOString().slice(0, 10)
const tomorrow = () => new Date(Date.now() + 86_400_000).toISOString().slice(0, 10)

export default function ExploreVehicleGrid({ vehicles, dict }: { vehicles: Vehicle[]; dict: Dict }) {
  const [selected, setSelected] = useState<Vehicle | null>(null)
  const [form, setForm] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    startDate: today(),
    endDate: tomorrow(),
    notes: '',
  })
  const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle')
  const [errorMsg, setErrorMsg] = useState('')

  function openModal(vehicle: Vehicle) {
    const minStart = vehicle.nextAvailableAt ? new Date(vehicle.nextAvailableAt).toISOString().slice(0, 10) : today()
    const minEnd = new Date(new Date(minStart).getTime() + 86_400_000).toISOString().slice(0, 10)
    setSelected(vehicle)
    setStatus('idle')
    setErrorMsg('')
    setForm({ firstName: '', lastName: '', email: '', phone: '', startDate: minStart, endDate: minEnd, notes: '' })
  }

  function closeModal() {
    setSelected(null)
    setStatus('idle')
    setErrorMsg('')
  }

  function set(field: keyof typeof form) {
    return (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setForm((prev) => {
        if (field !== 'startDate') return { ...prev, [field]: e.target.value }
        const nextStart = e.target.value
        const nextEnd = !prev.endDate || prev.endDate <= nextStart
          ? new Date(new Date(nextStart).getTime() + 86_400_000).toISOString().slice(0, 10)
          : prev.endDate
        return { ...prev, startDate: nextStart, endDate: nextEnd }
      })
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!selected) return
    const minStart = selected.nextAvailableAt ? new Date(selected.nextAvailableAt).toISOString().slice(0, 10) : today()
    if (form.startDate < minStart) {
      setStatus('error')
      setErrorMsg(`${dict.reserveAfterDate} ${formatAvailabilityDate(selected.nextAvailableAt) ?? minStart}.`)
      return
    }
    setStatus('submitting')
    setErrorMsg('')
    try {
      await marketplacePost('/marketplace/reservations', {
        vehicleId: selected.id,
        companySlug: selected.company.slug,
        firstName: form.firstName,
        lastName: form.lastName,
        email: form.email,
        phone: form.phone || undefined,
        startDate: new Date(form.startDate).toISOString(),
        endDate: new Date(form.endDate).toISOString(),
        notes: form.notes || undefined,
      })
      setStatus('success')
    } catch (err: any) {
      setStatus('error')
      if (err?.code === 'unavailable') {
        setErrorMsg(err?.nextAvailableAt ? `${dict.reserveAfterDate} ${formatAvailabilityDate(err.nextAvailableAt)}.` : dict.errorUnavailable)
      } else {
        setErrorMsg(err?.message ?? dict.errorGeneric)
      }
    }
  }

  const days = form.startDate && form.endDate ? daysBetween(form.startDate, form.endDate) : 0
  const estimatedTotal = selected ? selected.dailyRate * days : 0

  function getStatusCopy(vehicle: Vehicle) {
    if (vehicle.availabilityStatus === 'RESERVED') return dict.reserved
    if (vehicle.availabilityStatus === 'MAINTENANCE') return dict.maintenance
    if (vehicle.availabilityStatus === 'UNAVAILABLE') return dict.unavailableStatus
    if (vehicle.availability === false) return dict.checkAvailability
    return dict.available
  }

  return (
    <>
      <section>
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold text-stone-900">{dict.availableVehicles}</h2>
          <p className="text-sm text-stone-500">{vehicles.length} {dict.listings}</p>
        </div>
        <div className="mt-4 grid gap-5 md:grid-cols-2 xl:grid-cols-3">
          {vehicles.map((vehicle) => (
            <article key={vehicle.id} className="card overflow-hidden">
              <div className="aspect-[16/10] bg-stone-100">
                {vehicle.photos[0] ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={vehicle.photos[0]} alt={`${vehicle.make} ${vehicle.model}`} className="h-full w-full object-cover" />
                ) : null}
              </div>
              <div className="p-5">
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-xs uppercase tracking-[0.16em] text-stone-500">{vehicle.company.brand?.displayName ?? dict.rentalCompany}</p>
                    <h3 className="mt-2 text-xl font-bold text-stone-900">{vehicle.make} {vehicle.model}</h3>
                    <p className="mt-1 text-sm text-stone-500">{vehicle.year} · {vehicle.category}</p>
                  </div>
                  <span className={`rounded-full px-3 py-1 text-xs font-semibold ${vehicle.availability === false ? 'bg-rose-100 text-rose-700' : 'bg-emerald-100 text-emerald-700'}`}>
                    {getStatusCopy(vehicle)}
                  </span>
                </div>
                {vehicle.availability === false && (
                  <p className="mt-3 text-sm text-stone-500">
                    {vehicle.nextAvailableAt ? `${dict.availableFrom} ${formatAvailabilityDate(vehicle.nextAvailableAt)}` : dict.unavailableNoDate}
                  </p>
                )}
                <div className="mt-5 flex items-end justify-between">
                  <div>
                    <p className="text-sm text-stone-500">{dict.from}</p>
                    <p className="text-2xl font-black text-stone-900">{formatCents(vehicle.dailyRate)}</p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <button
                      onClick={() => openModal(vehicle)}
                      className="rounded-full bg-stone-900 px-5 py-2.5 text-sm font-semibold text-white"
                    >
                      {dict.bookNow}
                    </button>
                  </div>
                </div>
              </div>
            </article>
          ))}
          {vehicles.length === 0 && (
            <div className="card p-6 text-sm text-stone-500 md:col-span-2 xl:col-span-3">{dict.vehicleUnavailable}</div>
          )}
        </div>
      </section>

      {selected && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={closeModal}>
          <div
            className="relative w-full max-w-lg max-h-[90vh] overflow-y-auto rounded-3xl bg-white shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="flex items-start gap-4 p-6 border-b border-stone-100">
              {selected.photos[0] && (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={selected.photos[0]} alt="" className="h-16 w-24 rounded-xl object-cover flex-shrink-0" />
              )}
              <div className="flex-1 min-w-0">
                <p className="text-xs uppercase tracking-widest text-stone-400">{selected.company.brand?.displayName ?? dict.rentalCompany}</p>
                <h2 className="mt-1 text-xl font-bold text-stone-900 truncate">{selected.year} {selected.make} {selected.model}</h2>
                <p className="mt-0.5 text-sm text-stone-500">{selected.category} · {formatCents(selected.dailyRate)}/day</p>
              </div>
              <button onClick={closeModal} className="flex-shrink-0 rounded-full p-2 hover:bg-stone-100 text-stone-500">
                <svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" /></svg>
              </button>
            </div>

            {status === 'success' ? (
              <div className="p-8 text-center space-y-4">
                <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100">
                  <svg className="h-8 w-8 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" /></svg>
                </div>
                <h3 className="text-xl font-bold text-stone-900">{dict.successTitle}</h3>
                <p className="text-stone-500">{dict.successBody}</p>
                <button onClick={closeModal} className="mt-4 rounded-full bg-stone-900 px-8 py-3 text-sm font-semibold text-white">
                  {dict.close}
                </button>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="p-6 space-y-5">
                <h3 className="font-semibold text-stone-900">{dict.reserveVehicle}</h3>
                {selected.availability === false && (
                  <div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
                    {selected.nextAvailableAt ? `${dict.reserveAfterDate} ${formatAvailabilityDate(selected.nextAvailableAt)}.` : dict.unavailableNoDate}
                  </div>
                )}

                {/* Dates */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-stone-600 mb-1">{dict.pickupDate}</label>
                    <input
                      type="date"
                      required
                      min={selected.nextAvailableAt ? new Date(selected.nextAvailableAt).toISOString().slice(0, 10) : today()}
                      value={form.startDate}
                      onChange={set('startDate')}
                      className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-stone-600 mb-1">{dict.returnDate}</label>
                    <input
                      type="date"
                      required
                      min={form.startDate || today()}
                      value={form.endDate}
                      onChange={set('endDate')}
                      className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900"
                    />
                  </div>
                </div>

                {/* Estimated total */}
                {days > 0 && (
                  <div className="rounded-2xl bg-stone-50 px-4 py-3 flex items-center justify-between">
                    <p className="text-sm text-stone-500">{days} day{days > 1 ? 's' : ''} × {formatCents(selected.dailyRate)}</p>
                    <p className="font-bold text-stone-900">{formatCents(estimatedTotal)}</p>
                  </div>
                )}

                {/* Customer info */}
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-stone-600 mb-1">{dict.firstName}</label>
                    <input
                      type="text"
                      required
                      value={form.firstName}
                      onChange={set('firstName')}
                      className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-medium text-stone-600 mb-1">{dict.lastName}</label>
                    <input
                      type="text"
                      required
                      value={form.lastName}
                      onChange={set('lastName')}
                      className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-medium text-stone-600 mb-1">{dict.email}</label>
                  <input
                    type="email"
                    required
                    value={form.email}
                    onChange={set('email')}
                    className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900"
                  />
                </div>

                <div>
                  <label className="block text-xs font-medium text-stone-600 mb-1">{dict.phone}</label>
                  <input
                    type="tel"
                    value={form.phone}
                    onChange={set('phone')}
                    className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900"
                  />
                </div>

                <div>
                  <label className="block text-xs font-medium text-stone-600 mb-1">{dict.notes}</label>
                  <textarea
                    rows={3}
                    value={form.notes}
                    onChange={set('notes')}
                    className="w-full rounded-xl border border-stone-200 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-stone-900 resize-none"
                  />
                </div>

                {status === 'error' && (
                  <p className="rounded-2xl bg-rose-50 px-4 py-3 text-sm text-rose-700">{errorMsg}</p>
                )}

                <div className="flex gap-3 pt-1">
                  <button
                    type="button"
                    onClick={closeModal}
                    className="flex-1 rounded-full border border-stone-300 px-4 py-3 text-sm font-semibold text-stone-700"
                  >
                    {dict.cancel}
                  </button>
                  <button
                    type="submit"
                    disabled={status === 'submitting'}
                    className="flex-1 rounded-full bg-stone-900 px-4 py-3 text-sm font-semibold text-white disabled:opacity-60"
                  >
                    {status === 'submitting' ? dict.submitting : dict.submitRequest}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  )
}
