'use client'
import { Button } from '@/components/ui/button'
import { CalendarWithTrigger } from '@/components/ui/CalendarWithTrigger'
import { CustomSelect } from '@/components/ui/select'
import { cn } from '@/lib/utils/cn'
import { Car } from '@/payload-types'
import { ArrowRight, MapPin } from 'lucide-react'
import { useState, useEffect } from 'react'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
import { useCurrentLocale } from '@/locales/client'
import { Vehicle } from '@/lib/types/api/vehicle'
import { useScopedI18n } from '@/locales/client'

export const HeroForm = ({ className, cars }: { className?: string; cars?: Vehicle[] }) => {
  const t = useScopedI18n('catalog')
  const locale = useCurrentLocale()
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  const [activeToggle, setActiveToggle] = useState<1 | 2>(1)
  const [pickUpDate, setPickUpDate] = useState<Date>(new Date())
  const [returnDate, setReturnDate] = useState<Date>(new Date())
  const [departure, setDeparture] = useState<string>('')
  const [returnLocation, setReturnLocation] = useState<string>('')
  const [errors, setErrors] = useState<{ departure?: string; returnLocation?: string }>({})

  useEffect(() => {
    if (!searchParams) {
      setDeparture('')
      setReturnLocation('')
      setPickUpDate(new Date())
      setReturnDate(new Date())
      setActiveToggle(1)
      return
    }

    const dep = searchParams.get('departure')
    const ret = searchParams.get('returnLocation')
    const pu = searchParams.get('pickUpDate')
    const re = searchParams.get('returnDate')
    const wd = searchParams.get('withDriver')
    const wod = searchParams.get('withoutDriver')

    if (dep) setDeparture(dep)
    if (ret) setReturnLocation(ret)
    if (pu) {
      const d = new Date(pu)
      if (!isNaN(d.getTime())) setPickUpDate(d)
    }
    if (re) {
      const d = new Date(re)
      if (!isNaN(d.getTime())) setReturnDate(d)
    }
    if (wd === 'true') setActiveToggle(2)
    else if (wod === 'true') setActiveToggle(1)
  }, [searchParams])

  const onHandleClick = () => {
    const newErrors: { departure?: string; returnLocation?: string } = {}
    if (!departure) {
      newErrors.departure = 'Departure is required'
    }
    if (!returnLocation) {
      newErrors.returnLocation = 'Return location is required'
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors)
      return
    }

    setErrors({}) // Clear errors on successful submission

    const targetPath = `/${locale}/catalog`
    const params = new URLSearchParams({
      departure,
      returnLocation,
      pickUpDate: pickUpDate.toISOString(),
      returnDate: returnDate.toISOString(),
      withDriver: activeToggle === 2 ? 'true' : 'false',
      withoutDriver: activeToggle === 1 ? 'true' : 'false',
    })
    const queryString = params.toString()
    const currentPath = `${pathname}?${queryString}`

    if (pathname !== targetPath) {
      router.push(`${targetPath}?${params.toString()}`)
    } else {
      router.replace(currentPath, { scroll: false })
    }
  }

  return (
    <div className={cn('gradient-border w-full p-4 rounded-xl relative mt-[160px]', className)}>
      <div className="grid grid-cols-1 gap-2 md:grid-cols-2 lg:grid-cols-4">
        <CustomSelect
          triggerClassName="lg:px-2 xxl:px-4 xxl:min-w-[278px] xxl:max-w-[278px]"
          hideDefaultIcon
          iconLeft={<MapPin size={20} className="stroke-grey-200" />}
          label={t('labels.departure')}
          options={[
            ...new Map(
              cars?.flatMap((car) => car.locations || []).map((loc) => [loc.id, loc])
            ).values(),
          ].map((loc) => ({ label: loc.name, value: String(loc.id) }))}
          placeholder={t('placeholders.departure')}
          value={departure}
          onValueChange={(value) => {
            setDeparture(value)
            if (errors.departure) {
              setErrors((prev) => ({ ...prev, departure: undefined }))
            }
          }}
          hasError={!!errors.departure}
          errorMessage={errors.departure}
        />
        <CustomSelect
          triggerClassName="lg:px-2 xxl:px-4 xxl:min-w-[278px] xxl:max-w-[278px]"
          hideDefaultIcon
          iconLeft={<MapPin size={20} className="stroke-grey-200" />}
          label={t('labels.returnLocation')}
          options={[
            ...new Map(
              cars?.flatMap((car) => car.locations || []).map((loc) => [loc.id, loc])
            ).values(),
          ].map((loc) => ({ label: loc.name, value: String(loc.id) }))}
          placeholder={t('placeholders.returnLocation')}
          value={returnLocation}
          onValueChange={(value) => {
            setReturnLocation(value)
            if (errors.returnLocation) {
              setErrors((prev) => ({ ...prev, returnLocation: undefined }))
            }
          }}
          hasError={!!errors.returnLocation}
          errorMessage={errors.returnLocation}
        />
        <CalendarWithTrigger
          value={pickUpDate}
          onChange={setPickUpDate}
          className="w-full xxl:w-[278px]"
          label={t('labels.pickUpDate')}
        />
        <CalendarWithTrigger
          value={returnDate}
          onChange={setReturnDate}
          className="w-full xxl:w-[278px]"
          label={t('labels.returnDate')}
        />
      </div>

      <div className="mt-4 flex flex-col gap-4 md:flex-row md:justify-between md:items-center">
        <div className="flex justify-center md:justify-start">
          <div className="flex items-center gap-2 p-2 bg-grey-900 w-full md:w-fit rounded-xl">
            <div
              className={cn(
                'button-small-regular px-4 py-2 rounded-xl cursor-pointer flex-1 text-center whitespace-nowrap',
                activeToggle === 1
                  ? 'bg-transparent-white-20 text-base-white'
                  : 'bg-grey-900 text-grey-200',
              )}
              onClick={() => setActiveToggle(1)}
            >
              {t('labels.withoutDriver')}
            </div>
            <div
              className={cn(
                'button-small-regular px-4 py-2 rounded-xl cursor-pointer flex-1 text-center whitespace-nowrap',
                activeToggle === 2
                  ? 'bg-transparent-white-20 text-base-white'
                  : 'bg-grey-900 text-grey-200',
              )}
              onClick={() => setActiveToggle(2)}
            >
              {t('labels.withDriver')}
            </div>
          </div>
        </div>

        <div className="flex justify-center md:justify-end">
          <Button
            variant="primary"
            RightIcon={<ArrowRight size={24} className="stroke-basic-black" />}
            className="w-full md:w-auto"
            onClick={onHandleClick}
          >
            {t('labels.search')}
          </Button>
        </div>
      </div>
    </div>
  )
}

export default HeroForm
