import { useState, useEffect } from 'react';
import { Topbar } from '../../components/layout/Topbar';
import { Search, Upload, Download, RefreshCw, CheckCircle, XCircle, AlertTriangle, Info } from 'lucide-react';
import { UploadModal } from '../Docs/UploadModal';
import { useLanguage } from '../../contexts/LanguageContext';
import { getModelUsage, pingModelConnections } from '../../api/status';
import type { ModelUsageEntry } from '../../api/index';

const TOKEN_KEY = 'auth_token';
function authHeader(): Record<string, string> {
  const t = localStorage.getItem(TOKEN_KEY);
  return t ? { Authorization: `Bearer ${t}` } : {};
}

// ── API types ──────────────────────────────────────────────────────────────
interface Stats {
  documents_total: number;
  documents_indexed: number;
  documents_failed: number;
  chunks_total: number;
}

interface Health {
  milvus: { status: string; connected?: boolean; collection_name?: string; num_entities?: number; error?: string };
  minio: { status: string; connected: boolean };
  bm25: { available: boolean };
  reranker: { enabled: boolean; model: string | null };
  sessions: { active: number; max: number };
}

interface Config {
  embedding_model: string;
  embedding_dim: number;
  embedding_base_url: string;
  milvus_collection: string;
  parser_backend: string;
  chunk_backend: string;
  llm_provider: string;
  llm_model: string;
  parser_failure_mode: string;
  artifact_prefix?: string;
  document_metadata_path?: string;
}

// ── Small helpers ──────────────────────────────────────────────────────────
function StatusIcon({ status }: { status: 'ok' | 'error' | 'warn' | 'info' }) {
  if (status === 'ok') return <CheckCircle size={14} color="var(--ok)" />;
  if (status === 'error') return <XCircle size={14} color="var(--danger)" />;
  if (status === 'warn') return <AlertTriangle size={14} color="var(--warn)" />;
  return <Info size={14} color="var(--muted)" />;
}

function ServiceRow({ name, status, detail }: { name: string; status: 'ok' | 'error' | 'warn' | 'info'; detail?: string }) {
  const { t } = useLanguage();
  return (
    <div className="service-row">
      <StatusIcon status={status} />
      <span className="service-name" style={{ marginLeft: 8 }}>{name}</span>
      {detail && <span style={{ fontSize: 11, color: 'var(--muted)', marginLeft: 6 }}>{detail}</span>}
      <span className={`status ${status}`} style={{ marginLeft: 'auto' }}>
        {status === 'ok' ? t.status.badgeOnline : status === 'error' ? t.status.badgeError : status === 'warn' ? t.status.badgeDegraded : t.status.badgeUnknown}
      </span>
    </div>
  );
}

function ConfigRow({ label, value }: { label: string; value: string | number | null | undefined }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: '1px solid var(--border)', fontSize: 12 }}>
      <span style={{ color: 'var(--muted)' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--fg)', fontSize: 11, maxWidth: '60%', textAlign: 'right', wordBreak: 'break-all' }}>
        {value ?? '—'}
      </span>
    </div>
  );
}

