"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useCallback, useEffect, useMemo } from "react"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"
import { z } from "zod"

import { InfoCircleIcon } from "@/components/Icons"
import CheckboxChip from "@/components/TempDesignSystem/Form/FilterChip/Checkbox"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import { Tooltip } from "@/components/TempDesignSystem/Tooltip"

import { getIconForFeatureCode } from "../utils"

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

import {
  type RoomFilterProps,
  RoomPackageCodeEnum,
} from "@/types/components/hotelReservation/selectRate/roomFilter"

export default function RoomFilter({
  numberOfRooms,
  onFilter,
  filterOptions,
}: RoomFilterProps) {
  const initialFilterValues = useMemo(
    () =>
      filterOptions.reduce(
        (acc, option) => {
          acc[option.code] = false
          return acc
        },
        {} as Record<string, boolean | undefined>
      ),
    [filterOptions]
  )

  const intl = useIntl()
  const methods = useForm<Record<string, boolean | undefined>>({
    defaultValues: initialFilterValues,
    mode: "all",
    reValidateMode: "onChange",
    resolver: zodResolver(z.object({})),
  })

  const { watch, getValues, handleSubmit } = methods
  const petFriendly = watch(RoomPackageCodeEnum.PET_ROOM)
  const allergyFriendly = watch(RoomPackageCodeEnum.ALLERGY_ROOM)

  const selectedFilters = getValues()

  const tooltipText = intl.formatMessage({
    id: "Pet-friendly rooms have an additional fee of 20 EUR per stay",
  })

  const submitFilter = useCallback(() => {
    const data = getValues()
    onFilter(data)
  }, [onFilter, getValues])

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

  return (
    <div className={styles.container}>
      <div className={styles.infoDesktop}>
        <Body color="uiTextHighContrast">
          {intl.formatMessage(
            { id: "Room types available" },
            { numberOfRooms }
          )}
        </Body>
      </div>
      <div className={styles.infoMobile}>
        <div className={styles.filterInfo}>
          <Caption type="label" color="burgundy" textTransform="uppercase">
            {intl.formatMessage({ id: "Filter" })}
          </Caption>
          <Caption type="label" color="burgundy">
            {Object.entries(selectedFilters)
              .filter(([_, value]) => value)
              .map(([key]) => intl.formatMessage({ id: key }))
              .join(", ")}
          </Caption>
        </div>
        <Caption color="uiTextHighContrast">
          {intl.formatMessage(
            { id: "Room types available" },
            { numberOfRooms }
          )}
        </Caption>
      </div>
      <FormProvider {...methods}>
        <form onSubmit={handleSubmit(submitFilter)}>
          <div className={styles.roomsFilter}>
            {filterOptions.map((option) => {
              const { code, description } = option
              const isPetRoom = code === RoomPackageCodeEnum.PET_ROOM
              const isAllergyRoom = code === RoomPackageCodeEnum.ALLERGY_ROOM
              const isDisabled =
                (isAllergyRoom && petFriendly) || (isPetRoom && allergyFriendly)

              const checkboxChip = (
                <CheckboxChip
                  name={code}
                  key={code}
                  label={intl.formatMessage({ id: description })}
                  disabled={isDisabled}
                  selected={getValues(code)}
                  Icon={getIconForFeatureCode(code)}
                  hasTooltip={isPetRoom}
                />
              )

              return isPetRoom ? (
                <Tooltip
                  key={option.code}
                  text={tooltipText}
                  position="bottom"
                  arrow="right"
                >
                  {checkboxChip}
                </Tooltip>
              ) : (
                checkboxChip
              )
            })}
          </div>
        </form>
      </FormProvider>
    </div>
  )
}
