// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { useState, useEffect, useRef } from 'react';
import { useAuth } from '../context/AuthContext';
import { useIam } from '../context/IamContext';
import { useI18n } from '../context/I18nContext';
import TenantBillingStats from '../components/TenantBillingStats';
import NotificationMatrix from '../components/NotificationMatrix';
import UniversalTopbar from '../components/UniversalTopbar';
import { useModuleRegistry } from '../context/ModuleRegistryContext';
import { useCommercial } from '../context/CommercialContext';
import { IamPolicyProvider } from '../context/IamPolicyContext';
import SecurityEnclave from '../components/SecurityEnclave';
import CreatorsMark from '../components/CreatorsMark';
import ShapeshiftingRouter from '../components/ShapeshiftingRouter';
import TenantModuleMatrix from '../components/TenantModuleMatrix';

// Spectacular Kinetic Terminal Component
function KineticTerminal({ moduleId }) {
  const [logs, setLogs] = useState([]);
  const bottomRef = useRef(null);

  useEffect(() => {
    // Reset logs when module changes
    setLogs([`[INIT] Bootstrapping Protocol for Omni-Engine Module ${moduleId}...`]);
    
    let lineCount = 1;
    const interval = setInterval(() => {
      const operations = [
        "Handshake established with XCU Edge Node SG-1",
        "QUIC UDP Tunnel open. Latency: 4ms",
        "Synchronizing cryptographic lattice key...",
        "Bypassing TCP congestion control...",
        "Verifying Neural Sub-system... OK",
        "Packet drop rate: 0.00%",
        "Awaiting kinetic instruction...",
        "Validating telemetry hash..."
      ];
      const randomOp = operations[Math.floor(Math.random() * operations.length)];
      const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
      
      setLogs(prev => {
        const next = [...prev, `[${timestamp}] ${randomOp}`];
        if (next.length > 50) return next.slice(next.length - 50); // Keep last 50
        return next;
      });
      lineCount++;
    }, 1200);

    return () => clearInterval(interval);
  }, [moduleId]);

  useEffect(() => {
    if (bottomRef.current) bottomRef.current.scrollIntoView({ behavior: 'smooth' });
  }, [logs]);

  return (
    <div style={{
      background: '#0a0a0a', border: '1px solid #333', borderRadius: '8px', padding: '15px',
      fontFamily: 'monospace', color: '#00ff88', height: '300px', overflowY: 'auto',
      boxShadow: 'inset 0 0 20px rgba(0,0,0,0.8)', marginTop: '20px'
    }} className="custom-scrollbar">
      {logs.map((log, i) => (
        <div key={i} style={{marginBottom: '5px', fontSize: '0.8rem', opacity: i === logs.length - 1 ? 1 : 0.7}}>
          {log}
        </div>
      ))}
      <div ref={bottomRef} />
    </div>
  );
}

