"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { useCallback, useEffect } from "react"
import { FormProvider, useForm } from "react-hook-form"

import { useEnterDetailsStore } from "@/stores/enter-details"

import { KingBedIcon } from "@/components/Icons"
import RadioCard from "@/components/TempDesignSystem/Form/ChoiceCard/Radio"

import { bedTypeFormSchema } from "./schema"

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

import type {
  BedTypeFormSchema,
  BedTypeProps,
} from "@/types/components/hotelReservation/enterDetails/bedType"

export default function BedType({ bedTypes }: BedTypeProps) {
  const bedType = useEnterDetailsStore((state) => state.userData.bedType)

  const methods = useForm<BedTypeFormSchema>({
    defaultValues: bedType?.roomTypeCode
      ? {
          bedType: bedType.roomTypeCode,
        }
      : undefined,
    criteriaMode: "all",
    mode: "all",
    resolver: zodResolver(bedTypeFormSchema),
    reValidateMode: "onChange",
  })

  const completeStep = useEnterDetailsStore((state) => state.completeStep)

  const onSubmit = useCallback(
    (bedTypeRoomCode: BedTypeFormSchema) => {
      const matchingRoom = bedTypes.find(
        (roomType) => roomType.value === bedTypeRoomCode.bedType
      )
      if (matchingRoom) {
        const bedType = {
          description: matchingRoom.description,
          roomTypeCode: matchingRoom.value,
        }
        completeStep({ bedType })
      }
    },
    [completeStep, bedTypes]
  )

  useEffect(() => {
    if (methods.formState.isSubmitting) {
      return
    }

    const subscription = methods.watch(() => methods.handleSubmit(onSubmit)())
    return () => subscription.unsubscribe()
  }, [methods, onSubmit])

  return (
    <FormProvider {...methods}>
      <form className={styles.form} onSubmit={methods.handleSubmit(onSubmit)}>
        {bedTypes.map((roomType) => {
          const width =
            roomType.size.max === roomType.size.min
              ? `${roomType.size.min} cm`
              : `${roomType.size.min} cm - ${roomType.size.max} cm`
          return (
            <RadioCard
              key={roomType.value}
              Icon={KingBedIcon}
              iconWidth={46}
              id={roomType.value}
              name="bedType"
              subtitle={width}
              title={roomType.description}
              value={roomType.value}
            />
          )
        })}
      </form>
    </FormProvider>
  )
}
