import { useIntl } from "react-intl"

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

import ChildInfoSelector from "./ChildInfoSelector"

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

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

export default function ChildSelector({
  roomChildren = [],
  adultCount = 1,
  updateChildren = (children: Child[]) => {},
}: ChildSelectorProps) {
  const intl = useIntl()
  const childrenLabel = intl.formatMessage({ id: "Children" })

  function decreaseChildren() {
    if (roomChildren.length < 1) {
      return
    }
    roomChildren.pop()
    updateChildren(roomChildren)
  }

  function increaseChildren() {
    if (roomChildren.length > 5) {
      return
    }
    roomChildren.push({ age: -1, bed: -1 })
    updateChildren(roomChildren)
  }

  function updateChildInfo(child: Child, index: number) {
    roomChildren[index] = child
    updateChildren(roomChildren)
  }

  const childInAdultsBedIndices: number[] = []
  let availableInAdultsBed = adultCount
  const availableBedTypes: ChildBed[] = [
    { label: intl.formatMessage({ id: "In adults bed" }), value: 0 },
    { label: intl.formatMessage({ id: "In crib" }), value: 1 },
    { label: intl.formatMessage({ id: "In extra bed" }), value: 2 },
  ]

  const childBedTypes: ChildBed[][] = []
  for (let i = 0; i < roomChildren.length; i++) {
    if (roomChildren[i].bed == 0 && availableInAdultsBed > 0) {
      childInAdultsBedIndices.push(i)
      availableInAdultsBed = availableInAdultsBed - 1
    }
  }
  roomChildren.forEach((child, index) => {
    let types: typeof availableBedTypes = []
    if (
      child.age <= 5 &&
      (availableInAdultsBed > 0 || childInAdultsBedIndices.indexOf(index) != -1)
    ) {
      types.push(availableBedTypes[0])
    }
    if (child.age < 3) {
      types.push(availableBedTypes[1])
    }
    if (child.age > 2) {
      types.push(availableBedTypes[2])
    }
    childBedTypes[index] = types
  })

  return (
    <>
      <section className={styles.container}>
        <Caption>{childrenLabel}</Caption>
        <Button intent="text" size="small" onClick={decreaseChildren}>
          -
        </Button>
        <span className={styles.textCenter}>{roomChildren.length}</span>
        <Button intent="text" size="small" onClick={increaseChildren}>
          +
        </Button>
      </section>
      {roomChildren.map((child, index) => (
        <div key={index} className={styles.childInfoContainer}>
          <ChildInfoSelector
            index={index}
            child={child}
            availableBedTypes={childBedTypes[index]}
            updateChild={updateChildInfo}
          />
        </div>
      ))}
    </>
  )
}
