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

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

import Select from "@/components/TempDesignSystem/Select"

import { BedTypeEnum } from "@/types/components/bookingWidget/enums"
import {
  ChildBed,
  ChildInfoSelectorProps,
} from "@/types/components/bookingWidget/guestsRoomsPicker"

export default function ChildInfoSelector({
  child = { age: -1, bed: -1 },
  index = 0,
  roomIndex = 0,
}: ChildInfoSelectorProps) {
  const intl = useIntl()
  const ageLabel = intl.formatMessage({ id: "Age" })
  const ageReqdErrMsg = intl.formatMessage({ id: "Child age is required" })
  const bedLabel = intl.formatMessage({ id: "Bed" })
  const { setValue } = useFormContext()
  const { adults, childrenInAdultsBed } = guestsRoomsStore().rooms[roomIndex]
  const {
    isValidated,
    updateChildAge,
    updateChildBed,
    increaseChildInAdultsBed,
    decreaseChildInAdultsBed,
  } = guestsRoomsStore()

  const ageList = [
    { label: "0", value: 0 },
    { label: "1", value: 1 },
    { label: "2", value: 2 },
    { label: "3", value: 3 },
    { label: "4", value: 4 },
    { label: "5", value: 5 },
    { label: "6", value: 6 },
    { label: "7", value: 7 },
    { label: "8", value: 8 },
    { label: "9", value: 9 },
    { label: "10", value: 10 },
    { label: "11", value: 11 },
    { label: "12", value: 12 },
  ]

  function updateSelectedAge(age: number) {
    updateChildAge(age, roomIndex, index)
    setValue(`rooms.${roomIndex}.children.${index}.age`, age, {
      shouldTouch: true,
    })
    const availableBedTypes = getAvailableBeds(age)
    updateSelectedBed(availableBedTypes[0].value)
  }

  function updateSelectedBed(bed: number) {
    if (bed == BedTypeEnum["In adults bed"] && childrenInAdultsBed < adults) {
      increaseChildInAdultsBed(roomIndex)
    } else if (child.bed == BedTypeEnum["In adults bed"]) {
      decreaseChildInAdultsBed(roomIndex)
    }
    updateChildBed(bed, roomIndex, index)
    setValue(`rooms.${roomIndex}.children.${index}.bed`, bed)
  }

  const allBedTypes: ChildBed[] = [
    {
      label: intl.formatMessage({ id: "In adults bed" }),
      value: BedTypeEnum["In adults bed"],
    },
    {
      label: intl.formatMessage({ id: "In crib" }),
      value: BedTypeEnum["In crib"],
    },
    {
      label: intl.formatMessage({ id: "In extra bed" }),
      value: BedTypeEnum["In extra bed"],
    },
  ]

  function getAvailableBeds(age: number) {
    let availableBedTypes: ChildBed[] = []
    if (age <= 5 && (adults > childrenInAdultsBed || child.bed === 0)) {
      availableBedTypes.push(allBedTypes[0])
    }
    if (age < 3) {
      availableBedTypes.push(allBedTypes[1])
    }
    if (age > 2) {
      availableBedTypes.push(allBedTypes[2])
    }
    return availableBedTypes
  }

  return (
    <>
      <div>
        <Select
          required={true}
          items={ageList}
          label={ageLabel}
          aria-label={ageLabel}
          value={child.age}
          onSelect={(key) => {
            updateSelectedAge(parseInt(key.toString()))
          }}
          name={`rooms.${roomIndex}.children.${index}.age`}
          placeholder={ageLabel}
        />
        {isValidated && child.age < 0 ? <span>{ageReqdErrMsg}</span> : null}
      </div>
      <div>
        {child.age !== -1 ? (
          <Select
            items={getAvailableBeds(child.age)}
            label={bedLabel}
            aria-label={bedLabel}
            value={child.bed}
            onSelect={(key) => {
              updateSelectedBed(parseInt(key.toString()))
            }}
            name={`rooms.${roomIndex}.children.${index}.age`}
            placeholder={bedLabel}
          />
        ) : null}
      </div>
    </>
  )
}
