"use client"

import { useRef } from "react"

import { trpc } from "@/lib/trpc/client"

import useLang from "@/hooks/useLang"

import type { BookingStatusEnum } from "@/constants/booking"

export function useHandleBookingStatus({
  refId,
  expectedStatuses,
  maxRetries,
  retryInterval,
  enabled,
}: {
  refId: string | null
  expectedStatuses: BookingStatusEnum[]
  maxRetries: number
  retryInterval: number
  enabled: boolean
}) {
  const lang = useLang()
  const retries = useRef(0)

  const query = trpc.booking.status.useQuery(
    {
      lang,
      refId: refId ?? "",
    },
    {
      enabled,
      refetchInterval: (query) => {
        retries.current = query.state.dataUpdateCount

        if (query.state.error || query.state.dataUpdateCount >= maxRetries) {
          return false
        }

        if (
          expectedStatuses.includes(
            query.state.data?.booking.reservationStatus as BookingStatusEnum
          )
        ) {
          return false
        }

        return retryInterval
      },
      refetchIntervalInBackground: true,
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      retry: false,
    }
  )

  return {
    ...query,
    isTimeout: retries.current >= maxRetries,
  }
}
