import React, { useEffect, useRef, useState } from 'react';
import mermaid from 'mermaid';
import { useI18n } from '../context/I18nContext';

mermaid.initialize({
  startOnLoad: false,
  theme: 'dark',
  securityLevel: 'loose',
});

export default function Documents() {
  const { t } = useI18n();
  const [docs, setDocs] = useState([]);
  const [selectedVersion, setSelectedVersion] = useState(null);
  const [loading, setLoading] = useState(true);
  const mermaidRef = useRef(null);

  useEffect(() => {
    // Fetch dynamic architecture docs from DuckDB!
    const fetchDocs = async () => {
      try {
        const res = await fetch('https://api.xc.ultramodul.xyz/v1/docs/history');
        if (res.ok) {
          const data = await res.json();
          setDocs(data);
          if (data.length > 0) setSelectedVersion(data[0]);
        } else {
            // Fallback for demonstration if endpoint is not fully up yet
            throw new Error("Endpoint not ready");
        }
      } catch (e) {
        console.error("Using local fallback due to fetch error:", e);
        // Fallback Data if DuckDB API is still compiling/deploying
        const fallbackDocs = [
            {
                version: "Ver.TSM.19:24:00.07:05:2026.F89A",
                timestamp: "2026-05-07 19:24:00",
                narrative: "Pemisahan Mutlak antara Mesin Pemrosesan Video (XCU Core) dan Mesin Penagihan API (DuckDB Billing Matrix).",
                content: "graph TD\n    A[Supreme Admin UI] -->|API Request| B(api.xc.ultramodul.xyz)\n    C[Tenant UI / JUMPA.ID] -->|API Request| B\n    B -->|Query & Save| D[(DuckDB: Billing & Iam)]\n    \n    E[XCU Core Engine\nxc.ultramodul.xyz] -->|WebRTC / QUIC Stream| F[Video Routing]\n    E -->|Send Live Usage| B\n    B -->|Validate Token| E\n    \n    classDef muscle fill:#a855f7,stroke:#fff,color:#fff;\n    classDef brain fill:#00d2ff,stroke:#fff,color:#000;\n    class E,F muscle;\n    class B,D brain;"
            }
        ];
        setDocs(fallbackDocs);
        setSelectedVersion(fallbackDocs[0]);
      } finally {
        setLoading(false);
      }
    };
    fetchDocs();
  }, []);

  useEffect(() => {
    if (selectedVersion && mermaidRef.current) {
      mermaidRef.current.innerHTML = '';
      mermaid.render(`mermaid-${selectedVersion.version.replace(/[^a-zA-Z0-9]/g, '')}`, selectedVersion.content).then(result => {
        mermaidRef.current.innerHTML = result.svg;
      }).catch(e => console.error("Mermaid render error", e));
    }
  }, [selectedVersion]);

  return (
    <div style={{ display: 'flex', gap: '20px', height: '100%', color: '#fff' }}>
      {/* Sidebar Histori */}
      <div className="glass-panel" style={{ width: '250px', padding: '15px' }}>
        <h3 style={{ color: 'var(--accent-cyan)', marginBottom: '15px' }}>{t('documents')} (History)</h3>
        {loading ? (
           <p>Syncing Vault...</p>
        ) : docs.length === 0 ? (
           <p>No architecture records found.</p>
        ) : (
          <ul style={{ listStyle: 'none', padding: 0 }}>
            {docs.map(doc => (
              <li key={doc.version} style={{ marginBottom: '10px' }}>
                <button 
                  onClick={() => setSelectedVersion(doc)}
                  style={{
                    width: '100%', textAlign: 'left', background: selectedVersion?.version === doc.version ? 'rgba(168, 85, 247, 0.3)' : 'transparent',
                    border: '1px solid #a855f7', color: '#fff', padding: '10px', borderRadius: '5px', cursor: 'pointer'
                  }}>
                  <strong>{doc.version.split('.').pop()}</strong><br/>
                  <small style={{ color: 'var(--text-muted)' }}>{doc.timestamp}</small>
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Main Canvas Mermaid */}
      <div className="glass-panel" style={{ flex: 1, padding: '20px', overflow: 'auto' }}>
        <h2 style={{ marginBottom: '10px', color: 'var(--accent-cyan)' }}>Architecture: {selectedVersion?.version}</h2>
        <p style={{ color: 'var(--text-muted)', marginBottom: '20px', lineHeight: '1.6' }}>
          {selectedVersion ? selectedVersion.narrative : ''}
        </p>
        {selectedVersion && (
          <div ref={mermaidRef} className="mermaid-container" style={{ background: '#000', padding: '20px', borderRadius: '10px', display: 'flex', justifyContent: 'center' }} />
        )}
      </div>
    </div>
  );
}
