"use client"

import { useSession } from "next-auth/react"

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

import type { ComponentProps, ReactNode } from "react"

export function BookingFlowProviders({ children }: { children: ReactNode }) {
  const user = useBookingFlowUser()
  const isLinkedUser =
    !!user.data && user.data.type === "partner" && user.data.isLinked

  return (
    <BookingFlowContextProvider
      data={{
        isLoggedIn: user.state === "loaded" && isLinkedUser,
        user,
      }}
    >
      {children}
    </BookingFlowContextProvider>
  )
}

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

function useBookingFlowUser(): BookingFlowUser {
  const { data: session } = useSession()
  const hasValidSession = isValidSession(session)

  const {
    data: euroBonusProfile,
    isError,
    isLoading,
  } = trpc.partner.sas.getEuroBonusProfile.useQuery(undefined, {
    enabled: hasValidSession,
  })

  if (isLoading) {
    return { state: "loading", data: undefined }
  }

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

  return {
    state: "loaded",
    data: {
      type: "partner",
      partnerLoyaltyNumber: `EB${euroBonusProfile.eurobonusNumber}`,
      firstName: euroBonusProfile.firstName || null,
      lastName: euroBonusProfile.lastName || null,
      email: euroBonusProfile.email,
      isLinked: euroBonusProfile.linkStatus === "LINKED",
    },
  }
}
