"use client"
import { Checkbox, CheckboxGroup } from "react-aria-components"
import { Controller, useFormContext } from "react-hook-form"

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"

import { useRatesStore } from "@/stores/select-rate"

import { getIconNameByPackageCode } from "../../utils"
import PetRoomMessage from "./PetRoomMessage"
import {
  checkIsAllergyRoom,
  checkIsPetRoom,
  includesAllergyRoom,
  includesPetRoom,
} from "./utils"

import styles from "./checkbox.module.css"

import type { FormValues } from "../formValues"

export default function Checkboxes() {
  const packageOptions = useRatesStore((state) => state.packageOptions)
  const { control } = useFormContext<FormValues>()
  return (
    <Controller
      control={control}
      name="selectedPackages"
      render={({ field }) => {
        const allergyRoomSelected = includesAllergyRoom(field.value)
        const petRoomSelected = includesPetRoom(field.value)
        return (
          <CheckboxGroup {...field} className={styles.checkboxGroup}>
            {packageOptions.map((option) => {
              const isAllergyRoom = checkIsAllergyRoom(option.code)
              const isPetRoom = checkIsPetRoom(option.code)
              const isDisabled =
                (isPetRoom && allergyRoomSelected) ||
                (isAllergyRoom && petRoomSelected)

              const isSelected = field.value.includes(option.code)
              const iconName = getIconNameByPackageCode(option.code)

              return (
                <div key={option.code} className={styles.checkboxWrapper}>
                  <Checkbox
                    key={option.code}
                    className={styles.checkboxField}
                    isDisabled={isDisabled}
                    value={option.code}
                  >
                    <span className={styles.checkbox}>
                      {isSelected ? (
                        <MaterialIcon icon="check" color="Icon/Inverted" />
                      ) : null}
                    </span>
                    <Typography
                      className={styles.text}
                      variant="Body/Paragraph/mdRegular"
                    >
                      <span>{option.description}</span>
                    </Typography>
                    {iconName ? (
                      <MaterialIcon icon={iconName} color="Icon/Default" />
                    ) : null}
                  </Checkbox>
                  {isPetRoom ? <PetRoomMessage /> : null}
                </div>
              )
            })}
          </CheckboxGroup>
        )
      }}
    />
  )
}
