"use client"

import { usePathname, useSearchParams } from "next/navigation"
import { useCallback, useEffect } from "react"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"

import Checkbox from "@/components/TempDesignSystem/Form/Checkbox"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import Title from "@/components/TempDesignSystem/Text/Title"

import styles from "./hotelFilter.module.css"

import type { HotelFiltersProps } from "@/types/components/hotelReservation/selectHotel/hotelFilters"

export default function HotelFilter({ filters }: HotelFiltersProps) {
  const intl = useIntl()
  const searchParams = useSearchParams()
  const pathname = usePathname()

  const methods = useForm<Record<string, boolean | undefined>>({
    defaultValues: searchParams
      ?.get("filters")
      ?.split(",")
      .reduce((acc, curr) => ({ ...acc, [curr]: true }), {}),
  })
  const { watch, handleSubmit, getValues, register } = methods

  const submitFilter = useCallback(() => {
    const newSearchParams = new URLSearchParams(searchParams)
    const values = Object.entries(getValues())
      .filter(([_, value]) => !!value)
      .map(([key, _]) => key)
      .join(",")

    if (values === "") {
      newSearchParams.delete("filters")
    } else {
      newSearchParams.set("filters", values)
    }

    if (values !== searchParams.values.toString()) {
      window.history.replaceState(
        null,
        "",
        `${pathname}?${newSearchParams.toString()}`
      )
    }
  }, [getValues, pathname, searchParams])

  useEffect(() => {
    const subscription = watch(() => handleSubmit(submitFilter)())
    return () => subscription.unsubscribe()
  }, [handleSubmit, watch, submitFilter])

  if (!filters.facilityFilters.length && !filters.surroundingsFilters.length) {
    return null
  }

  return (
    <aside className={styles.container}>
      <FormProvider {...methods}>
        <form onSubmit={handleSubmit(submitFilter)}>
          <Title as="h4">{intl.formatMessage({ id: "Filter by" })}</Title>
          <div className={styles.facilities}>
            <Subtitle>
              {intl.formatMessage({ id: "Hotel facilities" })}
            </Subtitle>
            <ul>
              {filters.facilityFilters.map((filter) => (
                <li key={`li-${filter.id}`} className={styles.filter}>
                  <Checkbox name={filter.id.toString()}>{filter.name}</Checkbox>
                </li>
              ))}
            </ul>
          </div>

          <div className={styles.facilities}>
            <Subtitle>
              {intl.formatMessage({ id: "Hotel surroundings" })}
            </Subtitle>
            <ul>
              {filters.surroundingsFilters.map((filter) => (
                <li key={`li-${filter.id}`} className={styles.filter}>
                  <Checkbox name={filter.id.toString()}>{filter.name}</Checkbox>
                </li>
              ))}
            </ul>
          </div>
        </form>
      </FormProvider>
    </aside>
  )
}
