import { useState, useEffect, useRef } from 'react';
import { Html5Qrcode } from 'html5-qrcode';

export default function AuthenticatorPWA() {
  const [status, setStatus] = useState('MENUNGGU KAMERA...');
  const [scanning, setScanning] = useState(true);
  const scannerRef = useRef(null);

  // Web Crypto API HMAC-SHA256
  const signChallenge = async (secretHex, challenge) => {
    const enc = new TextEncoder();
    // Convert hex string to Uint8Array
    const secretBytes = new Uint8Array(secretHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
    const key = await window.crypto.subtle.importKey(
      'raw', secretBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
    );
    const signature = await window.crypto.subtle.sign('HMAC', key, enc.encode(challenge));
    // Convert signature back to hex
    return Array.from(new Uint8Array(signature)).map(b => b.toString(16).padStart(2, '0')).join('');
  };

  useEffect(() => {
    document.body.style.margin = "0";
    document.body.style.background = "#000";
    document.body.style.color = "#fff";
    document.body.style.fontFamily = "monospace";

    const html5QrCode = new Html5Qrcode("reader");
    scannerRef.current = html5QrCode;

    html5QrCode.start(
      { facingMode: "environment" },
      { fps: 10, qrbox: { width: 250, height: 250 } },
      async (decodedText) => {
        setScanning(false);
        html5QrCode.stop();
        
        const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
        const ws = new WebSocket(gatekeeperUrl);

        if (decodedText.startsWith('PAIR|')) {
          setStatus('MATRIKS SETUP DITEMUKAN. MENGAWINKAN KUNCI...');
          const parts = decodedText.split('|');
          const targetKeyId = parts[1];
          const secret = parts[2];
          
          localStorage.setItem('XCU_OPTICAL_SECRET', JSON.stringify({ targetKeyId, secret }));
          
          ws.onopen = () => ws.send(JSON.stringify({ type: 'CONFIRM_OPTICAL_PAIRING', payload: { targetKeyId, secret } }));
          ws.onmessage = (e) => {
            const data = JSON.parse(e.data);
            if (data.type === 'OPTICAL_PAIRING_SUCCESS') setStatus('✅ PERANGKAT BERHASIL DIKAWINKAN');
            else setStatus('❌ GAGAL: ' + data.payload);
            ws.close();
          };
        } else {
          setStatus('MATRIKS TANTANGAN DITEMUKAN. MENGOTENTIKASI...');
          const stored = localStorage.getItem('XCU_OPTICAL_SECRET');
          if (!stored) {
            setStatus('❌ PONSEL INI BELUM DIPAIRING DARI DASBOR');
            return;
          }
          
          const { targetKeyId, secret } = JSON.parse(stored);
          const parts = decodedText.split('|');
          const opticalCode = parts[0];
          const sessionId = parts[1] === 'null' ? null : parts[1];

          // Sign the challenge
          const signature = await signChallenge(secret, opticalCode);

          ws.onopen = () => {
            ws.send(JSON.stringify({
              type: 'AEGIS_AUTH_REQUEST',
              payload: { authType: 'OPTICAL_SYNC', keyPayload: { targetKeyId, signature, challenge: opticalCode }, sessionId }
            }));
          };
          ws.onmessage = (event) => {
            try {
              const data = JSON.parse(event.data);
              if (data.type === 'AUTH_SUCCESS' || data.type === 'MFA_SEQUENCE_STARTED' || data.type === 'MFA_STEP_REQUIRED') {
                setStatus('⚡ OTORISASI BERHASIL ⚡');
                ws.close();
              } else if (data.type === 'AUTH_FAILED') {
                setStatus('❌ DITOLAK: ' + data.payload);
                ws.close();
              }
            } catch(e) {}
          };
        }
        ws.onerror = () => setStatus('❌ KONEKSI GATEKEEPER GAGAL');
      },
      (errorMessage) => {}
    ).catch((err) => setStatus('GAGAL MENGAKSES KAMERA: ' + err));

    return () => {
      if (scannerRef.current && scannerRef.current.isScanning) {
        scannerRef.current.stop();
      }
    };
  }, []);

  return (
    <div style={{display: 'flex', flexDirection: 'column', height: '100vh', padding: '20px', boxSizing: 'border-box'}}>
      <div style={{textAlign: 'center', marginBottom: '30px'}}>
        <h1 style={{color: 'var(--accent-purple)', fontSize: '2rem', margin: '0'}}>XCU</h1>
        <p style={{color: '#fff', letterSpacing: '2px', fontSize: '0.8rem'}}>AUTHENTICATOR PWA</p>
      </div>

      <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center'}}>
        {scanning ? (
          <div id="reader" style={{width: '100%', maxWidth: '400px', borderRadius: '12px', overflow: 'hidden', border: '2px solid var(--accent-purple)'}}></div>
        ) : (
          <div style={{fontSize: '5rem', marginBottom: '20px'}}>
            {status.includes('BERHASIL') ? '🔓' : '🔒'}
          </div>
        )}
        <div style={{
          marginTop: '30px', padding: '15px', background: 'rgba(168, 85, 247, 0.1)', 
          border: '1px solid var(--accent-purple)', borderRadius: '8px', 
          color: status.includes('BERHASIL') ? 'var(--accent-green)' : (status.includes('❌') ? 'var(--accent-red)' : 'var(--accent-purple)'),
          textAlign: 'center', fontWeight: 'bold'
        }}>
          {status}
        </div>
      </div>

      <div style={{textAlign: 'center', marginTop: 'auto', color: 'var(--text-muted)', fontSize: '0.7rem'}}>
        ARAHKAN KAMERA KE MATRIKS KUANTUM DI LAYAR MONITOR
      </div>
    </div>
  );
}
