"use client"
import { useState } from "react"
import { useIntl } from "react-intl"

import useLang from "@/hooks/useLang"

import Button from "../TempDesignSystem/Button"
import Divider from "../TempDesignSystem/Divider"
import GuestsRoomPicker from "./GuestsRoomPicker"

import styles from "./guests-rooms-picker.module.css"

import {
  GuestsRoom,
  GuestsRoomsPickerProps,
} from "@/types/components/bookingWidget/guestsRoomsPicker"

export default function GuestsRoomsPicker({
  handleOnSelect,
  initialSelected = [
    {
      adults: 1,
      children: [],
    },
  ],
  closePicker,
  isValid,
}: GuestsRoomsPickerProps) {
  const lang = useLang()
  const intl = useIntl()
  const doneLabel = intl.formatMessage({ id: "Done" })
  const [selectedGuests, setSelectedGuests] =
    useState<GuestsRoom[]>(initialSelected)

  function handleSelectRoomGuests(
    selectedGuestsRoom: GuestsRoom,
    index: number
  ) {
    let updatedSelectedGuests = JSON.parse(JSON.stringify(selectedGuests))
    updatedSelectedGuests[index] = selectedGuestsRoom
    handleOnSelect(updatedSelectedGuests)
    setSelectedGuests(updatedSelectedGuests)
  }

  // Not in MVP scope
  function addRoom() {
    if (selectedGuests.length < 4) {
      let updatedSelectedGuests = JSON.parse(JSON.stringify(selectedGuests))
      updatedSelectedGuests.push({
        adults: 1,
        children: [],
      })
      setSelectedGuests(updatedSelectedGuests)
      handleOnSelect(updatedSelectedGuests)
    }
  }

  // Not in MVP scope
  function removeRoom(index: number) {
    if (selectedGuests.length > 1) {
      let updatedSelectedGuests = JSON.parse(JSON.stringify(selectedGuests))
      updatedSelectedGuests.splice(index, 1)
      setSelectedGuests(updatedSelectedGuests)
      handleOnSelect(updatedSelectedGuests)
    }
  }

  return (
    <>
      {selectedGuests.map((room, index) => (
        <section className={styles.roomContainer} key={index}>
          <GuestsRoomPicker
            room={room}
            handleOnSelect={handleSelectRoomGuests}
            index={index}
            isValid={isValid}
          />
          {/* Not in MVP
           {index > 0 ? (
            <Button intent="text" onClick={() => removeRoom(index)}>
              Remove Room
            </Button>
          ) : null} */}
          <Divider></Divider>
        </section>
      ))}
      <div className={styles.footer}>
        {/*  Not in MVP
        {selectedGuests.length < 4 ? (
          <Button intent="text" onClick={addRoom}>
            Add Room
          </Button>
        ) : null} */}
        <Button onClick={closePicker} disabled={!isValid}>
          {doneLabel}
        </Button>
      </div>
    </>
  )
}
