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

import { dt } from "@/lib/dt"

import Form from "@/components/Forms/BookingWidget"
import { bookingWidgetSchema } from "@/components/Forms/BookingWidget/schema"
import { CloseLarge } from "@/components/Icons"
import { debounce } from "@/utils/debounce"

import MobileToggleButton from "./MobileToggleButton"

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

import type {
  BookingWidgetClientProps,
  BookingWidgetSchema,
} from "@/types/components/bookingWidget"
import type { Location } from "@/types/trpc/routers/hotel/locations"

export default function BookingWidgetClient({
  locations,
}: BookingWidgetClientProps) {
  const [isOpen, setIsOpen] = useState(false)

  const sessionStorageSearchData =
    typeof window !== "undefined"
      ? sessionStorage.getItem("searchData")
      : undefined
  const initialSelectedLocation: Location | undefined = sessionStorageSearchData
    ? JSON.parse(sessionStorageSearchData)
    : undefined
  const methods = useForm<BookingWidgetSchema>({
    defaultValues: {
      search: initialSelectedLocation?.name ?? "",
      location: sessionStorageSearchData
        ? encodeURIComponent(sessionStorageSearchData)
        : undefined,
      date: {
        // UTC is required to handle requests from far away timezones https://scandichotels.atlassian.net/browse/SWAP-6375 & PET-507
        // This is specifically to handle timezones falling in different dates.
        from: dt().utc().format("YYYY-MM-DD"),
        to: dt().utc().add(1, "day").format("YYYY-MM-DD"),
      },
      bookingCode: "",
      redemption: false,
      voucher: false,
      rooms: [
        {
          adults: 1,
          children: [],
        },
      ],
    },
    shouldFocusError: false,
    mode: "all",
    resolver: zodResolver(bookingWidgetSchema),
    reValidateMode: "onChange",
  })

  function closeMobileSearch() {
    setIsOpen(false)
    document.body.style.overflowY = "visible"
  }

  function openMobileSearch() {
    setIsOpen(true)
    document.body.style.overflowY = "hidden"
  }

  useEffect(() => {
    const debouncedResizeHandler = debounce(function ([
      entry,
    ]: ResizeObserverEntry[]) {
      if (entry.contentRect.width > 1366) {
        closeMobileSearch()
      }
    })
    const observer = new ResizeObserver(debouncedResizeHandler)

    observer.observe(document.body)

    return () => {
      if (observer) {
        observer.unobserve(document.body)
      }
    }
  }, [])

  return (
    <FormProvider {...methods}>
      <section className={styles.container} data-open={isOpen}>
        <button
          className={styles.close}
          onClick={closeMobileSearch}
          type="button"
        >
          <CloseLarge />
        </button>
        <Form locations={locations} />
      </section>
      <MobileToggleButton openMobileSearch={openMobileSearch} />
    </FormProvider>
  )
}
