"use client"

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

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

import { BreakfastIcon, NoBreakfastIcon } from "@/components/Icons"
import RadioCard from "@/components/TempDesignSystem/Form/ChoiceCard/Radio"

import { breakfastSchema } from "./schema"

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

import type { BreakfastSchema } from "@/types/components/enterDetails/breakfast"
import { breakfastEnum } from "@/types/enums/breakfast"

export default function Breakfast() {
  const intl = useIntl()

  const breakfast = useEnterDetailsStore((state) => state.data.breakfast)

  const methods = useForm<BreakfastSchema>({
    defaultValues: breakfast ? { breakfast } : undefined,
    criteriaMode: "all",
    mode: "all",
    resolver: zodResolver(breakfastSchema),
    reValidateMode: "onChange",
  })

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

  const onSubmit = useCallback(
    (values: BreakfastSchema) => {
      completeStep(values)
    },
    [completeStep]
  )

  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)}>
        <RadioCard
          Icon={BreakfastIcon}
          id={breakfastEnum.BREAKFAST}
          name="breakfast"
          subtitle={intl.formatMessage<React.ReactNode>(
            { id: "<b>{amount} {currency}</b>/night per adult" },
            {
              amount: "150",
              b: (str) => <b>{str}</b>,
              currency: "SEK",
            }
          )}
          text={intl.formatMessage({
            id: "All our breakfast buffets offer gluten free, vegan, and allergy-friendly options.",
          })}
          title={intl.formatMessage({ id: "Breakfast buffet" })}
          value={breakfastEnum.BREAKFAST}
        />
        <RadioCard
          Icon={NoBreakfastIcon}
          id={breakfastEnum.NO_BREAKFAST}
          name="breakfast"
          subtitle={intl.formatMessage(
            { id: "{amount} {currency}" },
            {
              amount: "0",
              currency: "SEK",
            }
          )}
          text={intl.formatMessage({
            id: "You can always change your mind later and add breakfast at the hotel.",
          })}
          title={intl.formatMessage({ id: "No breakfast" })}
          value={breakfastEnum.NO_BREAKFAST}
        />
      </form>
    </FormProvider>
  )
}
