import { useState, useEffect, useRef } from 'react';
import { useAuth } from '../context/AuthContext';
import { useI18n } from '../context/I18nContext';
import UniversalTopbar from './UniversalTopbar';
import './LoginGateway.css'; 
import { startAuthentication } from '@simplewebauthn/browser';
import QRCode from 'react-qr-code';
import signatureData from '../config/signature.json';

function DeepSpaceRadarCanvas() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    
    let width = canvas.width = window.innerWidth;
    let height = canvas.height = window.innerHeight;

    // Starfield
    const stars = Array.from({ length: 200 }, () => ({
      x: Math.random() * width,
      y: Math.random() * height,
      size: Math.random() * 2,
      speed: Math.random() * 0.5 + 0.1,
      brightness: Math.random()
    }));

    const draw = () => {
      ctx.fillStyle = '#020108';
      ctx.fillRect(0, 0, width, height);
      
      stars.forEach(star => {
        ctx.fillStyle = `rgba(255, 255, 255, ${star.brightness})`;
        ctx.beginPath();
        ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
        ctx.fill();
        
        star.y += star.speed;
        if (star.y > height) {
          star.y = 0;
          star.x = Math.random() * width;
        }
      });
    };

    const intervalId = setInterval(draw, 30);
    const handleResize = () => {
      width = canvas.width = window.innerWidth;
      height = canvas.height = window.innerHeight;
    };
    window.addEventListener('resize', handleResize);

    return () => {
      clearInterval(intervalId);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <>
      <canvas ref={canvasRef} className="quantum-canvas" />
      <div className="hud-overlay" />
      <div className="radar-ring" />
    </>
  );
}

