"use client"

import { BookingFlowContextProvider } from "@scandic-hotels/booking-flow/BookingFlowContextProvider"
import { trpc } from "@scandic-hotels/trpc/client"

import { useIsUserLoggedIn } from "@/hooks/useIsUserLoggedIn"

import type { ComponentProps, ReactNode } from "react"

export function BookingFlowProviders({ children }: { children: ReactNode }) {
  const isLoggedIn = useIsUserLoggedIn()
  const user = useBookingFlowUser()

  return (
    <BookingFlowContextProvider data={{ isLoggedIn, user }}>
      {children}
    </BookingFlowContextProvider>
  )
}

type BookingFlowContextData = ComponentProps<
  typeof BookingFlowContextProvider
>["data"]
type BookingFlowUser = BookingFlowContextData["user"]

function useBookingFlowUser(): BookingFlowUser {
  const isLoggedIn = useIsUserLoggedIn()
  const { data, isError, isLoading } = trpc.user.getSafely.useQuery(undefined, {
    enabled: isLoggedIn,
  })

  if (isLoading) {
    return { state: "loading", data: undefined }
  }
  if (isError || !data) {
    return { state: "error", data: undefined }
  }

  return {
    state: "loaded",
    data: {
      type: "scandic",
      partnerLoyaltyNumber: null,
      membershipNumber: data.membershipNumber,
      firstName: data.firstName || null,
      lastName: data.lastName || null,
      email: data.email,
    },
  }
}
