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

interface LoginProps {
  onLoginSuccess: (token: string, masterKey: Uint8Array, communityId: string, username: 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());

  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);

      // Store token in localStorage for session persistence
      localStorage.setItem('auth_token', data.token);

      onLoginSuccess(data.token, masterKeyBytes, data.communityId, data.username);
    } 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);
    } 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, '');
  };

  if (!supported && authMethod === 'passkey') {
    return (
      <div className="min-h-screen bg-[#0a0b10] flex items-center justify-center p-6">
        <div className="max-w-md w-full bg-red-500/5 border border-red-500/20 rounded-2xl p-8 text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <h2 className="text-xl font-bold text-red-200 mb-2">Passkeys Not Supported</h2>
          <p className="text-red-400/80 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-indigo-600 hover:bg-indigo-500 text-white 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-[#0a0b10] 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-indigo-600/10 rounded-full blur-3xl animate-pulse"></div>
        <div className="absolute bottom-1/4 -right-48 w-96 h-96 bg-purple-600/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-indigo-600 rounded-2xl mb-4 shadow-2xl shadow-indigo-600/50">
            <Zap className="w-8 h-8 text-white fill-white" />
          </div>
          <h1 className="text-3xl font-black text-white tracking-tight mb-2">Welcome Back</h1>
          <p className="text-slate-500 text-sm font-medium">Sign in to your secure vault</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-indigo-600 text-white shadow-lg shadow-indigo-600/20'
                : 'bg-slate-800 text-slate-400 hover:bg-slate-700'
            }`}
          >
            <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-indigo-600 text-white shadow-lg shadow-indigo-600/20'
                : 'bg-slate-800 text-slate-400 hover:bg-slate-700'
            }`}
          >
            <Fingerprint className="w-4 h-4 inline mr-2" />
            Passkey
          </button>
        </div>

        {/* Login Card */}
        <div className="bg-[#0c0d14] border border-slate-800 rounded-3xl p-8 shadow-2xl">
          <div className="flex items-center space-x-3 mb-6">
            <div className="p-2 bg-indigo-500/10 border border-indigo-500/20 rounded-lg">
              <Shield className="w-5 h-5 text-indigo-400" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-white">{authMethod === 'password' ? 'Password Login' : 'Passkey Login'}</h2>
              <p className="text-xs text-slate-500">Zero-Trust Authentication</p>
            </div>
          </div>

          <form onSubmit={authMethod === 'password' ? handlePasswordLogin : handlePasskeyLogin} className="space-y-6">
            <div>
              <label className="block text-sm font-bold text-slate-300 mb-2">Username</label>
              <input
                type="text"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="Enter your username"
                className="w-full px-4 py-3 bg-slate-900 border border-slate-700 rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"
                required
                disabled={isLoading}
              />
            </div>

            {authMethod === 'password' && (
              <div>
                <label className="block text-sm font-bold text-slate-300 mb-2">Password</label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter your password"
                  className="w-full px-4 py-3 bg-slate-900 border border-slate-700 rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"
                  required
                  disabled={isLoading}
                />
              </div>
            )}

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

            <button
              type="submit"
              disabled={isLoading || !username.trim() || (authMethod === 'password' && !password.trim())}
              className="w-full bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-800 disabled:text-slate-600 text-white font-bold py-4 rounded-xl transition-all duration-200 shadow-lg shadow-indigo-600/20 active:scale-95 flex items-center justify-center space-x-2"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  <span>Authenticating...</span>
                </>
              ) : (
                <>
                  {authMethod === 'password' ? <Shield className="w-5 h-5" /> : <Fingerprint className="w-5 h-5" />}
                  <span>Sign in with {authMethod === 'password' ? 'Password' : 'Passkey'}</span>
                </>
              )}
            </button>
          </form>

          {/* Info Section */}
          <div className="mt-8 pt-6 border-t border-slate-800">
            <div className="grid grid-cols-2 gap-4 text-center">
              <div className="p-4 bg-slate-900/50 rounded-xl">
                <div className="text-2xl font-black text-indigo-400">E2EE</div>
                <div className="text-[10px] text-slate-500 font-bold uppercase tracking-wider mt-1">Zero-Knowledge</div>
              </div>
              <div className="p-4 bg-slate-900/50 rounded-xl">
                <div className="text-2xl font-black text-green-400">DSGVO</div>
                <div className="text-[10px] text-slate-500 font-bold uppercase tracking-wider mt-1">Compliant</div>
              </div>
            </div>
          </div>
        </div>

        {/* Switch to Register */}
        <p className="text-center text-sm text-slate-500 mt-6">
          Don't have an account?{' '}
          <button onClick={onSwitchToRegister} className="text-indigo-400 hover:text-indigo-300 font-bold transition-colors">
            Create one now
          </button>
        </p>

        {/* Footer */}
        <p className="text-center text-xs text-slate-600 mt-4">
          Protected by {authMethod === 'passkey' ? 'FIDO2 WebAuthn' : 'Argon2id'} security
        </p>
      </div>
    </div>
  );
};
