"use client"
import { FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"

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

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

import Divider from "@/components/TempDesignSystem/Divider"
import { useRoomContext } from "@/contexts/SelectRate/Room"
import useLang from "@/hooks/useLang"

import Checkboxes from "./Checkboxes"

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

import type { PackageEnum } from "@/types/requests/packages"
import type { FormValues } from "./formValues"

export default function Form({ close }: { close: () => void }) {
  const intl = useIntl()
  const lang = useLang()
  const utils = trpc.useUtils()

  const {
    actions: { removeSelectedPackages, selectPackages, updateRooms },
    bookingRoom,
    selectedPackages,
  } = useRoomContext()
  const booking = useRatesStore((state) => state.booking)

  const methods = useForm<FormValues>({
    values: {
      selectedPackages: selectedPackages.map((pkg) => pkg.code),
    },
  })

  async function getFilteredRates(packages: PackageEnum[]) {
    const filterRates = await utils.hotel.availability.selectRate.room.fetch({
      booking: {
        fromDate: booking.fromDate,
        hotelId: booking.hotelId,
        searchType: booking.searchType,
        toDate: booking.toDate,
        room: {
          ...bookingRoom,
          bookingCode: bookingRoom.rateCode
            ? bookingRoom.bookingCode
            : booking.bookingCode,
          packages,
        },
      },
      lang,
    })
    updateRooms(filterRates?.roomConfigurations)
  }

  function clearSelectedPackages() {
    removeSelectedPackages()
    close()
    getFilteredRates([])
  }

  function onSubmit(data: FormValues) {
    selectPackages(data.selectedPackages)
    close()
    getFilteredRates(data.selectedPackages)
  }

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <Checkboxes />
        <div className={styles.footer}>
          <Divider color="borderDividerSubtle" className={styles.divider} />
          <div className={styles.buttonContainer}>
            <Typography variant="Body/Supporting text (caption)/smBold">
              <Button variant="Tertiary" size="Small" type="submit">
                {intl.formatMessage({ defaultMessage: "Apply" })}
              </Button>
            </Typography>
            <Typography variant="Body/Supporting text (caption)/smBold">
              <Button
                onPress={clearSelectedPackages}
                size="Small"
                variant="Text"
              >
                {intl.formatMessage({
                  defaultMessage: "Clear",
                })}
              </Button>
            </Typography>
          </div>
        </div>
      </form>
    </FormProvider>
  )
}
