"use client";

import { useState } from "react";
import { useGoogleLogin } from "@react-oauth/google";
import { GoogleIcon } from "./google-icon";

interface GoogleAuthButtonProps {
  label: string;
  onError: (message: string) => void;
}

/**
 * Shared by the Login and Register pages. Never navigates on cancel/error —
 * only a successful backend exchange redirects, so a closed Google popup
 * silently leaves the user right where they were (no account touched).
 */
export function GoogleAuthButton({ label, onError }: GoogleAuthButtonProps) {
  const [isLoading, setIsLoading] = useState(false);

  const login = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      setIsLoading(true);

      try {
        const res = await fetch("/api/auth/google", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ access_token: tokenResponse.access_token }),
        });

        const body = await res.json().catch(() => null);

        if (!res.ok) {
          onError(body?.message ?? "Google authentication failed. Please try again.");
          setIsLoading(false);
          return;
        }

        // Full navigation — see login/page.tsx for why (Server Components
        // reading the auth cookie must see the freshly-set session).
        window.location.href = body?.data?.profileComplete ? "/" : "/complete-profile";
      } catch {
        onError("Unable to reach the server. Please check your connection and try again.");
        setIsLoading(false);
      }
    },
    onError: () => {
      onError("Google authentication failed. Please try again.");
    },
  });

  return (
    <button
      type="button"
      onClick={() => login()}
      disabled={isLoading}
      className="flex w-full items-center justify-center gap-3 rounded-lg border border-neutral-300 bg-white px-4 py-2 text-sm font-medium text-neutral-700 transition-colors duration-150 hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-kolabora-primary disabled:cursor-not-allowed disabled:opacity-60"
    >
      <GoogleIcon className="h-5 w-5" />
      {isLoading ? "Processing..." : label}
    </button>
  );
}