export default function LoginGateway() {
  const [error, setError] = useState('');
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const [opticalCode, setOpticalCode] = useState('AWAITING-SYNC...');
  const [isDragging, setIsDragging] = useState(false);
  const [mfaSession, setMfaSession] = useState(null);
  
  const { aegisAuth } = useAuth();
  const { t } = useI18n();

  // Listen for Optical Challenge from IAM Gatekeeper
  useEffect(() => {
    const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
    const ws = new WebSocket(gatekeeperUrl);
    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'OPTICAL_CHALLENGE') {
          setOpticalCode(data.payload);
        }
      } catch (e) {}
    };
    return () => {
      if (ws.readyState === 1) ws.close();
    };
  }, []);

  const handleAuthResult = (result) => {
    if (result && result.mfa) {
      setMfaSession(result.payload);
      setError('');
    } else {
      setMfaSession(null);
    }
  };

  const handleBiometricPulse = async () => {
    setError('');
    setIsAuthenticating(true);
    try {
      const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
      const ws = new WebSocket(gatekeeperUrl);
      
      const authOptions = await new Promise((resolve, reject) => {
        ws.onopen = () => {
          ws.send(JSON.stringify({ type: 'GENERATE_AUTHENTICATION_OPTIONS', payload: {} }));
        };
        ws.onmessage = (event) => {
          const data = JSON.parse(event.data);
          if (data.type === 'AUTHENTICATION_OPTIONS') resolve(data.payload);
          else if (data.type === 'AUTH_FAILED') reject(new Error(data.payload));
        };
        ws.onerror = () => reject(new Error('Koneksi WebAuthn Gagal'));
      });

      const asseResp = await startAuthentication(authOptions);
      const res = await aegisAuth('BIOMETRIC_PULSE', asseResp, mfaSession?.sessionId);
      handleAuthResult(res);
    } catch (err) {
      setError(err.message || t('access_denied'));
    } finally {
      setIsAuthenticating(false);
    }
  };

  const handleOpticalSyncBypass = async () => {
    setError('');
    setIsAuthenticating(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      const res = await aegisAuth('OPTICAL_SYNC', opticalCode, mfaSession?.sessionId);
      handleAuthResult(res);
    } catch (err) {
      setError(err.message || t('access_denied'));
    } finally {
      setIsAuthenticating(false);
    }
  };

  useEffect(() => {
    const handleDragOver = (e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); };
    const handleDragEnter = (e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); };
    const handleDragLeave = (e) => {
      e.preventDefault(); e.stopPropagation();
      if (e.target === document || e.clientY <= 0 || e.clientX <= 0 || (e.clientX >= window.innerWidth || e.clientY >= window.innerHeight)) {
        setIsDragging(false);
      }
    };
    const handleGlobalDrop = async (e) => {
      e.preventDefault(); e.stopPropagation(); setIsDragging(false);
      const file = e.dataTransfer.files[0];
      if (!file) return;
      setError(''); setIsAuthenticating(true);

      if (!file.name.endsWith('.xcu')) {
        setError(t('format_rejected'));
        setIsAuthenticating(false);
        return;
      }

      const reader = new FileReader();
      reader.onload = async (event) => {
        try {
          const fileContent = event.target.result.trim();
          await new Promise(resolve => setTimeout(resolve, 800)); 
          const res = await aegisAuth('AEGIS_KEYCARD', fileContent, mfaSession?.sessionId);
          handleAuthResult(res);
        } catch (err) {
          setError(err.message || t('access_denied'));
        } finally {
          setIsAuthenticating(false);
        }
      };
      reader.readAsText(file);
    };

    window.addEventListener('dragover', handleDragOver);
    window.addEventListener('dragenter', handleDragEnter);
    window.addEventListener('dragleave', handleDragLeave);
    window.addEventListener('drop', handleGlobalDrop);

    return () => {
      window.removeEventListener('dragover', handleDragOver);
      window.removeEventListener('dragenter', handleDragEnter);
      window.removeEventListener('dragleave', handleDragLeave);
      window.removeEventListener('drop', handleGlobalDrop);
    };
  }, [aegisAuth, t]);

  return (
    <div className="login-gateway-container">
      <UniversalTopbar />
      <DeepSpaceRadarCanvas />
      
      {isDragging && (
        <div className="reactor-active">
          <div style={{fontSize: '5rem', marginBottom: '20px', animation: 'sonarPulse 1s infinite'}}>☢️</div>
          <h1 style={{color: 'var(--accent-red)', fontFamily: 'monospace', letterSpacing: '5px'}}>{t('aegis_reactor_open')}</h1>
          <p style={{color: '#fff', fontFamily: 'monospace'}}>{t('drop_key_to_trigger')}</p>
        </div>
      )}

      {!isDragging && (
        <div className="aegis-monolith">
          <h1 className="supreme-title" data-text="XCU">
            <span className="kinetic-glitch" data-text="XCU">XCU</span>
          </h1>
          <div className="supreme-subtitle" style={{marginBottom: '10px'}}>O M N I - E N G I N E   G A T E W A Y</div>
          <div style={{
            textAlign: 'center', marginBottom: '40px', fontFamily: 'monospace', 
            color: 'var(--accent-cyan)', fontSize: '0.65rem', letterSpacing: '3px',
            textShadow: '0 0 5px var(--accent-cyan)', opacity: 0.8
          }}>
            V.{signatureData.signature}
          </div>

          {error && (
            <div style={{marginBottom: '25px', padding: '15px', background: 'rgba(255, 0, 60, 0.1)', borderLeft: '4px solid var(--accent-red)', color: 'var(--accent-red)', fontFamily: 'monospace'}}>
              <div className="typewriter-text">{error}</div>
            </div>
          )}

          {mfaSession ? (
            <div style={{textAlign: 'center', animation: 'fadeIn 0.5s ease'}}>
              <div style={{marginBottom: '20px', color: 'var(--accent-yellow)', fontFamily: 'monospace', borderBottom: '1px solid rgba(255,234,0,0.3)', paddingBottom: '10px'}}>
                {t('mfa_sequence_activated')}
              </div>
              <p style={{color: 'var(--text-muted)', fontSize: '0.9rem', marginBottom: '30px', fontFamily: 'monospace'}}>
                {t('mfa_sequence_desc')}
              </p>
              
              <div style={{display: 'flex', flexDirection: 'column', gap: '20px'}}>
                {mfaSession.requiredSteps.includes('BIOMETRIC_PULSE') && (
                  <button className="biometric-sonar-btn" onClick={handleBiometricPulse} disabled={isAuthenticating}>
                    {isAuthenticating ? t('scanning') : t('biometric_pulse_l1')}
                  </button>
                )}
                
                {mfaSession.requiredSteps.includes('OPTICAL_SYNC') && (
                  <div className="sniper-qr-container">
                    <div className="corners" />
                    <QRCode value={opticalCode} size={150} bgColor="transparent" fgColor="var(--accent-cyan)" />
                    <div className="cipher-text" onClick={handleOpticalSyncBypass} style={{cursor: 'pointer'}}>
                      {t('decrypting_optical_l2')}
                    </div>
                  </div>
                )}
                
                {mfaSession.requiredSteps.includes('AEGIS_KEYCARD') && (
                  <div className="reactor-dropzone">
                    {t('aegis_keycard_l3')}<br/><span style={{fontSize: '0.7rem', color: 'var(--text-muted)'}}>{t('drag_drop_xcu')}</span>
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div style={{animation: 'fadeIn 0.5s ease'}}>
              <button className="biometric-sonar-btn" onClick={handleBiometricPulse} disabled={isAuthenticating} style={{marginTop: '20px'}}>
                {isAuthenticating ? t('authorizing') : t('auth_fido2')}
              </button>
              
              <div style={{textAlign: 'center', marginTop: '30px'}}>
                <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', fontFamily: 'monospace', marginBottom: '15px'}}>{t('or_use_bypass')}</div>
                
                <div className="reactor-dropzone" style={{opacity: 0.7}}>
                  {t('drop_zone')}<br/>
                  <span style={{fontSize: '0.7rem'}}>{t('aegis_keycard_founder')}</span>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
