'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { LoginForm, MfaChallenge, type SocialProvider } from '@bytelyst/auth-ui';
import { useAuth } from '@/lib/auth-context';

const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || '';
// Only advertise social providers the backend actually supports. Today that is
// Google, and only when a client id is configured (gates /api/auth/oauth/google).
const SOCIAL_PROVIDERS: SocialProvider[] = GOOGLE_CLIENT_ID ? ['google'] : [];

export default function LoginPage() {
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { login } = useAuth();
  const router = useRouter();

  // MFA state
  const [mfaChallenge, setMfaChallenge] = useState<string | null>(null);
  const [mfaMethods, setMfaMethods] = useState<string[]>([]);
  const [useRecovery, setUseRecovery] = useState(false);

  // The shared LoginForm renders placeholder-only inputs; give them accessible
  // names so screen readers (and the a11y gate) have a label to announce.
  const formRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const root = formRef.current;
    if (!root) return;
    root.querySelector('[data-testid="bl-login-email"]')?.setAttribute('aria-label', 'Email');
    root.querySelector('[data-testid="bl-login-password"]')?.setAttribute('aria-label', 'Password');
  });

  const completeAuth = useCallback((data: { accessToken: string }) => {
    localStorage.setItem('tracker_token', data.accessToken);
    // Force full reload so auth-context re-reads token from localStorage.
    window.location.href = '/dashboard';
  }, []);

  const handleLoginResponse = useCallback(
    (data: Record<string, unknown>) => {
      if (data.mfaRequired) {
        setMfaChallenge(data.mfaChallenge as string);
        setMfaMethods((data.methods as string[]) || []);
        setError('');
        return;
      }
      completeAuth(data as { accessToken: string });
    },
    [completeAuth]
  );

  const handlePasswordLogin = async (email: string, password: string) => {
    setError('');
    setLoading(true);
    try {
      await login(email, password);
      router.push('/dashboard');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleSignIn = useCallback(async () => {
    setError('');
    setLoading(true);
    try {
      const google = (window as unknown as Record<string, unknown>).google as
        | {
            accounts: {
              id: {
                initialize: (config: Record<string, unknown>) => void;
                prompt: () => void;
              };
            };
          }
        | undefined;

      if (google) {
        google.accounts.id.initialize({
          client_id: GOOGLE_CLIENT_ID,
          callback: async (response: { credential: string }) => {
            const res = await fetch('/api/auth/oauth/google', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ idToken: response.credential }),
            });
            const data = await res.json();
            setLoading(false);
            if (!res.ok) {
              setError(data.error || 'Google sign-in failed');
              return;
            }
            handleLoginResponse(data);
          },
        });
        google.accounts.id.prompt();
      } else {
        // Fallback: popup
        const w = 500,
          h = 600;
        const left = window.screenX + (window.outerWidth - w) / 2;
        const top = window.screenY + (window.outerHeight - h) / 2;
        const popup = window.open(
          `https://accounts.google.com/o/oauth2/v2/auth?` +
            `client_id=${GOOGLE_CLIENT_ID}&` +
            `redirect_uri=${encodeURIComponent(window.location.origin + '/api/auth/callback/google')}&` +
            `response_type=id_token&scope=openid email profile&nonce=${crypto.randomUUID()}`,
          'google-signin',
          `width=${w},height=${h},left=${left},top=${top}`
        );
        const handler = (event: MessageEvent) => {
          if (event.origin === window.location.origin && event.data?.idToken) {
            window.removeEventListener('message', handler);
            popup?.close();
            fetch('/api/auth/oauth/google', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ idToken: event.data.idToken }),
            })
              .then(r => r.json())
              .then(data => {
                setLoading(false);
                if (data.error) {
                  setError(data.error);
                  return;
                }
                handleLoginResponse(data);
              });
          }
        };
        window.addEventListener('message', handler);
      }
    } catch {
      setError('Google sign-in failed');
      setLoading(false);
    }
  }, [handleLoginResponse]);

  const handleSocialLogin = (provider: SocialProvider) => {
    if (provider === 'google') void handleGoogleSignIn();
  };

  const handleMfaVerify = async (code: string) => {
    setError('');
    setLoading(true);
    try {
      const res = await fetch('/api/auth/mfa/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          challengeToken: mfaChallenge,
          code,
          method: useRecovery ? 'recovery' : 'totp',
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Verification failed');
        return;
      }
      completeAuth(data);
    } catch {
      setError('Service unavailable');
    } finally {
      setLoading(false);
    }
  };

  // MFA challenge view
  if (mfaChallenge) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background p-4">
        <div className="w-full max-w-sm space-y-6 rounded-xl border border-border bg-card p-8 shadow-lg">
          <div className="text-center">
            <h1 className="text-2xl font-bold tracking-tight">Two-Factor Auth</h1>
            <p className="mt-1 text-sm text-muted-foreground">
              {useRecovery ? 'Enter a recovery code' : 'Enter your authentication code'}
            </p>
          </div>
          <MfaChallenge
            methods={mfaMethods}
            isLoading={loading}
            error={error || null}
            onSubmit={handleMfaVerify}
            onUseRecovery={() => {
              setUseRecovery(true);
              setError('');
            }}
          />
          <button
            type="button"
            onClick={() => {
              setMfaChallenge(null);
              setMfaMethods([]);
              setUseRecovery(false);
              setError('');
            }}
            className="w-full text-center text-xs text-muted-foreground underline"
          >
            Back to login
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <div className="w-full max-w-sm space-y-6 rounded-xl border border-border bg-card p-8 shadow-lg">
        <div className="text-center">
          <h1 className="text-2xl font-bold tracking-tight">Tracker</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Feature requests, bugs &amp; task management
          </p>
        </div>

        <div ref={formRef}>
          <LoginForm
            onSubmit={handlePasswordLogin}
            isLoading={loading}
            error={error || null}
            providers={SOCIAL_PROVIDERS}
            onSocialLogin={handleSocialLogin}
          />
        </div>

        <p className="text-center text-xs text-muted-foreground">
          Uses platform-service credentials
        </p>
      </div>
    </div>
  );
}
