"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import { useIntl } from "react-intl"

import { useGuestsRoomsStore } from "@/stores/guests-rooms"

import { guestRoomsSchema } from "@/components/Forms/BookingWidget/schema"
import Body from "@/components/TempDesignSystem/Text/Body"

import GuestsRoomsPicker from "./GuestsRoomsPicker"

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

export default function GuestsRoomsPickerForm() {
  const intl = useIntl()
  const [isOpen, setIsOpen] = useState(false)
  const { rooms, adultCount, childCount, setIsValidated } = useGuestsRoomsStore(
    (state) => ({
      rooms: state.rooms,
      adultCount: state.adultCount,
      childCount: state.childCount,
      setIsValidated: state.setIsValidated,
    })
  )
  const ref = useRef<HTMLDivElement | null>(null)
  function handleOnClick() {
    setIsOpen((prevIsOpen) => !prevIsOpen)
  }
  const closePicker = useCallback(() => {
    const guestRoomsValidData = guestRoomsSchema.safeParse(rooms)
    if (guestRoomsValidData.success) {
      setIsOpen(false)
      setIsValidated(false)
    } else {
      setIsValidated(true)
    }
  }, [rooms, setIsValidated, setIsOpen])

  useEffect(() => {
    function handleClickOutside(evt: Event) {
      const target = evt.target as HTMLElement
      if (ref.current && target && !ref.current.contains(target)) {
        closePicker()
      }
    }
    document.addEventListener("click", handleClickOutside)
    return () => {
      document.removeEventListener("click", handleClickOutside)
    }
  }, [closePicker])

  return (
    <div className={styles.container} data-isopen={isOpen} ref={ref}>
      <button className={styles.btn} onClick={handleOnClick} type="button">
        <Body className={styles.body}>
          {intl.formatMessage(
            { id: "booking.rooms" },
            { totalRooms: rooms.length }
          )}
          {", "}
          {intl.formatMessage(
            { id: "booking.adults" },
            { totalAdults: adultCount }
          )}
          {childCount > 0
            ? ", " +
              intl.formatMessage(
                { id: "booking.children" },
                { totalChildren: childCount }
              )
            : null}
        </Body>
      </button>
      <div aria-modal className={styles.hideWrapper} role="dialog">
        <GuestsRoomsPicker closePicker={closePicker} />
      </div>
    </div>
  )
}
