"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 { ChildBedMapEnum } 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, child, childrenInAdultsBed } = useGuestsRoomsStore(
    (state) => state.rooms[roomIndex]
  )
  const increaseAdults = useGuestsRoomsStore((state) => state.increaseAdults)
  const decreaseAdults = useGuestsRoomsStore((state) => state.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 = child.findIndex(
          (child: Child) => child.bed == ChildBedMapEnum.IN_ADULTS_BED
        )
        if (toUpdateIndex != -1) {
          setValue(
            `rooms.${roomIndex}.children.${toUpdateIndex}.bed`,
            child[toUpdateIndex].age < 3
              ? ChildBedMapEnum.IN_CRIB
              : ChildBedMapEnum.IN_EXTRA_BED
          )
        }
      }
    }
  }

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