// Google Auth Utility
// This utility handles Google OAuth authentication flow

interface GoogleUser {
  id: string;
  email: string;
  name: string;
  image?: string;
  email_verified?: boolean;
}

/**
 * Initialize Google Sign-In
 * Should be called once when the component mounts
 */
export const initializeGoogleSignIn = () => {
  if (typeof window === "undefined") return;

  const googleClientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;

  if (!googleClientId) {
    console.warn(
      "Google Client ID not found in environment variables. Google Sign-In will not work."
    );
    return false;
  }

  // If the SDK is already loaded, just re-initialize
  if ((window as any).google) {
    (window as any).google.accounts.id.initialize({
      client_id: googleClientId,
      callback: handleGoogleCallback,
    });
    return true;
  }

  // Avoid adding the script tag more than once
  if (document.querySelector('script[src="https://accounts.google.com/gsi/client"]')) {
    return true;
  }

  // Load the Google Identity Services library
  const script = document.createElement("script");
  script.src = "https://accounts.google.com/gsi/client";
  script.async = true;
  script.defer = true;

  script.onload = () => {
    if ((window as any).google) {
      (window as any).google.accounts.id.initialize({
        client_id: googleClientId,
        callback: handleGoogleCallback,
      });
    }
  };

  document.head.appendChild(script);
  return true;
};

/**
 * Render the Google Sign-In button
 * Retries until the Google SDK is loaded and the container element exists.
 * @param containerId - The ID of the container element where the button will be rendered
 * @param theme - The theme of the button (outline or filled)
 * @param size - The size of the button (large or standard)
 */
export const renderGoogleSignInButton = (
  containerId: string,
  theme: "outline" | "filled_blue" | "filled_black" = "outline",
  size: "large" | "standard" = "large"
) => {
  if (typeof window === "undefined") return;

  const maxAttempts = 20;
  let attempts = 0;

  const tryRender = () => {
    attempts++;
    const container = document.getElementById(containerId);

    if ((window as any).google && container) {
      (window as any).google.accounts.id.renderButton(container, {
        theme,
        size,
        type: "standard",
        text: "signin_with",
      });
    } else if (attempts < maxAttempts) {
      setTimeout(tryRender, 300);
    } else {
      console.warn(
        "Google Sign-In button could not be rendered: SDK not loaded or container not found."
      );
    }
  };

  tryRender();
};

/**
 * Handle the callback from Google Sign-In
 * This function is called automatically after user authenticates with Google
 */
const handleGoogleCallback = (response: any) => {
  if (response.credential) {
    // Dispatch event that components can listen to
    const event = new CustomEvent("googleSignInSuccess", {
      detail: { token: response.credential },
    });
    window.dispatchEvent(event);
  }
};

/**
 * Decode the JWT token from Google and extract user information
 * Note: This should ideally be done on the backend for security
 * @param token - The JWT token from Google
 * @returns Decoded user information
 */
export const decodeGoogleToken = (token: string): GoogleUser | null => {
  try {
    // Split the JWT into parts
    const parts = token.split(".");
    if (parts.length !== 3) return null;

    // Decode the payload (second part)
    const payload = JSON.parse(atob(parts[1]));

    return {
      id: payload.sub,
      email: payload.email,
      name: payload.name,
      image: payload.picture,
      email_verified: payload.email_verified,
    };
  } catch (error) {
    console.error("Failed to decode Google token:", error);
    return null;
  }
};

/**
 * Sign out from Google
 */
export const signOutGoogle = () => {
  if (typeof window === "undefined") return;

  if ((window as any).google) {
    (window as any).google.accounts.id.disableAutoSelect();
  }
};
