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

import { createHotelDataStore } from "@/stores/hotel-data"
import { DEFAULT_SORT } from "@/stores/hotel-data/helper"

import { HotelDataContext } from "@/contexts/HotelData"

import type { HotelDataStore } from "@/types/contexts/hotel-data"
import type { HotelDataProviderProps } from "@/types/providers/hotel-data"
import type { SubmitCallbackData } from "@/types/stores/hotel-data"

export default function HotelDataProvider({
  allHotels,
  filterFromUrl,
  sortItems,
  children,
}: HotelDataProviderProps) {
  const storeRef = useRef<HotelDataStore>()
  const searchParams = useSearchParams()
  const pathname = usePathname()
  const router = useRouter()

  function submitCallbackFn({ sort, filters, basePath }: SubmitCallbackData) {
    const parsedUrl = new URL(window.location.href)
    const searchParams = parsedUrl.searchParams
    if (sort === DEFAULT_SORT && searchParams.has("sort")) {
      searchParams.delete("sort")
    } else if (sort !== DEFAULT_SORT) {
      searchParams.set("sort", sort)
    }

    const [firstFilter, ...remainingFilters] = filters

    parsedUrl.pathname = basePath
    if (firstFilter) {
      parsedUrl.pathname += `/${firstFilter}`
    }
    if (remainingFilters.length > 0) {
      parsedUrl.hash = `#${remainingFilters.join("&")}`
    } else {
      parsedUrl.hash = ""
    }

    router.push(parsedUrl.toString(), { scroll: false })
  }

  if (!storeRef.current) {
    storeRef.current = createHotelDataStore({
      allHotels,
      pathname,
      searchParams,
      filterFromUrl,
      sortItems,
      submitCallbackFn,
    })
  }

  return (
    <HotelDataContext.Provider value={storeRef.current}>
      {children}
    </HotelDataContext.Provider>
  )
}
