'use client';

import { useEffect, useRef, useState } from 'react';
import {
  getGoogleClientId,
  isGoogleSignInConfigured,
  loadGoogleIdentityServices,
} from '@/lib/googleAuth';

type GoogleSignInButtonProps = {
  mode?: 'signin' | 'signup' | 'continue';
  onCredential: (idToken: string) => void | Promise<void>;
  onError?: (message: string) => void;
  disabled?: boolean;
  showDivider?: boolean;
  dividerLabel?: string;
};

export function GoogleSignInButton({
  mode = 'signin',
  onCredential,
  onError,
  disabled = false,
  showDivider = true,
  dividerLabel = 'or',
}: GoogleSignInButtonProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const callbackRef = useRef(onCredential);
  const errorRef = useRef(onError);
  const [ready, setReady] = useState(false);
  const [failed, setFailed] = useState(false);

  callbackRef.current = onCredential;
  errorRef.current = onError;

  useEffect(() => {
    if (!isGoogleSignInConfigured() || disabled) return;

    let cancelled = false;

    const render = async () => {
      try {
        await loadGoogleIdentityServices();
        if (cancelled || !containerRef.current || !window.google?.accounts?.id) return;

        const clientId = getGoogleClientId();
        const width = Math.min(
          400,
          Math.max(240, Math.floor(containerRef.current.clientWidth || 320))
        );

        containerRef.current.innerHTML = '';
        window.google.accounts.id.initialize({
          client_id: clientId,
          callback: async (response) => {
            if (!response.credential) {
              errorRef.current?.('Google Sign-In did not return a credential');
              return;
            }
            try {
              await callbackRef.current(response.credential);
            } catch (err) {
              errorRef.current?.(
                err instanceof Error ? err.message : 'Google Sign-In failed'
              );
            }
          },
          auto_select: false,
          cancel_on_tap_outside: true,
        });

        const buttonText =
          mode === 'signup' ? 'signup_with' : mode === 'continue' ? 'continue_with' : 'signin_with';

        window.google.accounts.id.renderButton(containerRef.current, {
          theme: 'outline',
          size: 'large',
          text: buttonText,
          shape: 'rectangular',
          logo_alignment: 'left',
          width,
          locale: 'en',
        });

        if (!cancelled) setReady(true);
      } catch {
        if (!cancelled) {
          setFailed(true);
          errorRef.current?.('Google Sign-In could not be loaded');
        }
      }
    };

    void render();

    return () => {
      cancelled = true;
    };
  }, [mode, disabled]);

  if (!isGoogleSignInConfigured() || failed) {
    return null;
  }

  return (
    <div className="w-full space-y-4">
      <div
        ref={containerRef}
        className={`flex w-full justify-center min-h-11 ${disabled ? 'pointer-events-none opacity-50' : ''}`}
        aria-busy={!ready}
      />
      {showDivider && (
        <div className="relative">
          <div className="absolute inset-0 flex items-center" aria-hidden>
            <div className="w-full border-t border-border" />
          </div>
          <div className="relative flex justify-center text-xs uppercase tracking-wide">
            <span className="bg-white px-3 text-muted">{dividerLabel}</span>
          </div>
        </div>
      )}
    </div>
  );
}
