"use client";

import { useEffect, useRef, useState } from "react";
import { useGoogleLogin } from "@/hooks/useGoogleLogin";
import { ApiError } from "@/hooks/api-error";
import type { LoginUser } from "@/services/login-user";
import { SpinnerIcon } from "@/components/auth-form-ui";

/* Google Identity Services sign-in button.
   GIS renders its own (unstylable) button into a container we hand it, so this
   component owns the script tag, the one-time initialize() call and the sizing,
   then forwards the resulting credential to /api/auth/google.

   Renders nothing at all when NEXT_PUBLIC_GOOGLE_CLIENT_ID is unset, so a
   deployment without Google configured simply doesn't show the option. */

const GSI_SRC = "https://accounts.google.com/gsi/client";

type CredentialResponse = { credential?: string };

type GoogleIdApi = {
  initialize: (config: {
    client_id: string;
    callback: (response: CredentialResponse) => void;
    ux_mode?: "popup" | "redirect";
    auto_select?: boolean;
    cancel_on_tap_outside?: boolean;
  }) => void;
  renderButton: (
    parent: HTMLElement,
    options: {
      type?: "standard" | "icon";
      theme?: "outline" | "filled_blue" | "filled_black";
      size?: "large" | "medium" | "small";
      text?: "signin_with" | "signup_with" | "continue_with";
      shape?: "rectangular" | "pill";
      logo_alignment?: "left" | "center";
      width?: number;
    },
  ) => void;
};

declare global {
  interface Window {
    google?: { accounts?: { id?: GoogleIdApi } };
  }
}

// Load the GIS script once per page, reusing the promise across mounts.
let gsiPromise: Promise<void> | null = null;

function loadGsi(): Promise<void> {
  if (typeof window === "undefined") return Promise.resolve();
  if (window.google?.accounts?.id) return Promise.resolve();
  if (gsiPromise) return gsiPromise;

  gsiPromise = new Promise<void>((resolve, reject) => {
    const existing = document.querySelector<HTMLScriptElement>(
      `script[src="${GSI_SRC}"]`,
    );
    const script = existing ?? document.createElement("script");
    script.addEventListener("load", () => resolve());
    script.addEventListener("error", () =>
      reject(new Error("Failed to load Google sign-in")),
    );
    if (!existing) {
      script.src = GSI_SRC;
      script.async = true;
      script.defer = true;
      document.head.appendChild(script);
    }
  }).catch((error: unknown) => {
    // Let a later mount retry rather than caching the failure forever.
    gsiPromise = null;
    throw error;
  });

  return gsiPromise;
}

export function GoogleSignInButton({
  text = "signin_with",
  onSuccess,
  onError,
}: {
  text?: "signin_with" | "signup_with" | "continue_with";
  onSuccess: (user: LoginUser | undefined) => void;
  onError: (message: string) => void;
}) {
  const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;
  const containerRef = useRef<HTMLDivElement>(null);
  const [scriptError, setScriptError] = useState(false);
  const { mutate, isPending } = useGoogleLogin();

  // Callbacks change identity every render; keep the latest in a ref so the
  // effect below can stay keyed on the client id alone and initialize once.
  const handlers = useRef({ onSuccess, onError, mutate });
  useEffect(() => {
    handlers.current = { onSuccess, onError, mutate };
  });

  useEffect(() => {
    if (!clientId) return;
    let cancelled = false;

    loadGsi()
      .then(() => {
        const id = window.google?.accounts?.id;
        if (cancelled || !id || !containerRef.current) return;

        id.initialize({
          client_id: clientId,
          ux_mode: "popup",
          cancel_on_tap_outside: true,
          callback: ({ credential }) => {
            if (!credential) {
              handlers.current.onError(
                "Google didn't return a sign-in token. Please try again.",
              );
              return;
            }
            handlers.current.mutate(
              { idToken: credential },
              {
                onSuccess: (data) =>
                  handlers.current.onSuccess(data?.data?.user),
                onError: (err) =>
                  handlers.current.onError(googleErrorMessage(err)),
              },
            );
          },
        });

        // GIS appends its button rather than replacing, so clear first — React
        // never renders children here, and Strict Mode runs this effect twice
        // in development, which would otherwise leave two buttons stacked.
        containerRef.current.replaceChildren();

        id.renderButton(containerRef.current, {
          type: "standard",
          theme: "filled_black",
          size: "large",
          shape: "pill",
          logo_alignment: "center",
          text,
          // GIS needs a pixel width; match the card it sits in. clientWidth can
          // still be 0 if we run before layout — fall back to a sane default
          // rather than asking Google for a zero-width button. Max is 400.
          width: Math.min(400, Math.round(containerRef.current.clientWidth) || 320),
        });
      })
      .catch(() => {
        if (!cancelled) setScriptError(true);
      });

    return () => {
      cancelled = true;
    };
  }, [clientId, text]);

  // Google sign-in isn't configured for this deployment — show nothing. A dead
  // Google button is worse than no button, but say so in development so a
  // missing env var doesn't just look like a broken feature.
  if (!clientId) {
    if (process.env.NODE_ENV === "development") {
      console.warn(
        "[VehCall] Google sign-in hidden: NEXT_PUBLIC_GOOGLE_CLIENT_ID is not set. " +
          "Add it to .env.local (and GOOGLE_CLIENT_ID on the API), then restart " +
          "`npm run dev` — Next only reads env files at startup.",
      );
    }
    return null;
  }

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center gap-3">
        <span className="h-px flex-1 bg-white/10" />
        <span className="text-xs uppercase tracking-wider text-white/35">
          or
        </span>
        <span className="h-px flex-1 bg-white/10" />
      </div>

      <div className="relative min-h-[44px]">
        {/* GIS paints its button in here */}
        <div ref={containerRef} className="flex justify-center" />

        {isPending && (
          <div className="absolute inset-0 flex items-center justify-center gap-2 rounded-full bg-surface/80 text-sm text-white/70">
            <SpinnerIcon /> Signing you in…
          </div>
        )}
      </div>

      {scriptError && (
        <p className="text-center text-xs text-white/45">
          Google sign-in couldn&apos;t load. Use your email and password
          instead.
        </p>
      )}
    </div>
  );
}

// The backend distinguishes these cases; say something useful for each.
function googleErrorMessage(error: unknown): string {
  if (error instanceof ApiError) {
    if (error.code === 403) {
      return "This Google account can't sign in here. Contact support if that's unexpected.";
    }
    if (error.code === 501) {
      return "Google sign-in isn't available right now. Please use your email and password.";
    }
    if (error.code === 401) {
      return "Google couldn't verify that sign-in. Please try again.";
    }
    return error.message;
  }
  return "Couldn't reach the server. Check your connection and try again.";
}
