import React, { useState } from 'react';
import { Fingerprint, Shield, Zap, AlertCircle, Loader2, Key, CheckCircle, ArrowRight } from 'lucide-react';
import { isWebAuthnSupported } from '../lib/webauthn';

interface LoginProps {
  onLoginSuccess: (token: string, masterKey: Uint8Array, communityId: string, username: string, userId: string, role?: string) => void;
  onSwitchToRegister: () => void;
}

export const LoginV2: React.FC<LoginProps> = ({ onLoginSuccess, onSwitchToRegister }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [authMethod, setAuthMethod] = useState<'password' | 'passkey'>('password');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [supported] = useState(isWebAuthnSupported());

  // Stored after a successful password login while we show the passkey upsell
  const [pendingLogin, setPendingLogin] = useState<{
    token: string;
    masterKeyBytes: Uint8Array;
    communityId: string;
    username: string;
    userId: string;
    role?: string;
  } | null>(null);
  const [passkeySetupLoading, setPasskeySetupLoading] = useState(false);
  const [passkeySetupError, setPasskeySetupError] = useState<string | null>(null);

  const handlePasswordLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);

    try {
      const res = await fetch('/api/auth/login/password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Login failed');
      }

      const data = await res.json();
      const masterKeyBytes = new TextEncoder().encode(data.masterKey);

      localStorage.setItem('auth_token', data.token);

      if (supported) {
        // Show passkey upsell before entering the dashboard
        setPendingLogin({ token: data.token, masterKeyBytes, communityId: data.communityId, username: data.username, userId: data.userId, role: data.role });
      } else {
        onLoginSuccess(data.token, masterKeyBytes, data.communityId, data.username, data.userId, data.role);
      }
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  const handlePasskeyLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);

    try {
      // Step 1: Begin authentication
      const beginRes = await fetch('/api/auth/login/passkey/begin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username }),
      });

      if (!beginRes.ok) throw new Error('Failed to start passkey authentication');

      const options = await beginRes.json();

      // Step 2: Get credential
      const credential = await navigator.credentials.get({
        publicKey: {
          challenge: base64urlToBuffer(options.challenge),
          timeout: options.timeout,
          rpId: options.rpId,
          allowCredentials: (options.allowCredentials ?? []).map((id: string) => ({
            type: 'public-key' as const,
            id: base64urlToBuffer(id),
          })),
          userVerification: options.userVerification as UserVerificationRequirement,
        },
      }) as PublicKeyCredential | null;

      if (!credential) throw new Error('Authentication cancelled');

      const response = credential.response as AuthenticatorAssertionResponse;

      // Step 3: Finish authentication
      const finishRes = await fetch('/api/auth/login/passkey/finish', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: credential.id,
          rawId: bufferToBase64url(credential.rawId),
          type: credential.type,
          response: {
            authenticatorData: bufferToBase64url(response.authenticatorData),
            clientDataJSON: bufferToBase64url(response.clientDataJSON),
            signature: bufferToBase64url(response.signature),
            userHandle: response.userHandle ? bufferToBase64url(response.userHandle) : null,
          },
        }),
      });

      if (!finishRes.ok) throw new Error('Authentication failed');

      const data = await finishRes.json();
      const masterKeyBytes = new TextEncoder().encode(data.masterKey);

      localStorage.setItem('auth_token', data.token);

      onLoginSuccess(data.token, masterKeyBytes, data.communityId, data.username, data.userId ?? 'user-demo', data.role);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  const base64urlToBuffer = (base64url: string): ArrayBuffer => {
    const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
    const padded = base64.padEnd(base64.length + (4 - (base64.length % 4)) % 4, '=');
    const binary = atob(padded);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i);
    }
    return bytes.buffer;
  };

  const bufferToBase64url = (buffer: ArrayBuffer): string => {
    const bytes = new Uint8Array(buffer);
    let binary = '';
    for (let i = 0; i < bytes.length; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
  };

  const handleSetupPasskey = async () => {
    if (!pendingLogin) return;
    setPasskeySetupLoading(true);
    setPasskeySetupError(null);
    try {
      const beginRes = await fetch('/api/auth/passkeys/begin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${pendingLogin.token}` },
        body: JSON.stringify({}),
      });
      if (!beginRes.ok) throw new Error('Could not start passkey setup');
      const options = await beginRes.json();

      const credential = await navigator.credentials.create({
        publicKey: {
          challenge: base64urlToBuffer(options.challenge),
          rp: options.rp,
          user: {
            id: new TextEncoder().encode(options.user.id),
            name: options.user.name,
            displayName: options.user.displayName,
          },
          pubKeyCredParams: options.pubKeyCredParams as PublicKeyCredentialParameters[],
          timeout: options.timeout,
          attestation: options.attestation as AttestationConveyancePreference,
          authenticatorSelection: options.authenticatorSelection as AuthenticatorSelectionCriteria,
        },
      }) as PublicKeyCredential | null;

      if (!credential) throw new Error('Passkey setup was cancelled');
      const response = credential.response as AuthenticatorAttestationResponse;

      const finishRes = await fetch('/api/auth/passkeys/finish', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${pendingLogin.token}` },
        body: JSON.stringify({
          id: credential.id,
          rawId: bufferToBase64url(credential.rawId),
          type: credential.type,
          response: {
            attestationObject: bufferToBase64url(response.attestationObject),
            clientDataJSON: bufferToBase64url(response.clientDataJSON),
          },
        }),
      });
      if (!finishRes.ok) throw new Error('Failed to save passkey');

      onLoginSuccess(pendingLogin.token, pendingLogin.masterKeyBytes, pendingLogin.communityId, pendingLogin.username, pendingLogin.userId, pendingLogin.role);
    } catch (err) {
      setPasskeySetupError((err as Error).message);
      setPasskeySetupLoading(false);
    }
  };

  const handleSkipPasskey = () => {
    if (!pendingLogin) return;
    onLoginSuccess(pendingLogin.token, pendingLogin.masterKeyBytes, pendingLogin.communityId, pendingLogin.username, pendingLogin.userId, pendingLogin.role);
  };

  if (pendingLogin) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-6 relative overflow-hidden">
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          <div className="absolute top-1/4 -left-48 w-96 h-96 bg-primary/10 rounded-full blur-3xl animate-pulse"></div>
          <div className="absolute bottom-1/4 -right-48 w-96 h-96 bg-indigo-500/10 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }}></div>
        </div>

        <div className="max-w-md w-full relative z-10">
          <div className="text-center mb-10">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-primary rounded-2xl mb-4 shadow-2xl shadow-primary/50">
              <Zap className="w-8 h-8 text-primary-foreground fill-primary-foreground" />
            </div>
            <h1 className="text-3xl font-black text-foreground tracking-tight mb-2 uppercase italic">ArmaCloud</h1>
          </div>

          <div className="bg-card/50 backdrop-blur-xl border border-border/50 rounded-3xl p-8 shadow-2xl space-y-6">
            {/* Signed-in confirmation */}
            <div className="flex items-center gap-4 p-4 bg-emerald-500/5 border border-emerald-500/20 rounded-2xl">
              <div className="w-10 h-10 bg-emerald-500/10 border border-emerald-500/20 rounded-xl flex items-center justify-center flex-shrink-0">
                <CheckCircle className="w-5 h-5 text-emerald-500" />
              </div>
              <div>
                <p className="font-bold text-foreground text-sm">Signed in as <span className="text-primary">{pendingLogin.username}</span></p>
                <p className="text-xs text-muted-foreground">Password login successful</p>
              </div>
            </div>

            {/* Passkey pitch */}
            <div className="space-y-3">
              <div className="flex items-start gap-4">
                <div className="p-3 bg-primary/10 border border-primary/20 rounded-xl flex-shrink-0 mt-0.5">
                  <Fingerprint className="w-6 h-6 text-primary" />
                </div>
                <div>
                  <h2 className="font-black text-xl text-foreground mb-1">Use a passkey next time?</h2>
                  <p className="text-sm text-muted-foreground leading-relaxed">
                    Passkeys use your device's fingerprint, face ID, or PIN — no password to remember.
                    Setting one up takes just a few seconds and replaces your password entirely.
                  </p>
                </div>
              </div>

              <ul className="space-y-2 pl-1">
                {['Faster sign-in, no password needed', 'Phishing-resistant by design', 'Stored securely on your device'].map(item => (
                  <li key={item} className="flex items-center gap-2 text-sm text-muted-foreground">
                    <ArrowRight className="w-3.5 h-3.5 text-primary flex-shrink-0" />
                    {item}
                  </li>
                ))}
              </ul>
            </div>

            {passkeySetupError && (
              <div className="p-3 bg-destructive/10 border border-destructive/20 rounded-xl flex items-center gap-2 text-xs text-destructive">
                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                {passkeySetupError}
              </div>
            )}

            <div className="space-y-3">
              <button
                onClick={handleSetupPasskey}
                disabled={passkeySetupLoading}
                className="w-full bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground text-primary-foreground font-black uppercase tracking-widest py-4 rounded-xl transition-all duration-200 shadow-lg shadow-primary/20 active:scale-95 flex items-center justify-center gap-2"
              >
                {passkeySetupLoading ? (
                  <><Loader2 className="w-5 h-5 animate-spin" /> Setting up...</>
                ) : (
                  <><Fingerprint className="w-5 h-5" /> Set up Passkey</>
                )}
              </button>
              <button
                onClick={handleSkipPasskey}
                disabled={passkeySetupLoading}
                className="w-full py-3 text-sm text-muted-foreground hover:text-foreground transition-colors font-medium"
              >
                Skip for now — continue with password
              </button>
            </div>
          </div>

          <p className="text-center text-[10px] font-bold text-muted-foreground/30 mt-8 uppercase tracking-[0.2em]">
            ArmaCloud &copy; 2026
          </p>
        </div>
      </div>
    );
  }

  if (!supported && authMethod === 'passkey') {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-6">
        <div className="max-w-md w-full bg-destructive/10 border border-destructive/20 rounded-2xl p-8 text-center">
          <AlertCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
          <h2 className="text-xl font-bold text-destructive mb-2">Passkeys Not Supported</h2>
          <p className="text-muted-foreground text-sm mb-4">
            Your browser does not support WebAuthn. Please use a modern browser or switch to password login.
          </p>
          <button
            onClick={() => setAuthMethod('password')}
            className="bg-primary hover:bg-primary/90 text-primary-foreground px-6 py-2 rounded-xl font-bold text-sm transition-colors"
          >
            Use Password Instead
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-6 relative overflow-hidden">
      {/* Background Effects */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-1/4 -left-48 w-96 h-96 bg-primary/10 rounded-full blur-3xl animate-pulse"></div>
        <div className="absolute bottom-1/4 -right-48 w-96 h-96 bg-indigo-500/10 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }}></div>
      </div>

      <div className="max-w-md w-full relative z-10">
        {/* Logo & Branding */}
        <div className="text-center mb-10">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-primary rounded-2xl mb-4 shadow-2xl shadow-primary/50">
            <Zap className="w-8 h-8 text-primary-foreground fill-primary-foreground" />
          </div>
          <h1 className="text-3xl font-black text-foreground tracking-tight mb-2 uppercase italic italic">ArmaCloud</h1>
          <p className="text-muted-foreground text-sm font-medium tracking-widest uppercase">Sign in to your account</p>
        </div>

        {/* Auth Method Selector */}
        <div className="flex gap-2 mb-6">
          <button
            onClick={() => setAuthMethod('password')}
            className={`flex-1 px-4 py-3 rounded-xl font-bold text-sm transition-all ${
              authMethod === 'password'
                ? 'bg-primary text-primary-foreground shadow-lg shadow-primary/20'
                : 'bg-muted text-muted-foreground hover:bg-accent hover:text-accent-foreground'
            }`}
          >
            <Key className="w-4 h-4 inline mr-2" />
            Password
          </button>
          <button
            onClick={() => setAuthMethod('passkey')}
            className={`flex-1 px-4 py-3 rounded-xl font-bold text-sm transition-all ${
              authMethod === 'passkey'
                ? 'bg-primary text-primary-foreground shadow-lg shadow-primary/20'
                : 'bg-muted text-muted-foreground hover:bg-accent hover:text-accent-foreground'
            }`}
          >
            <Fingerprint className="w-4 h-4 inline mr-2" />
            Passkey
          </button>
        </div>

        {/* Login Card */}
        <div className="bg-card/50 backdrop-blur-xl border border-border/50 rounded-3xl p-8 shadow-2xl">
          <div className="flex items-center space-x-3 mb-6">
            <div className="p-2 bg-primary/10 border border-primary/20 rounded-lg">
              <Shield className="w-5 h-5 text-primary" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-foreground">{authMethod === 'password' ? 'Sign in' : 'Sign in with Passkey'}</h2>
              <p className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Welcome back</p>
            </div>
          </div>

          <form onSubmit={authMethod === 'password' ? handlePasswordLogin : handlePasskeyLogin} className="space-y-6">
            <div className="space-y-2">
              <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Username</label>
              <input
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="Operator ID"
                className="w-full px-4 py-3 bg-background border border-border/50 rounded-xl text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                required
                disabled={isLoading}
              />
            </div>

            {authMethod === 'password' && (
              <div className="space-y-2">
                <label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground/60">Password</label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••••••"
                  className="w-full px-4 py-3 bg-background border border-border/50 rounded-xl text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                  required
                  disabled={isLoading}
                />
              </div>
            )}

            {error && (
              <div className="p-4 bg-destructive/10 border border-destructive/20 rounded-xl flex items-start space-x-3">
                <AlertCircle className="w-5 h-5 text-destructive flex-shrink-0 mt-0.5" />
                <div>
                  <h3 className="text-sm font-bold text-destructive">Login failed</h3>
                  <p className="text-xs text-destructive/80 mt-1">{error}</p>
                </div>
              </div>
            )}

            <button
              type="submit"
              disabled={isLoading || !username.trim() || (authMethod === 'password' && !password.trim())}
              className="w-full bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground text-primary-foreground font-black uppercase tracking-widest py-4 rounded-xl transition-all duration-200 shadow-lg shadow-primary/20 active:scale-95 flex items-center justify-center space-x-2"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  <span>Verifying...</span>
                </>
              ) : (
                <>
                  {authMethod === 'password' ? <Shield className="w-5 h-5" /> : <Fingerprint className="w-5 h-5" />}
                  <span>Sign In</span>
                </>
              )}
            </button>
          </form>

          {/* Info Section */}
          <div className="mt-8 pt-6 border-t border-border/50">
            <p className="text-[11px] text-muted-foreground/50 text-center leading-relaxed">
              Your data is end-to-end encrypted. Encryption keys never leave your device.
            </p>
          </div>
        </div>

        {/* Switch to Register */}
        <p className="text-center text-sm text-muted-foreground mt-6">
          Don't have an account?{' '}
          <button onClick={onSwitchToRegister} className="text-primary hover:text-primary/80 font-black transition-colors uppercase tracking-widest">
            Create account
          </button>
        </p>

        {/* Footer */}
        <p className="text-center text-[10px] font-bold text-muted-foreground/30 mt-8 uppercase tracking-[0.2em]">
          ArmaCloud &copy; 2026
        </p>
      </div>
    </div>
  );
};
