"use client"

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

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 {
  Child,
  SelectorProps,
} from "@/types/components/bookingWidget/guestsRoomsPicker"

export default function AdultSelector({
  roomIndex = 0,
  currentAdults,
  currentChildren,
  childrenInAdultsBed,
}: SelectorProps) {
  const intl = useIntl()
  const adultsLabel = intl.formatMessage({ id: "Adults" })
  const { setValue } = useFormContext()

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

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

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