// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { useIamPolicy } from '../context/IamPolicyContext';

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

  // Resilient: default identities if Gatekeeper WebSocket offline
  const isOffline = !identities || Object.keys(identities).length === 0;
  const activeIdentities = isOffline ? {
    'AEGIS-SUPREME-974EFB44BE-X': { role: 'supreme_admin', tenant_id: 'XCU-SUPREME' },
    'AEGIS-TENANT-80AA3EEBE8-X': { role: 'tenant_admin', tenant_id: 'JUMPA.ID' }
  } : identities;
  const activePolicies = isOffline ? {
    'AEGIS-TENANT-80AA3EEBE8-X': {
      name: 'JUMPA.ID ENTERPRISE',
      supreme_allowed: { biometric: true, optical: true, aegis: true },
      tenant_enabled: { biometric: false, optical: false, aegis: true },
      mfa_mode: 'free'
    }
  } : (policies || {});

  const handleToggle = (keyId, methodKey, currentValue) => {
    if (isOffline) { alert('GATEKEEPER OFFLINE: Perubahan tidak dapat disimpan.'); return; }
    const policy = activePolicies[keyId];
    if (!policy) return;
    const newSupremeAllowed = { ...policy.supreme_allowed, [methodKey]: !currentValue };
    updatePolicy(keyId, newSupremeAllowed, null, null);
  };

  const handleMfaMode = (keyId, newMode) => {
    if (isOffline) { alert('GATEKEEPER OFFLINE: Perubahan tidak dapat disimpan.'); return; }
    updatePolicy(keyId, null, null, newMode);
  };

  return (
    <div className="glass-panel" style={{padding: '30px', borderColor: 'var(--accent-red)'}}>
      <h2 style={{color: 'var(--accent-red)', marginBottom: '10px', textTransform: 'uppercase', letterSpacing: '2px'}}>IAM Architect Matrix &amp; Key Forge</h2>
      <p style={{color: 'var(--text-muted)', marginBottom: '10px'}}>
        Kendali Diktator Mutlak atas metode otentikasi Kriptografik seluruh Tenant.
      </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.
          </span>
        </div>
      )}

      <table className="glass-table" style={{width: '100%', borderCollapse: 'collapse', textAlign: 'left'}}>
        <thead>
          <tr style={{borderBottom: '1px solid var(--table-border)'}}>
            <th style={{padding: '15px', color: 'var(--text-muted)', fontSize: '0.8rem'}}>IDENTITAS</th>
            <th style={{padding: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center'}}>BIOMETRIC</th>
            <th style={{padding: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center'}}>OPTICAL</th>
            <th style={{padding: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center'}}>AEGIS</th>
            <th style={{padding: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center'}}>MFA</th>
            <th style={{padding: '15px', color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center'}}>FORGE</th>
          </tr>
        </thead>
        <tbody>
          {Object.entries(activeIdentities).map(([keyId, identity]) => {
            const policy = activePolicies[keyId] || null;
            return (
              <tr key={keyId} style={{borderBottom: '1px solid var(--table-border-light)'}}>
                <td style={{padding: '15px'}}>
                  <div style={{color: 'var(--text-main)', fontWeight: 'bold'}}>{policy ? policy.name : 'SUPREME COMMAND'}</div>
                  <div style={{color: 'var(--accent-purple)', fontSize: '0.7rem', fontFamily: 'monospace'}}>{keyId}</div>
                  <div style={{color: 'var(--text-muted)', fontSize: '0.6rem'}}>{(identity && identity.role) ? identity.role.toUpperCase() : 'N/A'}</div>
                </td>
                
                {['biometric', 'optical', 'aegis'].map(methodKey => (
                  <td key={methodKey} style={{padding: '15px', textAlign: 'center'}}>
                    {policy ? (
                      <button 
                        onClick={() => handleToggle(keyId, methodKey, policy.supreme_allowed[methodKey])}
                        style={{
                          padding: '8px 15px', 
                          background: policy.supreme_allowed[methodKey] ? 'rgba(0, 255, 136, 0.1)' : 'rgba(255, 0, 60, 0.1)',
                          color: policy.supreme_allowed[methodKey] ? 'var(--accent-green)' : 'var(--accent-red)',
                          border: `1px solid ${policy.supreme_allowed[methodKey] ? 'var(--accent-green)' : 'var(--accent-red)'}`,
                          borderRadius: '4px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold',
                          transition: 'all 0.2s', width: '100px'
                        }}
                      >
                        {policy.supreme_allowed[methodKey] ? 'ENFORCED' : 'REVOKED'}
                      </button>
                    ) : (
                      <span style={{color: 'var(--text-muted)', fontSize: '0.8rem'}}>- IMMUNE -</span>
                    )}
                  </td>
                ))}

                <td style={{padding: '15px', textAlign: 'center'}}>
                  {policy ? (
                    <select 
                      value={policy.mfa_mode || 'free'} 
                      onChange={(e) => handleMfaMode(keyId, e.target.value)}
                      style={{
                        padding: '8px', background: 'var(--panel-bg)', color: 'var(--text-main)',
                        border: '1px solid var(--table-border)', borderRadius: '4px', cursor: 'pointer',
                        fontFamily: 'monospace'
                      }}
                    >
                      <option value="free">FREE</option>
                      <option value="strict">STRICT</option>
                      <option value="random">RANDOM</option>
                    </select>
                  ) : (
                    <span style={{color: 'var(--text-muted)', fontSize: '0.8rem'}}>-</span>
                  )}
                </td>

                <td style={{padding: '15px', textAlign: 'center'}}>
                  <button 
                    onClick={() => {
                      if (isOffline) { alert('GATEKEEPER OFFLINE'); return; }
                      regenerateKey(keyId);
                    }}
                    style={{
                      padding: '8px 15px', background: 'rgba(0, 243, 255, 0.1)',
                      color: 'var(--accent-cyan)', border: '1px solid var(--accent-cyan)',
                      borderRadius: '4px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold'
                    }}
                  >
                    REFORGE
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
