"use client"

import { useEffect, useRef, useState } from "react"
import { useFormContext, useWatch } from "react-hook-form"
import { useIntl } from "react-intl"

import Body from "@/components/TempDesignSystem/Text/Body"

import GuestsRoomsPicker from "./GuestsRoomsPicker"

import styles from "./guests-rooms-picker.module.css"

import {
  GuestsRoom,
  GuestsRoomsFormProps,
} from "@/types/components/bookingWidget/guestsRoomsPicker"

export default function GuestsRoomsPickerForm({
  name = "rooms",
}: GuestsRoomsFormProps) {
  const intl = useIntl()
  const [isOpen, setIsOpen] = useState(false)
  const selectedGuests = useWatch({ name })
  const { register, setValue } = useFormContext()
  const ref = useRef<HTMLDivElement | null>(null)
  function handleOnClick() {
    setIsOpen((prevIsOpen) => !prevIsOpen)
  }
  function handleSelectGuest(selected: GuestsRoom[]) {
    setValue(name, selected)
  }
  useEffect(() => {
    function handleClickOutside(evt: Event) {
      const target = evt.target as HTMLElement
      if (ref.current && target && !ref.current.contains(target)) {
        setIsOpen(false)
      }
    }
    document.addEventListener("click", handleClickOutside)
    return () => {
      document.removeEventListener("click", handleClickOutside)
    }
  }, [setIsOpen])

  let selectedAdultsCount = 0
  let selectedChildrenCount = 0
  selectedGuests.forEach((room: GuestsRoom) => {
    selectedAdultsCount = selectedAdultsCount + room.adults
    selectedChildrenCount =
      selectedChildrenCount + (room.children ? room.children.length : 0)
  })
  const selectedRoomsCount = selectedGuests.length
  const childCountLabel =
    (selectedChildrenCount > 1
      ? intl.formatMessage({ id: "Children" })
      : intl.formatMessage({ id: "Child" })) + ", "

  return (
    <div className={styles.container} data-isopen={isOpen} ref={ref}>
      <button className={styles.btn} onClick={handleOnClick} type="button">
        <Body className={styles.body}>
          {selectedAdultsCount}{" "}
          {selectedAdultsCount > 1
            ? intl.formatMessage({ id: "Adults" })
            : intl.formatMessage({ id: "Adult" })}{" "}
          {", "}
          {selectedChildrenCount > 0
            ? selectedChildrenCount + " " + childCountLabel
            : null}
          {selectedRoomsCount}{" "}
          {selectedRoomsCount > 1
            ? intl.formatMessage({ id: "Rooms" })
            : intl.formatMessage({ id: "Room" })}
        </Body>
      </button>
      <div aria-modal className={styles.hideWrapper} role="dialog">
        <GuestsRoomsPicker
          handleOnSelect={handleSelectGuest}
          initialSelected={selectedGuests}
          closePicker={handleOnClick}
        />
      </div>
    </div>
  )
}
