"use client"

import {
  Button,
  Dialog,
  DialogTrigger,
  Modal,
  Popover,
} from "react-aria-components"
import { useFormContext } from "react-hook-form"
import { useIntl } from "react-intl"

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

import PickerForm from "./Form"

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

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

export default function GuestsRoomsPickerForm() {
  const { watch } = useFormContext()

  const rooms = watch("rooms") as GuestsRoom[]

  return (
    <>
      <DialogTrigger>
        <Trigger rooms={rooms} className={styles.triggerMobile} />
        <Modal className="my-modal">
          <Dialog className={styles.pickerContainerMobile}>
            {({ close }) => <PickerForm rooms={rooms} onClose={close} />}
          </Dialog>
        </Modal>
      </DialogTrigger>
      <DialogTrigger>
        <Trigger rooms={rooms} className={styles.triggerDesktop} />
        <Popover placement="bottom start" offset={22}>
          <Dialog className={styles.pickerContainerDesktop}>
            {({ close }) => <PickerForm rooms={rooms} onClose={close} />}
          </Dialog>
        </Popover>
      </DialogTrigger>
    </>
  )
}

function Trigger({
  rooms,
  className,
}: {
  rooms: GuestsRoom[]
  className: string
}) {
  const intl = useIntl()

  return (
    <Button className={`${className} ${styles.btn}`} type="button">
      <Body>
        {rooms.map((room, i) => (
          <span key={i}>
            {intl.formatMessage(
              { id: "booking.rooms" },
              { totalRooms: rooms.length }
            )}
            {", "}
            {intl.formatMessage(
              { id: "booking.adults" },
              { totalAdults: room.adults }
            )}
            {room.child.length > 0
              ? ", " +
                intl.formatMessage(
                  { id: "booking.children" },
                  { totalChildren: room.child.length }
                )
              : null}
          </span>
        ))}
      </Body>
    </Button>
  )
}
