"use client";

import { useEffect, useRef, useState } from "react";
import Script from "next/script";
import { Loader2 } from "lucide-react";
import { authApi } from "@/lib/api";
import { tokenStore } from "@/lib/auth-store";
import { Button } from "@/components/ui/button";

declare global {
  interface Window {
    google?: {
      accounts: {
        id: {
          initialize: (options: {
            client_id: string;
            callback: (response: { credential?: string }) => void;
          }) => void;
          renderButton: (
            parent: HTMLElement,
            options: {
              theme: "outline" | "filled_blue" | "filled_black";
              size: "large" | "medium" | "small";
              width?: number;
              text?: "signin_with" | "signup_with" | "continue_with";
              shape?: "rectangular" | "pill" | "circle" | "square";
            }
          ) => void;
        };
      };
    };
  }
}

interface GoogleLoginButtonProps {
  text?: "signin_with" | "signup_with" | "continue_with";
  onSuccess: () => void;
  onError: (message: string) => void;
}

const googleClientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? "";

export function GoogleLoginButton({
  text = "continue_with",
  onSuccess,
  onError,
}: GoogleLoginButtonProps) {
  const buttonRef = useRef<HTMLDivElement | null>(null);
  const [loading, setLoading] = useState(false);
  const [scriptReady, setScriptReady] = useState(false);

  useEffect(() => {
    if (!scriptReady || !buttonRef.current || !window.google || !googleClientId) return;

    buttonRef.current.innerHTML = "";
    window.google.accounts.id.initialize({
      client_id: googleClientId,
      callback: async ({ credential }) => {
        if (!credential) {
          onError("Google did not return a sign-in credential");
          return;
        }
        setLoading(true);
        try {
          const tokens = await authApi.googleLogin(credential);
          tokenStore.set(tokens.access_token, tokens.refresh_token);
          onSuccess();
        } catch (err: unknown) {
          onError(err instanceof Error ? err.message : "Google login failed");
        } finally {
          setLoading(false);
        }
      },
    });
    window.google.accounts.id.renderButton(buttonRef.current, {
      theme: "outline",
      size: "large",
      width: 304,
      text,
      shape: "rectangular",
    });
  }, [onError, onSuccess, scriptReady, text]);

  if (!googleClientId) {
    return (
      <Button
        variant="outline"
        className="w-full border-white/10 bg-white/5 text-zinc-500 h-11"
        type="button"
        disabled
      >
        Google login not configured
      </Button>
    );
  }

  return (
    <>
      <Script
        src="https://accounts.google.com/gsi/client"
        strategy="afterInteractive"
        onLoad={() => setScriptReady(true)}
      />
      <div className="relative min-h-11">
        <div ref={buttonRef} className={loading ? "flex justify-center pointer-events-none opacity-60" : "flex justify-center"} />
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center rounded border border-white/10 bg-zinc-950/70">
            <Loader2 className="h-4 w-4 animate-spin text-white" />
          </div>
        )}
      </div>
    </>
  );
}
