"use client"

import React, { createContext, useContext } from "react"

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

/* eslint-disable formatjs/no-literal-string-in-jsx */

type SocialLoginContextType = {
  session: ReturnType<typeof useSocialSession>["session"]
  refresh: ReturnType<typeof useSocialSession>["refresh"]
}

const SocialLoginContext = createContext<SocialLoginContextType | undefined>(
  undefined
)

export function SocialLoginProvider({
  children,
}: {
  children: React.ReactNode
}) {
  const { session: socialSession, refresh } = useSocialSession()

  return (
    <SocialLoginContext.Provider value={{ session: socialSession, refresh }}>
      {process.env.NODE_ENV === "development" && (
        <>
          <span>Social login: </span>
          {socialSession.data?.status}{" "}
          {socialSession?.data?.status === "expired" && (
            <>
              <span>Expires@{socialSession?.data.expiresAt}</span>{" "}
              <button onClick={() => refresh.mutate()}>Refresh</button>
            </>
          )}
          {socialSession?.data?.status === "valid" && (
            <>
              <span>Expires@{socialSession?.data.expiresAt}</span>{" "}
              <button onClick={() => refresh.mutate()}>Refresh</button>
            </>
          )}
        </>
      )}

      {children}
    </SocialLoginContext.Provider>
  )
}

export function useSocialLogin() {
  const ctx = useContext(SocialLoginContext)
  if (!ctx) {
    throw new Error(
      "useSocialLogin must be used within SocialLoginContextProvider"
    )
  }
  return ctx
}
