"use client";

import GoogleSignInButtonBase, {
  GoogleAuthRootProvider,
} from "@/components/auth/GoogleSignInButton";
import InstagramSignInButtonBase from "@/components/auth/InstagramSignInButton";
import RegisterRouteGuard from "@/components/auth/RegisterRouteGuard";
import { GOOGLE_OAUTH_CLIENT_ID } from "@/config/googleAuth";
import { INSTAGRAM_OAUTH_CLIENT_ID } from "@/config/instagramAuth";
import { createContext, useContext, useEffect, useState } from "react";

const GoogleClientIdContext = createContext("");
const InstagramClientIdContext = createContext("");

export function useGoogleClientId(): string {
  return useContext(GoogleClientIdContext);
}

export function useInstagramClientId(): string {
  return useContext(InstagramClientIdContext);
}

export function GoogleSignInButton(
  props: Omit<React.ComponentProps<typeof GoogleSignInButtonBase>, "clientId">
) {
  const clientId = useGoogleClientId();
  return (
    <GoogleSignInButtonBase
      {...props}
      clientId={clientId || GOOGLE_OAUTH_CLIENT_ID}
    />
  );
}

export function InstagramSignInButton(
  props: Omit<React.ComponentProps<typeof InstagramSignInButtonBase>, "clientId">
) {
  const clientId = useInstagramClientId();
  return (
    <InstagramSignInButtonBase
      {...props}
      clientId={clientId || INSTAGRAM_OAUTH_CLIENT_ID}
    />
  );
}

export default function AuthProviders({
  children,
  googleClientId = "",
  instagramClientId = "",
}: {
  children: React.ReactNode;
  googleClientId?: string;
  instagramClientId?: string;
}) {
  const [resolvedClientId, setResolvedClientId] = useState(
    googleClientId || GOOGLE_OAUTH_CLIENT_ID
  );
  const [resolvedInstagramClientId, setResolvedInstagramClientId] = useState(
    instagramClientId || INSTAGRAM_OAUTH_CLIENT_ID
  );

  useEffect(() => {
    let cancelled = false;

    async function loadClientId() {
      const fallback = googleClientId || GOOGLE_OAUTH_CLIENT_ID;
      const instagramFallback = instagramClientId || INSTAGRAM_OAUTH_CLIENT_ID;
      setResolvedClientId(fallback);
      setResolvedInstagramClientId(instagramFallback);

      try {
        const res = await fetch("/api/auth/config", { cache: "no-store" });
        if (!res.ok) return;
        const data = (await res.json()) as {
          googleClientId?: string;
          instagramClientId?: string;
        };
        if (!cancelled) {
          setResolvedClientId(data?.googleClientId || fallback);
          setResolvedInstagramClientId(data?.instagramClientId || instagramFallback);
        }
      } catch {
        // keep fallback
      }
    }

    void loadClientId();

    return () => {
      cancelled = true;
    };
  }, [googleClientId, instagramClientId]);

  return (
    <GoogleClientIdContext.Provider value={resolvedClientId}>
      <InstagramClientIdContext.Provider value={resolvedInstagramClientId}>
        <GoogleAuthRootProvider clientId={resolvedClientId}>
          <RegisterRouteGuard>{children}</RegisterRouteGuard>
        </GoogleAuthRootProvider>
      </InstagramClientIdContext.Provider>
    </GoogleClientIdContext.Provider>
  );
}
