// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { createContext, useContext, useState, useEffect, useRef } from 'react';

const IamPolicyContext = createContext();

export function IamPolicyProvider({ children }) {
  const [policies, setPolicies] = useState({});
  const [identities, setIdentities] = useState({});
  const [newKeyData, setNewKeyData] = useState(null);
  const wsRef = useRef(null);

  useEffect(() => {
    const connect = () => {
      const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
      const ws = new WebSocket(gatekeeperUrl);
      wsRef.current = ws;

      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'SYNC_IAM_POLICY') {
            setPolicies(data.payload.policies || {});
            setIdentities(data.payload.identities || {});
          } else if (data.type === 'NEW_KEYCARD_GENERATED') {
            setNewKeyData(data.payload);
          }
        } catch (e) {}
      };

      ws.onclose = () => setTimeout(connect, 3000);
    };
    
    connect();

    return () => {
      if (wsRef.current && wsRef.current.readyState === 1) {
        wsRef.current.close();
      }
    };
  }, []);

  const updatePolicy = (keyId, supreme_allowed, tenant_enabled) => {
    if (wsRef.current && wsRef.current.readyState === 1) {
      wsRef.current.send(JSON.stringify({
        type: 'UPDATE_IAM_POLICY',
        payload: { keyId, supreme_allowed, tenant_enabled }
      }));
    }
  };

  const regenerateKey = (oldKeyId) => {
    if (wsRef.current && wsRef.current.readyState === 1) {
      wsRef.current.send(JSON.stringify({
        type: 'REGENERATE_AEGIS_KEY',
        payload: { oldKeyId }
      }));
    }
  };

  const handleDownload = () => {
    if (!newKeyData) return;
    const { newKeyString, role } = newKeyData;
    const blob = new Blob([newKeyString], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = role === 'supreme_admin' ? 'supreme_new.xcu' : 'tenant_new.xcu';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    setNewKeyData(null);
  };

  return (
    <IamPolicyContext.Provider value={{ policies, identities, updatePolicy, regenerateKey }}>
      {children}
      {newKeyData && (
        <div style={{
          position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', 
          background: 'rgba(0,0,0,0.8)', 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-cyan)'}}>
            <h1 style={{color: 'var(--accent-cyan)', marginBottom: '20px'}}>ðŸ›¡ï¸ KEYCARD BERHASIL DITEMPA</h1>
            <p style={{color: 'var(--text-main)', marginBottom: '10px'}}>Kunci lama telah resmi dihancurkan (Revoked). Kunci baru telah disinkronisasi ke seluruh jaringan XCU.</p>
            <p style={{color: 'var(--accent-red)', marginBottom: '30px', fontSize: '0.85rem'}}>PERINGATAN: Kunci baru ini hanya akan diunduh satu kali. Simpan baik-baik berkas .xcu yang akan Anda unduh.</p>
            
            <button 
              onClick={handleDownload}
              style={{
                padding: '15px 30px', background: 'var(--accent-cyan)', color: '#000', border: 'none',
                borderRadius: '8px', fontSize: '1.2rem', fontWeight: 'bold', cursor: 'pointer',
                boxShadow: '0 0 20px rgba(0, 243, 255, 0.5)'
              }}
            >
              ðŸ“¥ UNDUH BERKAS .XCU
            </button>
          </div>
        </div>
      )}
    </IamPolicyContext.Provider>
  );
}

export function useIamPolicy() {
  return useContext(IamPolicyContext);
}
