"use client"

import { create } from "zustand"

import { parseSelectRateSearchParams, searchParamsToRecord } from "@/utils/url"

import { checkIsSameBooking } from "./enter-details/helpers"

import type { ReadonlyURLSearchParams } from "next/navigation"

interface TrackingStoreState {
  initialStartTime: number
  setInitialPageLoadTime: (time: number) => void
  getPageLoadTime: () => number
  currentParams: ReadonlyURLSearchParams | null
  previousParams: ReadonlyURLSearchParams | null
  currentPath: string | null
  previousPath: string | null
  currentLang: string | null
  previousLang: string | null
  updateRouteInfo: (
    path: string,
    lang: string,
    params: ReadonlyURLSearchParams
  ) => void
  hasPathOrLangChanged: () => boolean
  hasBookingFlowParamsChanged: () => boolean
}

const useTrackingStore = create<TrackingStoreState>((set, get) => ({
  initialStartTime: Date.now(),
  setInitialPageLoadTime: (time) => set({ initialStartTime: time }),
  getPageLoadTime: () => {
    const { initialStartTime } = get()
    return (Date.now() - initialStartTime) / 1000
  },
  currentParams: null,
  previousParams: null,
  currentPath: null,
  previousPath: null,
  currentLang: null,
  previousLang: null,
  updateRouteInfo: (path, lang, params) =>
    set((state) => {
      if (!path || !lang) return state

      if (!state.currentPath || !state.currentLang) {
        return {
          currentParams: params,
          currentPath: path,
          currentLang: lang,
          previousParams: null,
          previousPath: null,
          previousLang: null,
        }
      }

      return {
        previousParams: state.currentParams,
        previousPath: state.currentPath,
        previousLang: state.currentLang,
        currentParams: params,
        currentPath: path,
        currentLang: lang,
      }
    }),
  hasPathOrLangChanged: () => {
    const { currentPath, previousPath, currentLang, previousLang } = get()

    if (!previousPath || !previousLang) return false

    return currentPath !== previousPath || currentLang !== previousLang
  },
  hasBookingFlowParamsChanged: () => {
    const { currentPath, currentParams, previousParams } = get()

    if (!previousParams || !currentParams) return false

    if (!currentPath?.match(/^\/(da|de|en|fi|no|sv)\/(hotelreservation)/))
      return false

    const previousParamsObject = parseSelectRateSearchParams(
      searchParamsToRecord(previousParams)
    )
    const currentParamsObject = parseSelectRateSearchParams(
      searchParamsToRecord(currentParams)
    )

    if (!previousParamsObject && !currentParamsObject) return false
    if (!previousParamsObject || !currentParamsObject) return true

    const isSameBooking = checkIsSameBooking(
      previousParamsObject,
      currentParamsObject
    )
    return !isSameBooking
  },
}))

export default useTrackingStore
