"use client"

import { useIntl } from "react-intl"

import { useDestinationDataStore } from "@/stores/destination-data"

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

import Checkbox from "./Checkbox"

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

import type { CategorizedFilters } from "@/types/components/destinationFilterAndSort"

interface FilterProps {
  filters: CategorizedFilters
}

export default function Filter({ filters }: FilterProps) {
  const intl = useIntl()
  const { facilityFilters, surroundingsFilters } = filters
  const { pendingFilters, togglePendingFilter } = useDestinationDataStore(
    (state) => ({
      pendingFilters: state.pendingFilters,
      togglePendingFilter: state.actions.togglePendingFilter,
    })
  )

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

  return (
    <div className={styles.container}>
      <Title level="h4">
        {intl.formatMessage({
          defaultMessage: "Filter by",
        })}
      </Title>
      <form className={styles.form}>
        <fieldset className={styles.fieldset}>
          <Subtitle type="two" asChild>
            <legend>
              {intl.formatMessage({
                defaultMessage: "Hotel facilities",
              })}
            </legend>
          </Subtitle>
          <ul className={styles.list}>
            {facilityFilters.map((filter) => (
              <li key={`filter-${filter.slug}`}>
                <Checkbox
                  name={filter.name}
                  value={filter.slug}
                  onChange={() => togglePendingFilter(filter.slug)}
                  isSelected={!!pendingFilters.find((f) => f === filter.slug)}
                />
              </li>
            ))}
          </ul>
        </fieldset>

        <fieldset className={styles.fieldset}>
          <Subtitle type="two" asChild>
            <legend>
              {intl.formatMessage({
                defaultMessage: "Hotel surroundings",
              })}
            </legend>
          </Subtitle>
          <ul className={styles.list}>
            {surroundingsFilters.map((filter) => (
              <li key={`filter-${filter.slug}`}>
                <Checkbox
                  name={filter.name}
                  value={filter.slug}
                  onChange={() => togglePendingFilter(filter.slug)}
                  isSelected={!!pendingFilters.find((f) => f === filter.slug)}
                />
              </li>
            ))}
          </ul>
        </fieldset>
      </form>
    </div>
  )
}
