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

import { dt } from "@/lib/dt"
import { useMyStayStore } from "@/stores/my-stay"

import Modal from "@/components/HotelReservation/MyStay/Modal"
import { toast } from "@/components/TempDesignSystem/Toasts"

import NoAvailability from "./Alerts/NoAvailability"
import NewDates from "./NewDates"

import {
  type ChangeDatesFormProps,
  type ChangeDatesSchema,
  changeDatesSchema,
} from "@/types/components/hotelReservation/myStay/changeDates"

export default function Form({
  checkAvailability,
  closeModal,
  noAvailability,
}: ChangeDatesFormProps) {
  const intl = useIntl()

  const { checkInDate, checkOutDate } = useMyStayStore((state) => ({
    checkInDate: state.bookedRoom.checkInDate,
    checkOutDate: state.bookedRoom.checkOutDate,
  }))

  const methods = useForm<ChangeDatesSchema>({
    defaultValues: {
      checkInDate: dt(checkInDate).format("YYYY-MM-DD"),
      checkOutDate: dt(checkOutDate).format("YYYY-MM-DD"),
    },
    resolver: zodResolver(changeDatesSchema),
  })

  async function handleSubmit(values: ChangeDatesSchema) {
    if (values.checkInDate && values.checkOutDate) {
      await checkAvailability(values.checkInDate, values.checkOutDate)
    } else {
      toast.error(
        intl.formatMessage({
          defaultMessage: "Please select dates",
        })
      )
    }
  }

  return (
    <FormProvider {...methods}>
      <form onSubmit={methods.handleSubmit(handleSubmit)}>
        <Modal.Content>
          <Modal.Content.Header
            handleClose={closeModal}
            title={intl.formatMessage({
              defaultMessage: "New dates for the stay",
            })}
          />
          <Modal.Content.Body>
            {noAvailability && <NoAvailability />}
            <NewDates checkInDate={checkInDate} checkOutDate={checkOutDate} />
          </Modal.Content.Body>
          <Modal.Content.Footer>
            <Modal.Content.Footer.Secondary onClick={closeModal}>
              {intl.formatMessage({ defaultMessage: "Back" })}
            </Modal.Content.Footer.Secondary>
            <Modal.Content.Footer.Primary
              disabled={methods.formState.isSubmitting}
              intent="secondary"
              type="submit"
            >
              {intl.formatMessage({
                defaultMessage: "Check availability",
              })}
            </Modal.Content.Footer.Primary>
          </Modal.Content.Footer>
        </Modal.Content>
      </form>
    </FormProvider>
  )
}
