'use client'

import { CalendarDays, Clock3, MapPin, Search } from 'lucide-react'
import { useState, type FormEvent } from 'react'
import type { CarplaceMessages } from '@/lib/carplace/messages'
import { carplaceHref } from '@/lib/carplace/routes'

export type CarplaceSearchValues = {
  pickupLocation?: string
  dropoffLocation?: string
  dropoffMode?: 'same' | 'different'
  pickupDate?: string
  pickupTime?: string
  returnDate?: string
  returnTime?: string
  driverAge?: string
  promoCode?: string
}

export default function CarplaceSearchForm({ cities, copy, initial = {}, compact = false }: { cities: string[]; copy: CarplaceMessages; initial?: CarplaceSearchValues; compact?: boolean }) {
  const [dropoffMode, setDropoffMode] = useState<'same' | 'different'>(initial.dropoffMode === 'different' ? 'different' : 'same')
  const [dateError, setDateError] = useState<string | null>(null)
  const today = new Date().toISOString().slice(0, 10)

  function validateDates(event: FormEvent<HTMLFormElement>) {
    const data = new FormData(event.currentTarget)
    const pickup = String(data.get('pickupDate') ?? '')
    const pickupTime = String(data.get('pickupTime') ?? '00:00')
    const returned = String(data.get('returnDate') ?? '')
    const returnTime = String(data.get('returnTime') ?? '00:00')
    if (!pickup || !returned || new Date(`${returned}T${returnTime}:00`) <= new Date(`${pickup}T${pickupTime}:00`)) {
      event.preventDefault()
      setDateError(copy.search.invalidDates)
    }
  }

  return (
    <form action={carplaceHref('/search')} method="get" onSubmit={validateDates} className={compact ? 'carplace-search carplace-search-compact' : 'carplace-search'}>
      {!compact ? <h2 className="text-xl font-black text-blue-950 dark:text-white">{copy.search.title}</h2> : null}
      <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        <SearchField icon={MapPin} label={copy.search.pickup}>
          <input list="carplace-cities" name="pickupLocation" defaultValue={initial.pickupLocation ?? ''} placeholder={copy.search.locationPlaceholder} required className="carplace-input" />
        </SearchField>
        <SearchField icon={MapPin} label={copy.search.returnLocation}>
          {dropoffMode === 'same' ? (
            <div className="carplace-input flex items-center text-stone-500 dark:text-slate-400">{copy.search.sameReturn}</div>
          ) : (
            <input list="carplace-cities" name="dropoffLocation" defaultValue={initial.dropoffLocation ?? ''} placeholder={copy.search.locationPlaceholder} required className="carplace-input" />
          )}
        </SearchField>
        <SearchField icon={CalendarDays} label={copy.search.pickupDate}>
          <div className="grid grid-cols-[1fr_7rem] gap-2">
            <input type="date" name="pickupDate" min={today} defaultValue={initial.pickupDate ?? ''} required className="carplace-input min-w-0" />
            <input type="time" name="pickupTime" defaultValue={initial.pickupTime ?? '10:00'} required className="carplace-input min-w-0" aria-label={copy.search.pickupTime} />
          </div>
        </SearchField>
        <SearchField icon={CalendarDays} label={copy.search.returnDate}>
          <div className="grid grid-cols-[1fr_7rem] gap-2">
            <input type="date" name="returnDate" min={today} defaultValue={initial.returnDate ?? ''} required className="carplace-input min-w-0" />
            <input type="time" name="returnTime" defaultValue={initial.returnTime ?? '10:00'} required className="carplace-input min-w-0" aria-label={copy.search.returnTime} />
          </div>
        </SearchField>
      </div>

      <div className="mt-3 flex flex-col gap-3 lg:flex-row lg:items-end">
        <div className="flex flex-wrap gap-2" role="group" aria-label={copy.search.returnLocation}>
          <label className={`carplace-choice ${dropoffMode === 'same' ? 'carplace-choice-active' : ''}`}>
            <input type="radio" name="dropoffMode" value="same" checked={dropoffMode === 'same'} onChange={() => setDropoffMode('same')} className="sr-only" />
            {copy.search.sameReturn}
          </label>
          <label className={`carplace-choice ${dropoffMode === 'different' ? 'carplace-choice-active' : ''}`}>
            <input type="radio" name="dropoffMode" value="different" checked={dropoffMode === 'different'} onChange={() => setDropoffMode('different')} className="sr-only" />
            {copy.search.differentReturn}
          </label>
        </div>

        <div className="grid flex-1 gap-3 sm:grid-cols-2 lg:max-w-xl">
          <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">
            {copy.search.age}
            <select name="driverAge" defaultValue={initial.driverAge ?? '25'} className="carplace-input">
              <option value="18">18+</option><option value="21">21+</option><option value="23">23+</option><option value="25">25+</option><option value="30">30+</option>
            </select>
          </label>
          <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">
            {copy.search.promo} <span className="font-normal text-stone-400">({copy.search.optional})</span>
            <input name="promoCode" defaultValue={initial.promoCode ?? ''} className="carplace-input" />
          </label>
        </div>

        <button type="submit" className="carplace-primary-button lg:ms-auto">
          <Search className="h-4 w-4" />
          {copy.actions.search}
        </button>
      </div>
      {dateError ? <p role="alert" className="mt-3 text-sm font-semibold text-red-700 dark:text-red-300">{dateError}</p> : null}
      <datalist id="carplace-cities">{cities.map((city) => <option key={city} value={city} />)}</datalist>
      <span className="sr-only"><Clock3 />{copy.search.pickupTime}</span>
    </form>
  )
}

function SearchField({ icon: Icon, label, children }: { icon: typeof MapPin; label: string; children: React.ReactNode }) {
  return (
    <label className="grid min-w-0 gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">
      <span className="flex items-center gap-2"><Icon className="h-4 w-4 text-orange-600 dark:text-orange-400" />{label}</span>
      {children}
    </label>
  )
}
