"use client"

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

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { REDEMPTION } from "@/constants/booking"

import Button from "../TempDesignSystem/Button"
import { Tooltip } from "../TempDesignSystem/Tooltip"
import { GuestsRoom } from "./GuestsRoom"

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

import type { BookingWidgetSchema } from "@/types/components/bookingWidget"
import type { GuestsRoom as TGuestsRoom } from "@/types/components/bookingWidget/guestsRoomsPicker"

const MAX_ROOMS = 4

interface GuestsRoomsPickerDialogProps {
  rooms: TGuestsRoom[]
  onClose: () => void
}

export default function GuestsRoomsPickerDialog({
  rooms,
  onClose,
}: GuestsRoomsPickerDialogProps) {
  const intl = useIntl()
  const { getFieldState, trigger, setValue, getValues } =
    useFormContext<BookingWidgetSchema>()
  const roomsValue = useWatch<BookingWidgetSchema, "rooms">({ name: "rooms" })
  const addRoomLabel = intl.formatMessage({
    defaultMessage: "Add room",
  })
  const doneLabel = intl.formatMessage({
    defaultMessage: "Done",
  })
  // Disable add room if booking code is either voucher or corporate cheque, or reward night is enabled
  const addRoomDisabledTextForSpecialRate = getValues(REDEMPTION)
    ? intl.formatMessage({
        defaultMessage:
          "Multi-room booking is not available with reward night.",
      })
    : getValues("bookingCode.value")?.toLowerCase().startsWith("vo") &&
      intl.formatMessage({
        defaultMessage:
          "Multi-room booking is not available with this booking code.",
      })

  const handleClose = useCallback(async () => {
    const isValid = await trigger("rooms")
    if (isValid) onClose()
  }, [trigger, onClose])

  const handleAddRoom = useCallback(() => {
    setValue("rooms", [...roomsValue, { adults: 1, childrenInRoom: [] }], {
      shouldValidate: true,
      shouldDirty: true,
    })
  }, [roomsValue, setValue])

  const handleRemoveRoom = useCallback(
    (index: number) => {
      setValue(
        "rooms",
        roomsValue.filter((_, i) => i !== index),
        { shouldValidate: true, shouldDirty: true }
      )
    },
    [roomsValue, setValue]
  )

  // Validate rooms when they change
  useEffect(() => {
    const fieldState = getFieldState("rooms")
    if (fieldState.invalid) trigger("rooms")
  }, [roomsValue, getFieldState, trigger])

  const isInvalid =
    getFieldState("rooms").invalid ||
    roomsValue.some((room) =>
      room.childrenInRoom.some((child) => child.age === undefined)
    )
  const canAddRooms = rooms.length < MAX_ROOMS

  return (
    <>
      <section className={styles.contentWrapper}>
        <header className={styles.header}>
          <button type="button" className={styles.close} onClick={onClose}>
            <MaterialIcon icon="close" />
          </button>
        </header>

        <div className={styles.contentContainer}>
          {rooms.map((room, index) => (
            <GuestsRoom
              key={index}
              room={room}
              index={index}
              onRemove={handleRemoveRoom}
            />
          ))}

          {addRoomDisabledTextForSpecialRate ? (
            <div className={styles.addRoomMobileContainer}>
              <Tooltip
                text={addRoomDisabledTextForSpecialRate}
                position="bottom"
                arrow="left"
              >
                <Button
                  intent="text"
                  variant="icon"
                  wrapping
                  theme="base"
                  fullWidth
                  onPress={handleAddRoom}
                  disabled
                >
                  <MaterialIcon icon="add" color="CurrentColor" />
                  {addRoomLabel}
                </Button>
              </Tooltip>
            </div>
          ) : (
            canAddRooms && (
              <div className={styles.addRoomMobileContainer}>
                <Button
                  className={styles.addRoomBtn}
                  intent="text"
                  variant="icon"
                  wrapping
                  theme="base"
                  fullWidth
                  onPress={handleAddRoom}
                >
                  <MaterialIcon icon="add" color="CurrentColor" />
                  {addRoomLabel}
                </Button>
              </div>
            )
          )}
        </div>
      </section>
      <footer className={styles.footer}>
        {addRoomDisabledTextForSpecialRate ? (
          <div className={styles.hideOnMobile}>
            <Tooltip
              text={addRoomDisabledTextForSpecialRate}
              position="top"
              arrow="left"
            >
              <Button
                intent="text"
                variant="icon"
                wrapping
                theme="base"
                disabled
                onPress={handleAddRoom}
              >
                <MaterialIcon icon="add_circle" color="CurrentColor" />
                {addRoomLabel}
              </Button>
            </Tooltip>
          </div>
        ) : (
          canAddRooms && (
            <div className={styles.hideOnMobile}>
              <Button
                className={styles.addRoomBtn}
                intent="text"
                variant="icon"
                wrapping
                theme="base"
                onPress={handleAddRoom}
              >
                <MaterialIcon icon="add_circle" color="CurrentColor" />
                {addRoomLabel}
              </Button>
            </div>
          )
        )}
        <Button
          onPress={handleClose}
          disabled={isInvalid}
          className={styles.hideOnDesktop}
          intent="tertiary"
          theme="base"
          size="large"
        >
          {doneLabel}
        </Button>
        <Button
          onPress={handleClose}
          disabled={isInvalid}
          className={styles.hideOnMobile}
          intent="tertiary"
          theme="base"
          size="small"
        >
          {doneLabel}
        </Button>
      </footer>
    </>
  )
}
