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

import { dt } from "@/lib/dt"
import { StickyElementNameEnum } from "@/stores/sticky-position"

import Form, {
  BookingWidgetFormSkeleton,
} from "@/components/Forms/BookingWidget"
import { bookingWidgetSchema } from "@/components/Forms/BookingWidget/schema"
import { CloseLargeIcon } from "@/components/Icons"
import useStickyPosition from "@/hooks/useStickyPosition"
import { debounce } from "@/utils/debounce"
import isValidJson from "@/utils/isValidJson"
import { convertSearchParamsToObj } from "@/utils/url"

import MobileToggleButton, {
  MobileToggleButtonSkeleton,
} from "./MobileToggleButton"

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

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

export default function BookingWidgetClient({
  locations,
  type,
  bookingWidgetSearchParams,
}: BookingWidgetClientProps) {
  const [isOpen, setIsOpen] = useState(false)
  const bookingWidgetRef = useRef(null)
  useStickyPosition({
    ref: bookingWidgetRef,
    name: StickyElementNameEnum.BOOKING_WIDGET,
  })

  const bookingWidgetSearchData = bookingWidgetSearchParams
    ? convertSearchParamsToObj<BookingWidgetSearchData>(
        bookingWidgetSearchParams
      )
    : undefined

  const getLocationObj = (destination: string): Location | undefined => {
    if (destination) {
      const location: Location | undefined = locations.find((location) => {
        return (
          location.name.toLowerCase() === destination.toLowerCase() ||
          //@ts-ignore (due to operaId not property error)
          (location.operaId && location.operaId == destination)
        )
      })
      return location
    }
    return undefined
  }

  const reqFromDate = bookingWidgetSearchData?.fromDate?.toString()
  const reqToDate = bookingWidgetSearchData?.toDate?.toString()

  const parsedFromDate = reqFromDate ? dt(reqFromDate) : undefined
  const parsedToDate = reqToDate ? dt(reqToDate) : undefined

  const now = dt()

  const isDateParamValid =
    parsedFromDate &&
    parsedToDate &&
    parsedFromDate.isSameOrAfter(now, "day") &&
    parsedToDate.isAfter(parsedFromDate)

  const selectedLocation = bookingWidgetSearchData
    ? getLocationObj(
        (bookingWidgetSearchData.hotelId ??
          bookingWidgetSearchData.city) as string
      )
    : undefined

  const defaultRoomsData: BookingWidgetSchema["rooms"] =
    bookingWidgetSearchData?.rooms?.map((room) => ({
      adults: room.adults,
      childrenInRoom: room.childrenInRoom ?? [],
    })) ?? [
      {
        adults: 1,
        childrenInRoom: [],
      },
    ]

  const methods = useForm<BookingWidgetSchema>({
    defaultValues: {
      search: selectedLocation?.name ?? "",
      location: selectedLocation ? JSON.stringify(selectedLocation) : 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.
        fromDate: isDateParamValid
          ? parsedFromDate.format("YYYY-MM-DD")
          : now.utc().format("YYYY-MM-DD"),
        toDate: isDateParamValid
          ? parsedToDate.format("YYYY-MM-DD")
          : now.utc().add(1, "day").format("YYYY-MM-DD"),
      },
      bookingCode: "",
      redemption: false,
      voucher: false,
      rooms: defaultRoomsData,
    },
    shouldFocusError: false,
    mode: "onSubmit",
    resolver: zodResolver(bookingWidgetSchema),
    reValidateMode: "onSubmit",
  })

  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)
      }
    }
  }, [])

  useEffect(() => {
    const sessionStorageSearchData =
      typeof window !== "undefined"
        ? sessionStorage.getItem("searchData")
        : undefined

    const initialSelectedLocation: Location | undefined =
      sessionStorageSearchData && isValidJson(sessionStorageSearchData)
        ? JSON.parse(sessionStorageSearchData)
        : undefined

    !selectedLocation?.name &&
      initialSelectedLocation?.name &&
      methods.setValue("search", initialSelectedLocation.name)
    !selectedLocation &&
      sessionStorageSearchData &&
      methods.setValue("location", encodeURIComponent(sessionStorageSearchData))
  }, [methods, selectedLocation])

  return (
    <FormProvider {...methods}>
      <section
        ref={bookingWidgetRef}
        className={styles.wrapper}
        data-open={isOpen}
      >
        <MobileToggleButton openMobileSearch={openMobileSearch} />
        <div className={styles.formContainer}>
          <button
            className={styles.close}
            onClick={closeMobileSearch}
            type="button"
          >
            <CloseLargeIcon />
          </button>
          <Form locations={locations} type={type} onClose={closeMobileSearch} />
        </div>
      </section>
      <div className={styles.backdrop} onClick={closeMobileSearch} />
    </FormProvider>
  )
}

export function BookingWidgetSkeleton() {
  return (
    <>
      <section className={styles.wrapper} style={{ top: 0 }}>
        <MobileToggleButtonSkeleton />
        <div className={styles.formContainer}>
          <BookingWidgetFormSkeleton />
        </div>
      </section>
    </>
  )
}
