'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { LogIn, AlertCircle, Loader2, ShieldCheck } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAuth } from '@/lib/auth-context';

const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || '';

// ── MFA Challenge Sub-view ──────────────────────────────────

function MfaChallengeView({
  mfaChallenge,
  mfaMethods,
  onVerified,
  onBack,
}: {
  mfaChallenge: string;
  mfaMethods: string[];
  onVerified: (data: {
    accessToken: string;
    refreshToken: string;
    user: Record<string, unknown>;
  }) => void;
  onBack: () => void;
}) {
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [useRecovery, setUseRecovery] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    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;
      }
      onVerified(data);
    } catch {
      setError('Service unavailable');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="text-center">
        <ShieldCheck className="mx-auto h-8 w-8 text-primary mb-2" />
        <p className="text-sm text-muted-foreground">
          {useRecovery ? 'Enter a recovery code' : 'Enter your authentication code'}
        </p>
        {mfaMethods.length > 0 && (
          <p className="text-xs text-muted-foreground mt-1">Methods: {mfaMethods.join(', ')}</p>
        )}
      </div>

      <Input
        type="text"
        inputMode="numeric"
        autoComplete="one-time-code"
        placeholder={useRecovery ? 'Recovery code' : '000000'}
        value={code}
        onChange={e => setCode(e.target.value)}
        required
        maxLength={useRecovery ? 20 : 6}
        className="text-center text-lg tracking-widest font-mono"
        autoFocus
      />

      {error && (
        <div className="flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive">
          <AlertCircle className="h-4 w-4 shrink-0" />
          {error}
        </div>
      )}

      <Button
        type="submit"
        className="w-full"
        disabled={loading || code.length < (useRecovery ? 6 : 6)}
      >
        {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
        Verify
      </Button>

      <div className="flex justify-between text-xs">
        <button type="button" onClick={onBack} className="text-muted-foreground underline">
          Back to login
        </button>
        <button
          type="button"
          onClick={() => {
            setUseRecovery(!useRecovery);
            setCode('');
            setError('');
          }}
          className="text-primary underline"
        >
          {useRecovery ? 'Use authenticator' : 'Use recovery code'}
        </button>
      </div>
    </form>
  );
}

// ── Google Sign-In Button ───────────────────────────────────

