"use client";

import { useState } from "react";
import { useGoogleLogin } from "@react-oauth/google";
import { loginWithGoogleProfile } from "@/lib/auth";

interface GoogleSignInButtonProps {
  onSuccess: () => void;
  onError?: (error: string) => void;
  className?: string;
}

function isValidGoogleClientId(value: string | undefined): boolean {
  if (!value) return false;
  if (value === "your_google_oauth_client_id_here") return false;
  return value.includes(".apps.googleusercontent.com");
}

function GoogleSignInButtonInner({
  onSuccess,
  onError,
  className = "",
}: GoogleSignInButtonProps) {
  const [isLoading, setIsLoading] = useState(false);

  const startGoogleLogin = useGoogleLogin({
    scope: "openid email profile",
    onSuccess: async (tokenResponse) => {
      try {
        setIsLoading(true);
        const userInfoRes = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
          headers: {
            Authorization: `Bearer ${tokenResponse.access_token}`,
          },
        });

        if (!userInfoRes.ok) {
          onError?.("গুগোল ইউজার তথ্য আনতে সমস্যা হয়েছে।");
          return;
        }

        const profile = (await userInfoRes.json()) as {
          sub?: string;
          name?: string;
          email?: string;
        };

        if (!profile.sub || !profile.name || !profile.email) {
          onError?.("গুগোল থেকে তথ্য পাওয়া যায়নি।");
          return;
        }

        const result = loginWithGoogleProfile({
          googleId: profile.sub,
          fullName: profile.name,
          email: profile.email,
        });

        if (!result.ok) {
          onError?.(result.error || "সাইনিন ব্যর্থ হয়েছে।");
          return;
        }

        onSuccess();
      } catch {
        onError?.("সাইনিন প্রক্রিয়ায় ত্রুটি হয়েছে।");
      } finally {
        setIsLoading(false);
      }
    },
    onError: () => {
      onError?.("গুগোল সাইনিন ব্যর্থ হয়েছে।");
    },
  });

  const handleClick = () => {
    try {
      startGoogleLogin();
    } catch {
      onError?.("গুগোল সাইনিন শুরু করা যায়নি।");
    }
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={isLoading}
      className={`flex h-[42px] w-full items-center justify-center gap-2 rounded-xl border border-white/20 bg-white/[0.06] px-3 text-sm font-semibold text-white transition hover:bg-white/[0.12] disabled:cursor-not-allowed disabled:opacity-70 ${className}`}
    >
      <span className="flex h-5 w-5 items-center justify-center rounded-full bg-white text-xs font-black">
        <span className="bg-gradient-to-r from-[#4285F4] via-[#34A853] to-[#EA4335] bg-clip-text text-transparent">G</span>
      </span>
      Google
    </button>
  );
}

export function GoogleSignInButton({
  onSuccess,
  onError,
  className = "",
}: GoogleSignInButtonProps) {
  const rawClientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;
  const clientId = isValidGoogleClientId(rawClientId) ? rawClientId : undefined;

  if (!clientId) {
    return (
      <div className={`rounded-xl border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-xs text-yellow-600 ${className}`}>
        ⚠️ Google Client ID সঠিক নয়। পুরো Client ID দিন (শেষে .apps.googleusercontent.com থাকতে হবে)।
      </div>
    );
  }

  return (
    <GoogleSignInButtonInner
      onSuccess={onSuccess}
      onError={onError}
      className={className}
    />
  );
}
