

// buzzwareTech imports
import { API_BASE_URL } from "@buzzwaretech/constants";
import type { TOAuthConfigs, TOAuthOption } from "@buzzwaretech/types";
import { useTheme } from "next-themes";
import { useSearchParams } from "next/navigation";
// assets
import giteaLogo from "@/app/assets/logos/gitea-logo.svg?url";
import GithubLightLogo from "@/app/assets/logos/github-black.png?url";
import GithubDarkLogo from "@/app/assets/logos/github-dark.svg?url";
import gitlabLogo from "@/app/assets/logos/gitlab-logo.svg?url";
import googleLogo from "@/app/assets/logos/google-logo.svg?url";
// hooks
import { useInstance } from "@/hooks/store/use-instance";

export const useCoreOAuthConfig = (oauthActionText: string): TOAuthConfigs => {
  //router
  const searchParams = useSearchParams();
  // query params
  const next_path = searchParams.get("next_path");
  // theme
  const { resolvedTheme } = useTheme();
  // store hooks
  const { config } = useInstance();
  // derived values
  const isOAuthEnabled =
    (config &&
      (config?.is_google_enabled ||
        config?.is_github_enabled ||
        config?.is_gitlab_enabled ||
        config?.is_gitea_enabled)) ||
    false;
  const oAuthOptions: TOAuthOption[] = [
    {
      id: "google",
      text: `${oauthActionText} with Google`,
      icon: <img src={googleLogo} height={18} width={18} alt="Google Logo" />,
      onClick: async () => {
        try {
          const { GoogleAuthProvider, signInWithPopup } = await import("firebase/auth");
          const { firebaseAuth } = await import("@/lib/firebase");
          const provider = new GoogleAuthProvider();
          const userCredential = await signInWithPopup(firebaseAuth, provider);
          
          // Write user details to Firestore immediately if new
          const { doc, setDoc } = await import("firebase/firestore");
          const { db } = await import("@/lib/firestore");
          
          // Upsert user profile — only set onboarding defaults if creating for the first time
          const { getDoc: getUserDoc } = await import("firebase/firestore");
          const userRef = doc(db, "users", userCredential.user.uid);
          const existingUser = await getUserDoc(userRef);
          const profileDefaults: Record<string, unknown> = {
            email: userCredential.user.email?.toLowerCase(),
            display_name: userCredential.user.displayName || userCredential.user.email?.split("@")[0],
            first_name: userCredential.user.displayName?.split(" ")[0] || userCredential.user.email?.split("@")[0],
            last_name: userCredential.user.displayName?.split(" ").slice(1).join(" ") || "",
            updated_at: new Date().toISOString(),
          };
          if (!existingUser.exists()) {
            profileDefaults.is_onboarded = false;
            profileDefaults.is_tour_completed = false;
            profileDefaults.theme = { theme: "system" };
            profileDefaults.created_at = new Date().toISOString();
          }
          await setDoc(userRef, profileDefaults, { merge: true });

          // Force redirect/reload after successful pop-up sign-in
          window.location.href = next_path || "/";
        } catch (error) {
          console.error("Google sign in failed:", error);
          alert("Failed to authenticate with Google. Please try again.");
        }
      },
      enabled: config?.is_google_enabled,
    },
    {
      id: "github",
      text: `${oauthActionText} with GitHub`,
      icon: (
        <img
          src={resolvedTheme === "dark" ? GithubDarkLogo : GithubLightLogo}
          height={18}
          width={18}
          alt="GitHub Logo"
        />
      ),
      onClick: () => {
        window.location.assign(
          `${API_BASE_URL}/auth/github/${next_path ? `?next_path=${next_path}` : ``}`,
        );
      },
      enabled: config?.is_github_enabled,
    },
    {
      id: "gitlab",
      text: `${oauthActionText} with GitLab`,
      icon: <img src={gitlabLogo} height={18} width={18} alt="GitLab Logo" />,
      onClick: () => {
        window.location.assign(
          `${API_BASE_URL}/auth/gitlab/${next_path ? `?next_path=${next_path}` : ``}`,
        );
      },
      enabled: config?.is_gitlab_enabled,
    },
    {
      id: "gitea",
      text: `${oauthActionText} with Gitea`,
      icon: <img src={giteaLogo} height={18} width={18} alt="Gitea Logo" />,
      onClick: () => {
        window.location.assign(
          `${API_BASE_URL}/auth/gitea/${next_path ? `?next_path=${next_path}` : ``}`,
        );
      },
      enabled: config?.is_gitea_enabled,
    },
  ];

  return {
    isOAuthEnabled,
    oAuthOptions,
  };
};
