'use client'

import { createUrl } from '@/utilities/createUrl'
import { updateShopSearchParams } from '@/utilities/shopParams'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import type { FormEvent } from 'react'
import { useId } from 'react'

type Props = {
  applyLabel?: null | string
  maxLabel?: null | string
  maxPlaceholder?: null | string
  minLabel?: null | string
  minPlaceholder?: null | string
  title?: null | string
}

export function PriceRangeControl({
  applyLabel,
  maxLabel,
  maxPlaceholder,
  minLabel,
  minPlaceholder,
  title,
}: Props) {
  const maxInputID = useId()
  const minInputID = useId()
  const pathname = usePathname()
  const router = useRouter()
  const searchParams = useSearchParams()
  const currentMinPrice = searchParams.get('minPrice') || ''
  const currentMaxPrice = searchParams.get('maxPrice') || ''
  const hasActiveRange = Boolean(currentMinPrice || currentMaxPrice)

  const onSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()

    const formData = new FormData(event.currentTarget)
    const nextParams = updateShopSearchParams(searchParams, {
      maxPrice: String(formData.get('maxPrice') || ''),
      minPrice: String(formData.get('minPrice') || ''),
      type: 'priceRange',
    })

    router.push(createUrl(pathname, nextParams))
  }

  const onClear = () => {
    const nextParams = updateShopSearchParams(searchParams, {
      maxPrice: null,
      minPrice: null,
      type: 'priceRange',
    })

    router.push(createUrl(pathname, nextParams))
  }

  return (
    <form className="space-y-3 border-t border-[#dbe8d7] pt-5" onSubmit={onSubmit}>
      <h3 className="text-[11px] font-semibold uppercase tracking-[0.18em] text-[#607668]">
        {title || 'Price range'}
      </h3>

      <div className="grid grid-cols-2 gap-2">
        <div>
          <label className="sr-only" htmlFor={minInputID}>
            {minLabel || 'Minimum price'}
          </label>
          <input
            autoComplete="off"
            className="w-full rounded-lg border border-[#dbe8d7] bg-[#f7faf4] px-3 py-2.5 text-sm text-[#063f2b] outline-none transition placeholder:text-[#8a9a8e] focus:border-[#003b29] focus:bg-white focus:ring-4 focus:ring-[#003b29]/10"
            defaultValue={currentMinPrice}
            id={minInputID}
            inputMode="numeric"
            key={`min-${currentMinPrice}`}
            min={0}
            name="minPrice"
            placeholder={minPlaceholder || 'Min'}
            step={1}
            type="number"
          />
        </div>

        <div>
          <label className="sr-only" htmlFor={maxInputID}>
            {maxLabel || 'Maximum price'}
          </label>
          <input
            autoComplete="off"
            className="w-full rounded-lg border border-[#dbe8d7] bg-[#f7faf4] px-3 py-2.5 text-sm text-[#063f2b] outline-none transition placeholder:text-[#8a9a8e] focus:border-[#003b29] focus:bg-white focus:ring-4 focus:ring-[#003b29]/10"
            defaultValue={currentMaxPrice}
            id={maxInputID}
            inputMode="numeric"
            key={`max-${currentMaxPrice}`}
            min={0}
            name="maxPrice"
            placeholder={maxPlaceholder || 'Max'}
            step={1}
            type="number"
          />
        </div>
      </div>

      <div className="flex items-center gap-3">
        <button
          className="rounded-lg bg-[#003b29] px-4 py-2.5 text-xs font-semibold text-white shadow-sm transition hover:bg-[#125238]"
          type="submit"
        >
          {applyLabel || 'Apply'}
        </button>

        {hasActiveRange ? (
          <button
            className="text-xs font-semibold text-[#607668] underline underline-offset-4 transition hover:text-[#063f2b]"
            onClick={onClear}
            type="button"
          >
            Clear
          </button>
        ) : null}
      </div>
    </form>
  )
}
