"use client"
import { useSearchParams } from "next/navigation"
import { useRef } from "react"

import { createDestinationDataStore } from "@/stores/destination-data"

import { DestinationDataContext } from "@/contexts/DestinationData"

import DestinationDataProviderContent from "./Content"

import type { HotelFilters } from "@scandic-hotels/trpc/routers/hotels/filters/output"
import type { DestinationCityListItem } from "@scandic-hotels/trpc/types/destinationCityPage"
import type { DestinationFilters } from "@scandic-hotels/trpc/types/destinationsData"
import type {
  HotelListingHotelData,
  HotelSortItem,
} from "@scandic-hotels/trpc/types/hotel"

import type { DestinationDataStore } from "@/types/contexts/destination-data"

interface DestinationDataProviderProps extends React.PropsWithChildren {
  allHotels: HotelListingHotelData[]
  allCities?: DestinationCityListItem[]
  hotelFilters: HotelFilters
  seoFilters: DestinationFilters
  filterFromUrl?: string
  sortItems: HotelSortItem[]
  pathname: string
}

export default function DestinationDataProvider({
  allCities = [],
  allHotels,
  hotelFilters,
  seoFilters,
  sortItems,
  pathname,
  children,
}: DestinationDataProviderProps) {
  const storeRef = useRef<DestinationDataStore>(undefined)
  const searchParams = useSearchParams()

  // eslint-disable-next-line react-hooks/refs
  if (!storeRef.current) {
    storeRef.current = createDestinationDataStore({
      allCities,
      allHotels,
      hotelFilters,
      seoFilters,
      pathname,
      sortItems,
      searchParams,
    })
  }

  return (
    // eslint-disable-next-line react-hooks/refs
    <DestinationDataContext.Provider value={storeRef.current}>
      <DestinationDataProviderContent>
        {children}
      </DestinationDataProviderContent>
    </DestinationDataContext.Provider>
  )
}
