// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { useIamPolicy } from '../context/IamPolicyContext';
import { useAuth } from '../context/AuthContext';
import { startRegistration } from '@simplewebauthn/browser';
import { useRef, useState } from 'react';
import QRCode from 'react-qr-code';

export default function SecurityEnclave() {
  const { policies, identities, updatePolicy, regenerateKey } = useIamPolicy();
  const { cryptographicKey } = useAuth();

  // Decode identity from local token and find real KeyId
  let tenantKeyId = null;
  try {
    const payload = JSON.parse(atob(cryptographicKey.split('.')[1]));
    tenantKeyId = Object.keys(identities).find(key => identities[key].tenant_id === payload.tenant_id);
  } catch (e) {}

  const [pairingQr, setPairingQr] = useState(null);

  const handleRegisterBiometric = () => {
    const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
    const ws = new WebSocket(gatekeeperUrl);
    ws.onopen = () => {
      ws.send(JSON.stringify({ type: 'GENERATE_REGISTRATION_OPTIONS', payload: { targetKeyId: tenantKeyId } }));
    };
    ws.onmessage = async (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'REGISTRATION_OPTIONS') {
          const options = data.payload;
          const attResp = await startRegistration(options);
          ws.send(JSON.stringify({ type: 'VERIFY_REGISTRATION_RESPONSE', payload: { targetKeyId: tenantKeyId, response: attResp } }));
        } else if (data.type === 'REGISTRATION_SUCCESS') {
          alert('Berhasil! Kunci Biometrik Anda telah terdaftar permanen di XCU Ultra.');
          ws.close();
        } else if (data.type === 'AUTH_FAILED') {
          alert('Registrasi Gagal: ' + data.payload);
          ws.close();
        }
      } catch (err) {
        alert('Gagal memproses WebAuthn.');
      }
    };
  };

  const handlePairOptical = () => {
    const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
    const ws = new WebSocket(gatekeeperUrl);
    ws.onopen = () => {
      ws.send(JSON.stringify({ type: 'GENERATE_OPTICAL_PAIRING', payload: { targetKeyId: tenantKeyId } }));
    };
    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.type === 'OPTICAL_PAIRING_QR') {
        setPairingQr(data.payload);
      } else if (data.type === 'OPTICAL_PAIRING_SUCCESS') {
        alert('LUAR BIASA! Ponsel Cerdas Anda kini telah resmi terikat dengan Server secara Air-Gapped.');
        setPairingQr(null);
        ws.close();
      } else if (data.type === 'AUTH_FAILED') {
        alert(data.payload);
        ws.close();
      }
    };
  };

  // RESILIENT: Use default policy if Gatekeeper WebSocket is offline
  const livePolicy = policies[tenantKeyId];
  const isOffline = !livePolicy;
  const activePolicy = livePolicy || {
    supreme_allowed: { biometric: true, optical: true, aegis: true },
    tenant_enabled: { biometric: false, optical: false, aegis: true },
    mfa_mode: 'free'
  };

  const handleToggle = (methodKey, currentValue) => {
    if (isOffline) {
      alert("GATEKEEPER OFFLINE: Koneksi WebSocket ke IAM Gatekeeper belum tersedia. Perubahan tidak dapat disimpan saat ini.");
      return;
    }
    
    if (!activePolicy.supreme_allowed[methodKey]) {
      alert("AKSES DITOLAK: Protokol ini dikunci mati oleh Supreme Admin.");
      return;
    }

    const newTenantEnabled = {
      ...activePolicy.tenant_enabled,
      [methodKey]: !currentValue
    };

    updatePolicy(tenantKeyId, null, newTenantEnabled);
  };

  const renderMethodBox = (title, desc, methodKey, icon) => {
    const isSupremeAllowed = activePolicy.supreme_allowed[methodKey];
    const isTenantEnabled = activePolicy.tenant_enabled[methodKey];
    
    const isActive = isSupremeAllowed && isTenantEnabled;
    const isLocked = !isSupremeAllowed;

    return (
      <div style={{
        flex: 1, border: `1px solid ${isActive ? 'var(--accent-cyan)' : (isLocked ? 'var(--accent-red)' : 'var(--table-border)')}`, 
        background: isActive ? 'rgba(0, 243, 255, 0.05)' : 'var(--panel-bg)', 
        padding: '30px', borderRadius: '12px', textAlign: 'center', display: 'flex', flexDirection: 'column',
        opacity: isLocked ? 0.6 : 1, transition: 'all 0.3s'
      }}>
        <div style={{fontSize: '3rem', marginBottom: '15px'}}>{icon}</div>
        <h3 style={{color: isActive ? 'var(--accent-cyan)' : 'var(--text-main)', marginBottom: '10px'}}>{title}</h3>
        <p style={{color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '20px', flex: 1}}>{desc}</p>
        
        {isLocked ? (
          <div style={{color: 'var(--accent-red)', fontFamily: 'monospace', fontWeight: 'bold', padding: '10px', border: '1px solid var(--accent-red)', borderRadius: '4px'}}>
            LOCKED BY SUPREME
          </div>
        ) : (
          <button 
            onClick={() => handleToggle(methodKey, isTenantEnabled)}
            style={{
              padding: '10px', background: isTenantEnabled ? 'var(--accent-cyan)' : 'transparent',
              color: isTenantEnabled ? '#000' : 'var(--text-muted)', border: `1px solid ${isTenantEnabled ? 'var(--accent-cyan)' : 'var(--table-border)'}`,
              borderRadius: '4px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold', transition: 'all 0.2s'
            }}
          >
            {isTenantEnabled ? 'ENABLED' : 'DISABLED'}
          </button>
        )}
      </div>
    );
  };

  return (
    <div className="glass-panel" style={{padding: '30px', borderColor: 'var(--accent-cyan)'}}>
      <h2 style={{color: 'var(--accent-cyan)', marginBottom: '10px', textTransform: 'uppercase', letterSpacing: '2px'}}>Security Enclave</h2>
      <p style={{color: 'var(--text-muted)', marginBottom: '10px'}}>
        Pusat kendali pertahanan lapis tiga. Anda memiliki otonomi untuk mengunci metode masuk tertentu demi mencegah pembajakan fisik.
      </p>

      {isOffline && (
        <div style={{
          padding: '10px 15px', background: 'rgba(255, 234, 0, 0.1)', border: '1px solid var(--accent-yellow)',
          borderRadius: '6px', marginBottom: '20px', display: 'flex', alignItems: 'center', gap: '10px'
        }}>
          <span style={{color: 'var(--accent-yellow)', fontSize: '1.2rem'}}>⚠</span>
          <span style={{color: 'var(--accent-yellow)', fontFamily: 'monospace', fontSize: '0.8rem'}}>
            GATEKEEPER OFFLINE — Menampilkan konfigurasi default. Koneksi WebSocket ke port 4001 tidak tersedia.
          </span>
        </div>
      )}

      <div style={{display: 'flex', gap: '20px', alignItems: 'stretch'}}>
        {renderMethodBox('Lapis 1: Biometric', 'Login seketika menggunakan Sidik Jari atau FaceID dari perangkat keras Anda.', 'biometric', '👆')}
        {renderMethodBox('Lapis 2: Optical', 'Gunakan Smartphone Anda untuk memindai Matriks Kuantum pada layar.', 'optical', '📱')}
        {renderMethodBox('Lapis 3: Aegis', 'Gunakan berkas kunci fisik berekstensi .xcu untuk kondisi terisolasi.', 'aegis', '💽')}
      </div>

      <div style={{marginTop: '40px', padding: '20px', background: 'var(--panel-bg)', border: '1px solid var(--accent-purple)', borderRadius: '12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
        <div>
          <h3 style={{color: 'var(--accent-purple)', marginBottom: '5px'}}>MFA SEQUENCE STRATEGY</h3>
          <p style={{color: 'var(--text-muted)', fontSize: '0.85rem'}}>Jika lebih dari 1 Lapis aktif, tentukan bagaimana urutan masuknya.</p>
        </div>
        <select 
          value={activePolicy.mfa_mode || 'free'} 
          onChange={(e) => {
            if (isOffline) { alert("GATEKEEPER OFFLINE: Tidak dapat mengubah MFA mode."); return; }
            updatePolicy(tenantKeyId, null, null, e.target.value);
          }}
          style={{
            padding: '12px', background: 'rgba(168, 85, 247, 0.1)', color: 'var(--accent-purple)',
            border: '1px solid var(--accent-purple)', borderRadius: '6px', cursor: 'pointer',
            fontFamily: 'monospace', fontWeight: 'bold'
          }}
        >
          <option value="free">FREE MODE (Pilih Salah Satu Saja)</option>
          <option value="strict">STRICT MODE (Wajib Semua Secara Berurutan)</option>
          <option value="random">QUANTUM RANDOM (Wajib Semua, Urutan Acak)</option>
        </select>
      </div>

      <div style={{marginTop: '40px', padding: '20px', background: 'rgba(0, 243, 255, 0.05)', border: '1px solid var(--accent-cyan)', borderRadius: '12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
        <div>
          <h3 style={{color: 'var(--accent-cyan)', marginBottom: '5px'}}>HARDWARE BIOMETRIC BINDING</h3>
          <p style={{color: 'var(--text-muted)', fontSize: '0.85rem'}}>Daftarkan Windows Hello / TouchID pada mesin ini sebagai Kunci Publik Kinetik.</p>
        </div>
        <button 
          onClick={handleRegisterBiometric}
          style={{
            padding: '12px 20px', background: 'var(--accent-cyan)', color: '#000', border: 'none',
            borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold',
            boxShadow: '0 0 15px rgba(0, 243, 255, 0.4)'
          }}
        >
          👆 DAFTARKAN BIOMETRIK
        </button>
      </div>

      <div style={{marginTop: '40px', padding: '20px', background: 'rgba(168, 85, 247, 0.05)', border: '1px solid var(--accent-purple)', borderRadius: '12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
        <div>
          <h3 style={{color: 'var(--accent-purple)', marginBottom: '5px'}}>AIR-GAPPED MOBILE PAIRING</h3>
          <p style={{color: 'var(--text-muted)', fontSize: '0.85rem'}}>Kawinkan Ponsel Cerdas Anda sebagai Penandatangan Kriptografi Offline.</p>
        </div>
        <button 
          onClick={handlePairOptical}
          style={{
            padding: '12px 20px', background: 'var(--accent-purple)', color: '#fff', border: 'none',
            borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold',
            boxShadow: '0 0 15px rgba(168, 85, 247, 0.4)'
          }}
        >
          🔗 PAIR MOBILE AUTHENTICATOR
        </button>
      </div>

      <div style={{marginTop: '40px', padding: '20px', background: 'rgba(255, 0, 60, 0.05)', border: '1px solid var(--accent-red)', borderRadius: '12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
        <div>
          <h3 style={{color: 'var(--accent-red)', marginBottom: '5px'}}>EMERGENCY KEYCARD ROTATION</h3>
          <p style={{color: 'var(--text-muted)', fontSize: '0.85rem'}}>Hanguskan kunci .xcu lama Anda jika dicuri, dan langsung unduh kunci Kinetik yang baru.</p>
        </div>
        <button 
          onClick={() => {
            if (isOffline) { alert("GATEKEEPER OFFLINE: Tidak dapat merotasi keycard."); return; }
            if (window.confirm("Peringatan Mutlak: Kunci Aegis lama Anda akan ditolak selamanya. Lanjutkan?")) {
              regenerateKey(tenantKeyId);
            }
          }}
          style={{
            padding: '12px 20px', background: 'var(--accent-red)', color: '#fff', border: 'none',
            borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold',
            boxShadow: '0 0 15px rgba(255, 0, 60, 0.4)'
          }}
        >
          🚨 FORGE NEW KEYCARD
        </button>
      </div>

      {/* PAIRING MODAL */}
      {pairingQr && (
        <div style={{
          position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', 
          background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(10px)', 
          zIndex: 99999, display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <div className="glass-panel" style={{padding: '40px', textAlign: 'center', maxWidth: '500px', borderColor: 'var(--accent-purple)'}}>
            <h1 style={{color: 'var(--accent-purple)', marginBottom: '20px'}}>🔗 PAIR MOBILE DEVICE</h1>
            <p style={{color: 'var(--text-main)', marginBottom: '20px'}}>
              Buka <strong style={{color: 'var(--accent-cyan)'}}>http://localhost:4173/authenticator</strong> di Ponsel Anda dan Pindai Matriks ini untuk mengunci Kriptografi.
            </p>
            
            <div style={{background: '#fff', padding: '20px', display: 'inline-block', borderRadius: '12px', marginBottom: '30px'}}>
              <QRCode value={pairingQr} size={250} fgColor="#000" bgColor="#fff" />
            </div>
            
            <div>
              <button 
                onClick={() => setPairingQr(null)}
                style={{
                  padding: '10px 30px', background: 'transparent', color: 'var(--text-muted)', border: '1px solid var(--text-muted)',
                  borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace'
                }}
              >
                BATAL
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
