"use client"

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

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

import { MinusIcon, PlusIcon } from "@/components/Icons"
import Button from "@/components/TempDesignSystem/Button"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"

import ChildInfoSelector from "./ChildInfoSelector"

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

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

export default function ChildSelector({ roomIndex = 0 }: ChildSelectorProps) {
  const intl = useIntl()
  const childrenLabel = intl.formatMessage({ id: "Children" })
  const { setValue } = useFormContext()
  const { children } = useGuestsRoomsStore((state) => state.rooms[roomIndex])
  const { increaseChildren, decreaseChildren } = useGuestsRoomsStore()

  function increaseChildrenCount(roomIndex: number) {
    if (children.length < 5) {
      increaseChildren(roomIndex)
      setValue(`rooms.${roomIndex}.children.${children.length}`, {
        age: -1,
        bed: -1,
      })
    }
  }
  function decreaseChildrenCount(roomIndex: number) {
    if (children.length > 0) {
      decreaseChildren(roomIndex)
      let newChildrenList = JSON.parse(JSON.stringify(children))
      newChildrenList.pop()
      setValue(`rooms.${roomIndex}.children`, newChildrenList)
    }
  }

  return (
    <>
      <section className={styles.container}>
        <Caption color="uiTextHighContrast" textTransform="bold">
          {childrenLabel}
        </Caption>
        <div className={styles.counterContainer}>
          <Button
            className={styles.counterBtn}
            intent="elevated"
            onClick={() => {
              decreaseChildrenCount(roomIndex)
            }}
            size="small"
            theme="base"
            variant="icon"
            wrapping={true}
            disabled={children.length == 0}
          >
            <MinusIcon color="burgundy" />
          </Button>
          <Body color="textHighContrast" textAlign="center">
            {children.length}
          </Body>
          <Button
            className={styles.counterBtn}
            onClick={() => {
              increaseChildrenCount(roomIndex)
            }}
            intent="elevated"
            variant="icon"
            theme="base"
            wrapping={true}
            size="small"
            disabled={children.length == 5}
          >
            <PlusIcon color="burgundy" />
          </Button>
        </div>
      </section>
      {children.map((child, index) => (
        <ChildInfoSelector
          roomIndex={roomIndex}
          index={index}
          child={child}
          key={index}
        />
      ))}
    </>
  )
}