// ── Main component ─────────────────────────────────────────────────────────
export function StatusPage() {
  const { t } = useLanguage();
  const [stats, setStats] = useState<Stats | null>(null);
  const [health, setHealth] = useState<Health | null>(null);
  const [config, setConfig] = useState<Config | null>(null);
  const [loading, setLoading] = useState(true);
  const [healthLoading, setHealthLoading] = useState(true);
  const [modelsLoading, setModelsLoading] = useState(true);
  const [configOpen, setConfigOpen] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const [showUpload, setShowUpload] = useState(false);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
  const [modelUsage, setModelUsage] = useState<ModelUsageEntry[] | null>(null);
  const [pinging, setPinging] = useState(false);

  useEffect(() => {
    setLoading(true);
    setHealthLoading(true);
    setModelsLoading(true);

    // Fetch all endpoints in parallel. The first three use raw fetch() (legacy
    // pattern already established in this file); model usage uses the typed
    // fetchAPI-based client from api/status.ts — new code should prefer that.
    Promise.allSettled([
      fetch('/api/v1/status/stats', { headers: authHeader() }).then(r => r.json()),
      fetch('/api/v1/status/health', { headers: authHeader() }).then(r => r.json()),
      fetch('/api/v1/status/config', { headers: authHeader() }).then(r => r.json()),
      getModelUsage(),
    ]).then(([statsRes, healthRes, configRes, modelsRes]) => {
      if (statsRes.status === 'fulfilled') setStats(statsRes.value);
      else setStats({ documents_total: 0, documents_indexed: 0, documents_failed: 0, chunks_total: 0 });

      if (healthRes.status === 'fulfilled') setHealth(healthRes.value);
      if (configRes.status === 'fulfilled') setConfig(configRes.value);
      if (modelsRes.status === 'fulfilled') setModelUsage(modelsRes.value.models);
      else setModelUsage(null);

      setLoading(false);
      setHealthLoading(false);
      setModelsLoading(false);
      setLastRefresh(new Date());
    });
  }, [refreshKey]);

  // ── Derived values ───────────────────────────────────────────────────────
  const indexedPct = stats && stats.documents_total > 0
    ? Math.round((stats.documents_indexed / stats.documents_total) * 100)
    : 0;

  function milvusStatus(): 'ok' | 'error' | 'warn' | 'info' {
    if (!health) return 'info';
    return health.milvus.status === 'ok' ? 'ok' : 'error';
  }
  function milvusDetail() {
    if (!health) return undefined;
    if (health.milvus.error) return health.milvus.error.slice(0, 60);
    const parts: string[] = [];
    if (health.milvus.collection_name) parts.push(health.milvus.collection_name);
    if (health.milvus.num_entities !== undefined) parts.push(`${health.milvus.num_entities.toLocaleString()} entities`);
    return parts.join(' · ') || undefined;
  }

  // ── Export ───────────────────────────────────────────────────────────────
  function handleExport() {
    const data = { stats, health, config, exportedAt: new Date().toISOString() };
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `regulation-hub-status-${Date.now()}.json`; a.click();
    URL.revokeObjectURL(url);
  }

  async function handleTestConnections() {
    setPinging(true);
    try {
      const res = await pingModelConnections();
      setModelUsage(res.models);
    } catch {
      // Leave modelUsage as-is; the card below already shows a muted
      // "never_called"/error state per row when data can't be refreshed.
    } finally {
      setPinging(false);
    }
  }

  function modelBadgeStatus(status: ModelUsageEntry['status']): 'ok' | 'error' | 'warn' | 'info' {
    if (status === 'ok') return 'ok';
    if (status === 'error') return 'error';
    if (status === 'disabled') return 'info';
    return 'info'; // never_called
  }

  function modelStatusLabel(entry: ModelUsageEntry): string {
    if (entry.status === 'never_called') return t.status.modelStatusNeverCalled;
    if (entry.status === 'disabled') return t.status.modelStatusDisabled;
    return entry.status === 'ok' ? t.status.badgeOnline : t.status.badgeError;
  }

  /** Small relative-ish hint shown next to provider/model — "Never" or a local time string. */
  function modelLastCalledLabel(entry: ModelUsageEntry): string {
    if (!entry.last_called_at) return t.status.lastCalledNever;
    return new Date(entry.last_called_at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
  }

  return (
    <div className="status-page">
      <Topbar
        title={t.status.topbarTitle}
        actions={
          <>
            <div className="search-box">
              <Search size={13} />
              <input placeholder={t.status.searchPlaceholder} />
            </div>
            <button className="btn sm" onClick={handleExport}>
              <Download size={13} />{t.status.exportBtn}
            </button>
            <button className="btn sm" onClick={() => setRefreshKey(k => k + 1)}>
              <RefreshCw size={13} />{t.status.refreshBtn}
            </button>
            <button className="btn sm primary" onClick={() => setShowUpload(true)}>
              <Upload size={13} />{t.status.newUploadBtn}
            </button>
          </>
        }
      />

      <div className="page-content">

        {/* ── Stats grid ────────────────────────────────────────────────── */}
        <div className="stats-grid">
          <div className="stat-cell">
            {loading ? <span className="loading-shimmer stat-value-loading" /> : <div className="stat-value">{stats?.documents_total ?? '—'}</div>}
            <div className="stat-label">{t.status.statTotal}</div>
          </div>
          <div className="stat-cell">
            {loading ? <span className="loading-shimmer stat-value-loading" /> : <div className="stat-value">{stats?.documents_indexed ?? '—'}</div>}
            <div className="stat-label">{t.status.statIndexed}</div>
          </div>
          <div className="stat-cell danger">
            {loading ? <span className="loading-shimmer stat-value-loading" /> : <div className="stat-value">{stats?.documents_failed ?? '—'}</div>}
            <div className="stat-label">{t.status.statFailed}</div>
          </div>
          <div className="stat-cell">
            {loading ? <span className="loading-shimmer stat-value-loading" /> : <div className="stat-value">{stats?.chunks_total?.toLocaleString() ?? '—'}</div>}
            <div className="stat-label">{t.status.statChunks}</div>
          </div>
        </div>

        {/* Indexed progress bar */}
        {!loading && stats && stats.documents_total > 0 && (
          <div style={{ padding: '0 0 20px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ fontSize: 12, color: 'var(--muted)', whiteSpace: 'nowrap' }}>{t.status.statCoverage}</span>
            <div style={{ flex: 1, height: 6, background: 'var(--border)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{
                height: '100%', borderRadius: 3,
                width: `${indexedPct}%`,
                background: indexedPct === 100 ? 'var(--ok)' : indexedPct > 60 ? 'var(--accent)' : 'var(--warn)',
                transition: 'width 0.6s ease',
              }} />
            </div>
            <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--fg)', whiteSpace: 'nowrap' }}>
              {indexedPct}% ({stats.documents_indexed}/{stats.documents_total})
            </span>
          </div>
        )}

        {/* ── Main panel grid ───────────────────────────────────────────── */}
        <div className="panel-grid">
          <div className="panel-left">

            {/* System health */}
            <div className="card">
              <div className="card-header" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>{t.status.cardHealth}</span>
                {lastRefresh && (
                  <span style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 400 }}>
                    Updated {lastRefresh.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                  </span>
                )}
              </div>

              {healthLoading ? (
                <div style={{ padding: '12px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {[1, 2, 3, 4, 5].map(i => (
                    <div key={i} className="loading-shimmer" style={{ height: 28, borderRadius: 6 }} />
                  ))}
                </div>
              ) : health ? (
                <>
                  <ServiceRow
                    name="Milvus vector store"
                    status={milvusStatus()}
                    detail={milvusDetail()}
                  />
                  <ServiceRow
                    name="MinIO object storage"
                    status={health.minio.connected ? 'ok' : 'error'}
                  />
                  <ServiceRow
                    name="BM25 keyword retriever"
                    status={health.bm25.available ? 'ok' : 'warn'}
                    detail={health.bm25.available ? undefined : t.status.serviceNotLoaded}
                  />
                  <ServiceRow
                    name={`Reranker${health.reranker.model ? ` (${health.reranker.model})` : ''}`}
                    status={health.reranker.enabled ? 'ok' : 'info'}
                    detail={health.reranker.enabled ? t.status.serviceEnabled : t.status.serviceDisabled}
                  />
                  <ServiceRow
                    name="Active sessions"
                    status={health.sessions.active < health.sessions.max ? 'ok' : 'warn'}
                    detail={`${health.sessions.active} / ${health.sessions.max} max`}
                  />
                </>
              ) : (
                <div style={{ padding: '12px 0', color: 'var(--muted)', fontSize: 13 }}>
                  {t.status.healthEndpointError}
                </div>
              )}
            </div>

            {/* AI Models — connection status + cumulative token usage */}
            <div className="card">
              <div className="card-header" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>{t.status.cardModels}</span>
                <button className="btn sm" onClick={handleTestConnections} disabled={pinging}>
                  {pinging ? t.status.testingBtn : t.status.testConnectionBtn}
                </button>
              </div>

              {modelsLoading ? (
                <div style={{ padding: '12px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {[1, 2, 3, 4].map(i => (
                    <div key={i} className="loading-shimmer" style={{ height: 28, borderRadius: 6 }} />
                  ))}
                </div>
              ) : modelUsage ? (
                modelUsage.map(entry => {
                  const roleLabel = entry.role === 'main_llm' ? t.status.roleMainLlm
                    : entry.role === 'hyde_llm' ? t.status.roleHydeLlm
                    : entry.role === 'embedding' ? t.status.roleEmbedding
                    : t.status.roleReranker;
                  return (
                    <div className="service-row" key={entry.role}>
                      <StatusIcon status={modelBadgeStatus(entry.status)} />
                      <span className="service-name" style={{ marginLeft: 8 }}>{roleLabel}</span>
                      <span style={{ fontSize: 11, color: 'var(--muted)', marginLeft: 6, fontFamily: 'var(--font-mono)' }}>
                        {entry.provider}/{entry.model}
                        {entry.shares_usage_with && ` · ${t.status.sharesUsageWithMain}`}
                        {` · ${modelLastCalledLabel(entry)}`}
                      </span>
                      <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg)' }}>
                        {entry.total_tokens > 0 || entry.status === 'ok' || entry.status === 'error'
                          ? entry.total_tokens.toLocaleString()
                          : '—'}
                      </span>
                      <span className={`status ${modelBadgeStatus(entry.status)}`} style={{ marginLeft: 8 }}>
                        {modelStatusLabel(entry)}
                      </span>
                    </div>
                  );
                })
              ) : (
                <div style={{ padding: '12px 0', color: 'var(--muted)', fontSize: 13 }}>{t.status.modelsLoadError}</div>
              )}
            </div>

            {/* System config (collapsible) */}
            <div className="card">
              <button
                onClick={() => setConfigOpen(v => !v)}
                style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
              >
                <div className="card-header" style={{ margin: 0, padding: 0, flex: 1, textAlign: 'left' }}>{t.status.cardConfig}</div>
                <span style={{ fontSize: 11, color: 'var(--muted)', transform: configOpen ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}>▾</span>
              </button>

              {configOpen && (
                <div style={{ marginTop: 12 }}>
                  {config ? (
                    <>
                      <ConfigRow label={t.status.labelLLMProvider} value={config.llm_provider} />
                      <ConfigRow label={t.status.labelLLMModel} value={config.llm_model} />
                      <ConfigRow label={t.status.labelEmbeddingModel} value={config.embedding_model} />
                      <ConfigRow label={t.status.labelEmbeddingDim} value={config.embedding_dim} />
                      <ConfigRow label={t.status.labelMilvusCollection} value={config.milvus_collection} />
                      <ConfigRow label={t.status.labelParserBackend} value={config.parser_backend} />
                      <ConfigRow label={t.status.labelChunkBackend} value={config.chunk_backend} />
                      <ConfigRow label={t.status.labelParserFailureMode} value={config.parser_failure_mode} />
                    </>
                  ) : (
                    <div style={{ color: 'var(--muted)', fontSize: 13 }}>{t.status.configLoadError}</div>
                  )}
                </div>
              )}
            </div>
          </div>

          <div className="panel-right">

            {/* Document breakdown */}
            <div className="card">
              <div className="card-header">{t.status.cardBreakdown}</div>
              {loading ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {[1, 2, 3].map(i => <div key={i} className="loading-shimmer" style={{ height: 24, borderRadius: 4 }} />)}
                </div>
              ) : stats ? (
                <>
                  {[
                    { label: t.status.breakdownIndexed, value: stats.documents_indexed, total: stats.documents_total, color: 'var(--ok)' },
                    { label: t.status.breakdownProcessing, value: stats.documents_total - stats.documents_indexed - stats.documents_failed, total: stats.documents_total, color: 'var(--warn)' },
                    { label: t.status.breakdownFailed, value: stats.documents_failed, total: stats.documents_total, color: 'var(--danger)' },
                  ].map(row => {
                    const pct = stats.documents_total > 0 ? Math.round((Math.max(0, row.value) / stats.documents_total) * 100) : 0;
                    return (
                      <div key={row.label} style={{ marginBottom: 10 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                          <span style={{ color: 'var(--muted)' }}>{row.label}</span>
                          <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--fg)' }}>{Math.max(0, row.value)} ({pct}%)</span>
                        </div>
                        <div style={{ height: 5, background: 'var(--border)', borderRadius: 2, overflow: 'hidden' }}>
                          <div style={{ height: '100%', width: `${pct}%`, background: row.color, borderRadius: 2, transition: 'width 0.5s' }} />
                        </div>
                      </div>
                    );
                  })}
                  <div style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                    <span style={{ color: 'var(--muted)' }}>{t.status.totalChunks}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{stats.chunks_total.toLocaleString()}</span>
                  </div>
                </>
              ) : null}
            </div>

            {/* Sessions & reranker quick facts */}
            {health && (
              <div className="card">
                <div className="card-header">{t.status.cardRuntime}</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0' }}>
                    <span style={{ color: 'var(--muted)' }}>{t.status.labelActiveSessions}</span>
                    <span style={{ fontFamily: 'var(--font-mono)' }}>{health.sessions.active}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0' }}>
                    <span style={{ color: 'var(--muted)' }}>{t.status.labelSessionCapacity}</span>
                    <span style={{ fontFamily: 'var(--font-mono)' }}>{health.sessions.max}</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0' }}>
                    <span style={{ color: 'var(--muted)' }}>{t.status.labelBM25}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', color: health.bm25.available ? 'var(--ok)' : 'var(--muted)' }}>
                      {health.bm25.available ? t.status.statusActive : t.status.statusUnavailable}
                    </span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      <footer className="page-footer">
        <div className="live-dot" />
        <span>Regulation Hub · T-Systems AI · {health ? (health.milvus.status === 'ok' && health.minio.connected ? t.status.footerAllOk : t.status.footerDegraded) : t.status.footerChecking}</span>
      </footer>

      {showUpload && <UploadModal onClose={() => setShowUpload(false)} />}
    </div>
  );
}