export default function TenantDashboard() {
  const { logout, cryptographicKey } = useAuth();
  const { identity } = useIam();
  const { t } = useI18n();
  const { tiers } = useCommercial();
  const { registry } = useModuleRegistry();
  
  const [allowedModules, setAllowedModules] = useState([]);
  const [activeTab, setActiveTab] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isRevoked, setIsRevoked] = useState(false);

  useEffect(() => {
    if (identity && identity.packages) {
      if (identity.packages.length > 0) {
        // Ekstrak nama paket menjadi daftar modul ID
        let extractedModules = new Set();
        identity.packages.forEach(pkgName => {
          const matchedTier = tiers.find(t => t.name === pkgName || t.id === pkgName);
          if (matchedTier && matchedTier.modules) {
            matchedTier.modules.forEach(m => extractedModules.add(m));
          } else {
            extractedModules.add(pkgName);
          }
        });
        
        setAllowedModules(Array.from(extractedModules));
        setActiveTab('overview');
        setIsRevoked(false);
      } else {
        setIsRevoked(true);
      }
    } else {
      setIsRevoked(true);
    }
    setIsLoading(false);
  }, [identity, tiers]);

  if (isLoading) {
    return <div style={{width: '100vw', height: '100vh', background: '#05030a', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#a855f7', fontFamily: 'monospace'}}>ABSORBING TENANT MATRIX...</div>;
  }

  if (isRevoked) {
    return (
      <div style={{width: '100vw', height: '100vh', background: '#1a0000', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: '#ff003c', fontFamily: 'monospace', textAlign: 'center'}}>
        <h1 style={{fontSize: '3rem', marginBottom: '20px'}}>AKSES KOMERSIAL DICABUT</h1>
        <p style={{fontSize: '1.2rem', marginBottom: '40px', maxWidth: '600px'}}>Kunci Kriptografi Anda telah dinonaktifkan oleh Supreme Admin atau masa berlaku telah habis. Semua fungsi WebRTC QUIC dan Matriks Penagihan dikunci mati.</p>
        <button className="btn-primary" style={{background: 'transparent', border: '1px solid #ff003c', color: '#ff003c'}} onClick={logout}>
          KEMBALI KE GERBANG MASUK
        </button>
      </div>
    );
  }

  // Dynamic mapping helper
  const getModuleDetails = (modId) => {
    if (modId === 'm21') return { id: 'm21', name: 'Billing & Quota Matrix', color: '#ffea00' };
    if (modId === 'support_tickets') return { id: 'support_tickets', name: 'Supreme Support Channel', color: '#888' };
    for (let coreKey in registry) {
      const found = registry[coreKey].modules.find(m => m.id === modId);
      if (found) return { id: found.id, name: found.name, color: '#00f3ff' }; // default color for real modules
    }
    return { id: modId, name: `Unknown Module ${modId}`, color: '#ff003c' };
  };

  const activeMod = activeTab ? getModuleDetails(activeTab) : null;

  return (
    <IamPolicyProvider>
    <div className="app-container tenant-theme" style={{paddingTop: '50px'}}>
      <UniversalTopbar />
      <nav className="sidebar tenant-sidebar">
        <div className="brand" style={{color: 'var(--text-main)'}}>
          {identity.username || 'TENANT CLIENT'}
          <div style={{fontSize: '0.6rem', color: 'var(--accent-purple)', letterSpacing: '2px', marginTop: '5px'}}>COMMERCIAL GATEWAY</div>
        </div>
        
        <div 
          className={`nav-link ${activeTab === 'overview' ? 'active' : ''}`} 
          onClick={() => setActiveTab('overview')}
          style={{borderBottom: '1px solid var(--table-border)', paddingBottom: '15px', marginBottom: '15px'}}
        >
          {t('overview_matrix')}
        </div>

        <div 
          className={`nav-link ${activeTab === 'module-matrix' ? 'active' : ''}`} 
          onClick={() => setActiveTab('module-matrix')}
        >
          ⬡ Module Matrix
        </div>

        <div 
          className={`nav-link ${activeTab === 'notifications' ? 'active' : ''}`} 
          onClick={() => setActiveTab('notifications')}
        >
          Omni-Messenger Prefs
        </div>

        <div 
          className={`nav-link ${activeTab === 'security-enclave' ? 'active' : ''}`} 
          onClick={() => setActiveTab('security-enclave')}
          style={{borderBottom: '1px solid var(--table-border)', paddingBottom: '15px', marginBottom: '15px'}}
        >
          Security Enclave
        </div>

        <div 
          className={`nav-link ${activeTab === 'creators-mark' ? 'active' : ''}`} 
          onClick={() => setActiveTab('creators-mark')}
          style={{borderBottom: '1px solid var(--table-border)', paddingBottom: '15px', marginBottom: '15px', color: 'var(--accent-purple)'}}
        >
          System Genesis (About)
        </div>

        {/* Dynamic Sidebar Mapping */}
        <div className="custom-scrollbar" style={{overflowY: 'auto', flex: 1, paddingRight: '5px', marginBottom: '20px'}}>
          {allowedModules.map(modId => {
            const modInfo = getModuleDetails(modId);
            return (
              <div 
                key={modId}
                className={`nav-link ${activeTab === modId ? 'active' : ''}`} 
                onClick={() => setActiveTab(modId)}
              >
                {modInfo.name}
              </div>
            );
          })}
        </div>

        <div style={{marginTop: 'auto'}}>
          <button className="btn-primary" style={{width: '100%', background: 'transparent', border: '1px solid rgba(168, 85, 247, 0.5)', color: 'var(--accent-purple)'}} onClick={logout}>
            LOGOUT TENANT
          </button>
        </div>
      </nav>

      <main className="main-content">
        <header className="topbar">
          <h1 className="page-title" style={{color: 'var(--text-main)', textTransform: 'uppercase'}}>
            {activeTab === 'overview' ? 'CORE DASHBOARD' : activeTab === 'module-matrix' ? 'MODULE ACCESS MATRIX' : activeTab === 'notifications' ? 'OMNI-MESSENGER PREFERENCES' : activeTab === 'security-enclave' ? 'SECURITY ENCLAVE' : activeTab === 'creators-mark' ? 'SYSTEM GENESIS' : (activeMod ? activeMod.name : 'DASHBOARD')}
          </h1>
          <div className="user-profile">
            <span className="badge active" style={{background: 'rgba(168, 85, 247, 0.1)', color: 'var(--accent-purple)', borderColor: 'var(--accent-purple)'}}>
              COMMERCIAL PLAN: {(() => {
                const activeTier = tiers.find(t => 
                  t.modules.every(m => allowedModules.includes(m)) && allowedModules.length === t.modules.length
                );
                return activeTier ? activeTier.name.toUpperCase() : 'CUSTOM A LA CARTE';
              })()}
            </span>
          </div>
        </header>

        <div className="dashboard-content">
          {activeTab === 'overview' ? (
            <TenantBillingStats />
          ) : activeTab === 'module-matrix' ? (
            <TenantModuleMatrix allowedModules={allowedModules} />
          ) : activeTab === 'notifications' ? (
            <NotificationMatrix />
          ) : activeTab === 'security-enclave' ? (
            <SecurityEnclave />
          ) : activeTab === 'creators-mark' ? (
            <CreatorsMark />
          ) : activeTab === 'm21' ? (
            <TenantBillingStats />
          ) : activeTab === 'support_tickets' ? (
            <div className="glass-panel" style={{padding: '30px', textAlign: 'center'}}>
              <h2>Contact Supreme Administration</h2>
              <p style={{color: 'var(--text-muted)'}}>Ticketing portal is currently handled via encrypted channel.</p>
            </div>
          ) : (
            <div style={{animation: 'fadeIn 0.5s ease-out'}}>
              {/* Spectacular Module Orchestration Panel */}
              <div style={{display: 'flex', gap: '20px', marginBottom: '20px'}}>
                <div className="glass-panel" style={{flex: 1, padding: '20px', borderLeft: '4px solid var(--accent-green)'}}>
                  <h3 style={{color: 'var(--text-muted)', fontSize: '0.8rem', marginBottom: '10px'}}>INTEGRATION STATUS</h3>
                  <div style={{color: 'var(--accent-green)', fontSize: '1.5rem', fontWeight: 'bold', fontFamily: 'monospace'}}>ONLINE / ACTIVE</div>
                  <div style={{color: 'var(--text-muted)', fontSize: '0.8rem', marginTop: '10px'}}>Latency: 4ms | Packet Drop: 0%</div>
                </div>
                <div className="glass-panel" style={{flex: 2, padding: '20px', borderLeft: '4px solid var(--accent-purple)'}}>
                  <h3 style={{color: 'var(--text-muted)', fontSize: '0.8rem', marginBottom: '10px'}}>LIVE ENDPOINT CONNECTION</h3>
                  <div style={{
                    background: 'var(--hover-bg)', padding: '10px', borderRadius: '4px', 
                    color: 'var(--accent-purple)', fontFamily: 'monospace', fontSize: '0.9rem',
                    border: '1px solid var(--glass-border)'
                  }}>
                    wss://{window.location.hostname}:8443/v1/matrix?mod={activeTab}
                  </div>
                </div>
              </div>

              <div className="glass-panel" style={{padding: '30px', borderColor: 'var(--accent-purple)'}}>
                <p style={{color: 'var(--text-muted)'}}>
                  Anda sedang mengakses kontrol absolut untuk modul {activeTab}. Semua jalur data Anda dienkripsi berlapis 
                  menggunakan *Post-Quantum Lattice Shield*. Jangan memutuskan koneksi secara tiba-tiba.
                </p>
                
                <ShapeshiftingRouter moduleId={activeTab} />
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
    </IamPolicyProvider>
  );
}
