"use client"

import { useFormContext } from "react-hook-form"
import { useIntl } from "react-intl"

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

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

import Counter from "../Counter"

import styles from "./adult-selector.module.css"

import { BedTypeEnum } from "@/types/components/bookingWidget/enums"
import {
  AdultSelectorProps,
  Child,
} from "@/types/components/bookingWidget/guestsRoomsPicker"

export default function AdultSelector({ roomIndex = 0 }: AdultSelectorProps) {
  const intl = useIntl()
  const adultsLabel = intl.formatMessage({ id: "Adults" })
  const { setValue } = useFormContext()
  const { adults, children, childrenInAdultsBed } = useGuestsRoomsStore(
    (state) => ({ ...state.rooms[roomIndex] })
  )
  const increaseAdults = useGuestsRoomsStore.use.increaseAdults()
  const decreaseAdults = useGuestsRoomsStore.use.decreaseAdults()

  function increaseAdultsCount(roomIndex: number) {
    if (adults < 6) {
      increaseAdults(roomIndex)
      setValue(`rooms.${roomIndex}.adults`, adults + 1)
    }
  }

  function decreaseAdultsCount(roomIndex: number) {
    if (adults > 1) {
      decreaseAdults(roomIndex)
      setValue(`rooms.${roomIndex}.adults`, adults - 1)
      if (childrenInAdultsBed > adults) {
        const toUpdateIndex = children.findIndex(
          (child: Child) => child.bed == BedTypeEnum.IN_ADULTS_BED
        )
        if (toUpdateIndex != -1) {
          setValue(
            `rooms.${roomIndex}.children.${toUpdateIndex}.bed`,
            children[toUpdateIndex].age < 3
              ? BedTypeEnum.IN_CRIB
              : BedTypeEnum.IN_EXTRA_BED
          )
        }
      }
    }
  }

  return (
    <section className={styles.container}>
      <Caption color="uiTextHighContrast" textTransform="bold">
        {adultsLabel}
      </Caption>
      <Counter
        count={adults}
        handleOnDecrease={() => {
          decreaseAdultsCount(roomIndex)
        }}
        handleOnIncrease={() => {
          increaseAdultsCount(roomIndex)
        }}
        disableDecrease={adults == 1}
        disableIncrease={adults == 6}
      />
    </section>
  )
}
