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

interface LoginProps {
  onLoginSuccess: (masterKey: Uint8Array, communityId: string) => void;
}

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

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

    try {
      const result = await authenticateWebAuthn(username);

      if (result.success && result.masterKey && result.communityId) {
        onLoginSuccess(result.masterKey, result.communityId);
      } else {
        setError(result.error || 'Authentication failed');
      }
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  if (!supported) {
    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">Browser Not Supported</h2>
          <p className="text-red-400/80 text-sm">
            Your browser does not support WebAuthn. Please use a modern browser like Chrome, Firefox, Safari, or Edge.
          </p>
        </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">ArmaAdmin Cloud</h1>
          <p className="text-slate-500 text-sm font-medium">Zero-Knowledge Gaming Infrastructure</p>
        </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">Hardware Authentication</h2>
              <p className="text-xs text-slate-500">Passwordless & Zero-Trust</p>
            </div>
          </div>

          <form onSubmit={handleLogin} 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-background 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()}
              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>
                </>
              ) : (
                <>
                  <Fingerprint className="w-5 h-5" />
                  <span>Unlock with Hardware Key</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-background/50 rounded-xl">
                <div className="text-2xl font-black text-indigo-400">0</div>
                <div className="text-[10px] text-slate-500 font-bold uppercase tracking-wider mt-1">Passwords</div>
              </div>
              <div className="p-4 bg-background/50 rounded-xl">
                <div className="text-2xl font-black text-green-400">100%</div>
                <div className="text-[10px] text-slate-500 font-bold uppercase tracking-wider mt-1">E2EE</div>
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <p className="text-center text-xs text-slate-600 mt-6">
          Protected by WebAuthn FIDO2 hardware authentication
        </p>
      </div>
    </div>
  );
};