function GoogleSignInButton({
  disabled,
  onCredential,
}: {
  disabled: boolean;
  onCredential: (idToken: string) => void;
}) {
  const [loading, setLoading] = useState(false);

  const handleClick = useCallback(async () => {
    setLoading(true);
    try {
      // Use Google Identity Services popup approach
      const google = (window as unknown as Record<string, unknown>).google as
        | {
            accounts: {
              id: {
                initialize: (config: Record<string, unknown>) => void;
                prompt: (cb?: (notification: { isNotDisplayed: () => boolean }) => void) => void;
              };
            };
          }
        | undefined;

      if (!google) {
        // Fallback: open Google OAuth consent in popup
        const width = 500;
        const height = 600;
        const left = window.screenX + (window.outerWidth - width) / 2;
        const top = window.screenY + (window.outerHeight - height) / 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=${width},height=${height},left=${left},top=${top}`
        );
        // Listen for message from callback
        const handler = (event: MessageEvent) => {
          if (event.origin === window.location.origin && event.data?.idToken) {
            window.removeEventListener('message', handler);
            popup?.close();
            onCredential(event.data.idToken);
          }
        };
        window.addEventListener('message', handler);
        return;
      }

      // Use GIS one-tap / popup
      google.accounts.id.initialize({
        client_id: GOOGLE_CLIENT_ID,
        callback: (response: { credential: string }) => {
          onCredential(response.credential);
        },
      });
      google.accounts.id.prompt();
    } finally {
      setLoading(false);
    }
  }, [onCredential]);

  return (
    <Button
      type="button"
      variant="outline"
      className="w-full"
      disabled={disabled || loading}
      onClick={handleClick}
    >
      {loading ? (
        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
      ) : (
        <svg className="mr-2 h-4 w-4" viewBox="0 0 24 24">
          <path
            d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z"
            fill="#4285F4"
          />
          <path
            d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
            fill="#34A853"
          />
          <path
            d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
            fill="#FBBC05"
          />
          <path
            d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
            fill="#EA4335"
          />
        </svg>
      )}
      Sign in with Google
    </Button>
  );
}

// ── Main Login Page ─────────────────────────────────────────

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

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

  // Validation
  const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
  const isValidEmail = emailRegex.test(email);
  const isValidPassword = password.length >= 8;
  const canSubmit = isValidEmail && isValidPassword && !loading;

  const validationHint = useMemo(() => {
    if (email && !isValidEmail) return 'Enter a valid email address';
    if (password && !isValidPassword) return 'Password must be at least 8 characters';
    return null;
  }, [email, password, isValidEmail, isValidPassword]);

  // Redirect if already logged in
  if (isAuthenticated) {
    router.replace('/');
    return null;
  }

  // Handle successful auth (either direct login or MFA verified)
  const handleAuthenticated = (data: {
    accessToken: string;
    refreshToken: string;
    user: Record<string, unknown>;
  }) => {
    // Store tokens and redirect — the auth context will pick them up
    localStorage.setItem('admin_access_token', data.accessToken);
    localStorage.setItem('admin_refresh_token', data.refreshToken);
    localStorage.setItem(
      'admin_auth_user',
      JSON.stringify({
        email: data.user.email,
        name: data.user.displayName || data.user.name,
        role: data.user.role,
      })
    );
    router.replace('/');
    // Force reload to re-initialize auth context from localStorage
    window.location.href = '/';
  };

  // Handle login response that might require MFA
  const handleLoginResponse = (data: Record<string, unknown>) => {
    if (data.mfaRequired) {
      setMfaChallenge(data.mfaChallenge as string);
      setMfaMethods((data.methods as string[]) || []);
      setError('');
      return;
    }
    handleAuthenticated(
      data as { accessToken: string; refreshToken: string; user: Record<string, unknown> }
    );
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (!canSubmit) return;
    setLoading(true);

    const success = await login(email, password);
    setLoading(false);

    if (success) {
      router.replace('/');
    } else {
      setError('Invalid email or password');
    }
  };

  // Google Sign-In handler
  const handleGoogleCredential = async (idToken: string) => {
    setError('');
    setLoading(true);
    try {
      const res = await fetch('/api/auth/oauth/google', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ idToken }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Google sign-in failed');
        return;
      }
      handleLoginResponse(data);
    } catch {
      setError('Service unavailable');
    } finally {
      setLoading(false);
    }
  };

  // Show MFA challenge view
  if (mfaChallenge) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-muted/40 p-4">
        <Card className="w-full max-w-sm">
          <CardHeader className="text-center">
            <CardTitle className="text-xl">Two-Factor Authentication</CardTitle>
            <CardDescription>Additional verification required</CardDescription>
          </CardHeader>
          <CardContent>
            <MfaChallengeView
              mfaChallenge={mfaChallenge}
              mfaMethods={mfaMethods}
              onVerified={handleAuthenticated}
              onBack={() => {
                setMfaChallenge(null);
                setMfaMethods([]);
              }}
            />
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-muted/40 p-4">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
            <LogIn className="h-6 w-6 text-primary" />
          </div>
          <CardTitle className="text-xl">Platform Admin</CardTitle>
          <CardDescription>Sign in to access the admin dashboard</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                type="email"
                placeholder="admin@example.com"
                value={email}
                onChange={e => setEmail(e.target.value)}
                required
                autoFocus
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                type="password"
                placeholder="••••••••"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
              />
            </div>

            {validationHint && !error && <p className="text-xs text-amber-600">{validationHint}</p>}

            {error && (
              <div className="flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive">
                <AlertCircle className="h-4 w-4 shrink-0" />
                {error}
              </div>
            )}

            <Button type="submit" className="w-full" disabled={!canSubmit}>
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Sign In
            </Button>

            {GOOGLE_CLIENT_ID && (
              <>
                <div className="relative my-2">
                  <div className="absolute inset-0 flex items-center">
                    <span className="w-full border-t" />
                  </div>
                  <div className="relative flex justify-center text-xs uppercase">
                    <span className="bg-card px-2 text-muted-foreground">or</span>
                  </div>
                </div>
                <GoogleSignInButton disabled={loading} onCredential={handleGoogleCredential} />
              </>
            )}

            <p className="text-center text-xs text-muted-foreground">
              Demo: admin@example.com / Admin123!
            </p>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
