"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 { Highlight } from "@/components/TempDesignSystem/Form/ChoiceCard/_Card"
import RadioCard from "@/components/TempDesignSystem/Form/ChoiceCard/Radio"

import { breakfastFormSchema } from "./schema"

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

import type {
  BreakfastFormSchema,
  BreakfastProps,
} from "@/types/components/enterDetails/breakfast"
import { BreakfastPackageEnum } from "@/types/enums/breakfast"

export default function Breakfast({ packages }: BreakfastProps) {
  const intl = useIntl()

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

  let defaultValues = undefined
  if (breakfast === BreakfastPackageEnum.NO_BREAKFAST) {
    defaultValues = { breakfast: BreakfastPackageEnum.NO_BREAKFAST }
  } else if (breakfast?.code) {
    defaultValues = { breakfast: breakfast.code }
  }
  const methods = useForm<BreakfastFormSchema>({
    defaultValues,
    criteriaMode: "all",
    mode: "all",
    resolver: zodResolver(breakfastFormSchema),
    reValidateMode: "onChange",
  })

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

  const onSubmit = useCallback(
    (values: BreakfastFormSchema) => {
      const pkg = packages?.find((p) => p.code === values.breakfast)
      if (pkg) {
        completeStep({ breakfast: pkg })
      } else {
        completeStep({ breakfast: BreakfastPackageEnum.NO_BREAKFAST })
      }
    },
    [completeStep, packages]
  )

  useEffect(() => {
    if (methods.formState.isSubmitting) {
      return
    }
    const subscription = methods.watch(() => methods.handleSubmit(onSubmit)())
    return () => subscription.unsubscribe()
  }, [methods, onSubmit])

  if (!packages) {
    return null
  }

  return (
    <FormProvider {...methods}>
      <form className={styles.form} onSubmit={methods.handleSubmit(onSubmit)}>
        {packages.map((pkg) => (
          <RadioCard
            key={pkg.code}
            id={pkg.code}
            name="breakfast"
            subtitle={
              pkg.code === BreakfastPackageEnum.FREE_MEMBER_BREAKFAST
                ? intl.formatMessage<React.ReactNode>(
                    { id: "breakfast.price.free" },
                    {
                      amount: pkg.originalPrice,
                      currency: pkg.currency,
                      free: (str) => <Highlight>{str}</Highlight>,
                      strikethrough: (str) => <s>{str}</s>,
                    }
                  )
                : intl.formatMessage(
                    { id: "breakfast.price" },
                    {
                      amount: pkg.packagePrice,
                      currency: pkg.currency,
                    }
                  )
            }
            text={intl.formatMessage({
              id: "All our breakfast buffets offer gluten free, vegan, and allergy-friendly options.",
            })}
            title={intl.formatMessage({ id: "Breakfast buffet" })}
            value={pkg.code}
          />
        ))}
        <RadioCard
          id={BreakfastPackageEnum.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={BreakfastPackageEnum.NO_BREAKFAST}
        />
      </form>
    </FormProvider>
  )
}
