import { useState, useRef, useEffect } from 'react';
import { useLanguage } from '../../contexts/LanguageContext';
import { Search, Plus, Download, MessageSquare, ChevronDown, AlertTriangle } from 'lucide-react';
import { Topbar } from '../../components/layout/Topbar';
import { NewAnalysisModal } from './NewAnalysisModal';
import { useComplianceAnalysis } from './useComplianceAnalysis';
import { usePageState } from '../../contexts';
import { HistoryRail } from './HistoryRail';
import { FindingChatDrawer } from './FindingChatDrawer';
import type { FindingEvent, SourceEvent, AnalysisMeta } from './useComplianceAnalysis';

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

function riskClass(score: number) {
  if (score >= 70) return 'high';
  if (score >= 40) return 'med';
  return 'low';
}

function highlightText(text: string, terms: string[]): React.ReactNode[] {
  if (!terms.length) return [text];
  const escaped = terms.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  const pattern = new RegExp(`(${escaped.join('|')})`, 'i');
  const patternGlobal = new RegExp(`(${escaped.join('|')})`, 'gi');
  return text.split(patternGlobal).map((part, i) =>
    pattern.test(part)
      ? <mark key={i} className="comp-highlight">{part}</mark>
      : <span key={i}>{part}</span>
  );
}

function formatTs(iso: string) {
  try {
    return new Date(iso).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  } catch { return iso; }
}

/** Wrapper that resolves findingIndex → findingId from the saved analysis, then renders FindingChatDrawer. */
function FindingChatDrawerWrapper({
  analysisId,
  findingIndex,
  finding,
  onClose,
}: {
  analysisId: string;
  findingIndex: number;
  finding: { title: string; desc: string; status: string; clause_ref?: string };
  onClose: () => void;
}) {
  const [findingId, setFindingId] = useState<string | null>(null);

  useEffect(() => {
    fetch(`/api/v1/compliance/history/${analysisId}`, {
      headers: authHeader(),
    })
      .then(r => r.json())
      .then((data: { findings?: Array<{ seq: number; id: string }> }) => {
        const f = (data.findings ?? []).find(f => f.seq === findingIndex);
        if (f?.id) setFindingId(f.id);
      })
      .catch(() => {});
  }, [analysisId, findingIndex]);

  if (!findingId) return null;
  return (
    <FindingChatDrawer
      analysisId={analysisId}
      findingId={findingId}
      finding={finding}
      onClose={onClose}
    />
  );
}

export function CompliancePage() {
  const [showModal, setShowModal] = useState(false);
  const [showExportMenu, setShowExportMenu] = useState(false);
  const { state, run, reset } = useComplianceAnalysis();
  // drawerFinding holds {index, finding} for the currently-open FindingChatDrawer
  const [drawerFinding, setDrawerFinding] = useState<{ idx: number; finding: FindingEvent } | null>(null);

  const { setComplianceState } = usePageState();
  const { t } = useLanguage();
  const STATUS_LABEL: Record<string, string> = { ok: t.compliance.statusCovered, warn: t.compliance.statusGap, risk: t.compliance.statusCritical, info: t.compliance.statusInfo };
  const SOURCE_TYPE_LABEL: Record<string, string> = { text: t.compliance.sourceTypePasted, doc: t.compliance.sourceTypeIndexed, upload: t.compliance.sourceTypeUploaded };

  const [historyRefresh, setHistoryRefresh] = useState(0);
  const prevAnalysisIdRef = useRef<string | null>(null);

  useEffect(() => {
    if (state.analysisId && state.analysisId !== prevAnalysisIdRef.current) {
      prevAnalysisIdRef.current = state.analysisId;
      setHistoryRefresh(n => n + 1);
    }
  }, [state.analysisId]);

  async function handleSelectHistory(id: string) {
    const res = await fetch(`/api/v1/compliance/history/${id}`, { headers: authHeader() });
    if (!res.ok) return;
    const data = await res.json();
    setComplianceState({
      status: 'done',
      stageLabel: 'Complete',
      stageKey: 'concluding',
      meta: { title: data.doc_name, sourceType: 'doc', startedAt: data.created_at },
      sources: [],
      findings: (data.findings || []).map((f: Record<string, unknown>) => ({
        title: String(f.title ?? ''),
        desc: String(f.description ?? ''),
        status: String(f.status ?? 'ok'),
        clause_ref: f.clause_ref ? String(f.clause_ref) : undefined,
      })),
      done: {
        conclusion: String(data.conclusion ?? ''),
        actions: data.actions ?? [],
        risk_score: Number(data.risk_score ?? 0),
        highlight_terms: data.highlight_terms ?? [],
        para_text: String(data.para_text ?? ''),
      },
      errorText: '',
      analysisId: data.id,
      isReadOnly: true,
      activeFindingId: null,
      progress: null,
      conflicts: [],
    });
  }

  const isIdle = state.status === 'idle';
  const isStreaming = state.status === 'streaming';
  const isDone = state.status === 'done';
  const isError = state.status === 'error';

  // ── Export helpers ────────────────────────────────────────────────────────
  function exportJSON() {
    const data = {
      title: state.meta?.title,
      sourceType: state.meta?.sourceType,
      startedAt: state.meta?.startedAt,
      sources: state.sources,
      findings: state.findings,
      conclusion: state.done?.conclusion,
      actions: state.done?.actions,
      risk_score: state.done?.risk_score,
      highlight_terms: state.done?.highlight_terms,
      para_text: state.done?.para_text,
    };
    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 = `compliance-report-${Date.now()}.json`; a.click();
    URL.revokeObjectURL(url);
    setShowExportMenu(false);
  }

  function exportText() {
    const lines: string[] = [
      t.compliance.exportReportHeader,
      `Title: ${state.meta?.title ?? 'Untitled'}`,
      `Date: ${state.meta?.startedAt ? formatTs(state.meta.startedAt) : ''}`,
      `Source: ${SOURCE_TYPE_LABEL[state.meta?.sourceType ?? 'text']}`,
      `Risk Score: ${state.done?.risk_score ?? 'N/A'} / 100`,
      '',
      t.compliance.exportSectionParagraph,
      state.done?.para_text ?? '',
      '',
      t.compliance.exportSectionFindings,
      ...state.findings.map((f, i) =>
        `[${i + 1}] [${f.status.toUpperCase()}] ${f.title}\n    ${f.desc}${f.clause_ref ? `\n    Ref: ${f.clause_ref}` : ''}`
      ),
      '',
      t.compliance.exportSectionConclusion,
      state.done?.conclusion ?? '',
      '',
      t.compliance.exportSectionActions,
      ...(state.done?.actions ?? []).map(a => `• ${a.label}: ${a.value}`),
    ];
    const blob = new Blob([lines.join('\n')], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    a.download = `compliance-report-${Date.now()}.txt`; a.click();
    URL.revokeObjectURL(url);
    setShowExportMenu(false);
  }

  return (
    <div className="compliance-page" style={{ position: 'relative' }}>
      <Topbar
        title={t.compliance.topbarTitle}
        actions={
          <>
            <div className="search-box">
              <Search size={13} />
              <input placeholder={t.compliance.searchPlaceholder} />
            </div>
            {isStreaming || isDone || isError ? (
              <button className="btn sm" onClick={reset}>{t.compliance.clearBtn}</button>
            ) : null}
            {isDone && (
              <div style={{ position: 'relative' }}>
                <button
                  className="btn sm"
                  onClick={() => setShowExportMenu(v => !v)}
                >
                  <Download size={13} />{t.compliance.exportBtn}<ChevronDown size={11} />
                </button>
                {showExportMenu && (
                  <div style={{
                    position: 'absolute', right: 0, top: '100%', marginTop: 4,
                    background: 'var(--surface)', border: '1px solid var(--border)',
                    borderRadius: 8, boxShadow: '0 6px 20px rgba(0,0,0,.15)',
                    zIndex: 50, minWidth: 140, overflow: 'hidden',
                  }}>
                    <button onClick={exportJSON} style={{ display: 'block', width: '100%', padding: '9px 14px', textAlign: 'left', fontSize: 13, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg)' }}
                      onMouseEnter={e => (e.currentTarget.style.background = 'var(--bg)')}
                      onMouseLeave={e => (e.currentTarget.style.background = 'none')}
                    >{t.compliance.exportJSON}</button>
                    <button onClick={exportText} style={{ display: 'block', width: '100%', padding: '9px 14px', textAlign: 'left', fontSize: 13, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg)' }}
                      onMouseEnter={e => (e.currentTarget.style.background = 'var(--bg)')}
                      onMouseLeave={e => (e.currentTarget.style.background = 'none')}
                    >{t.compliance.exportText}</button>
                  </div>
                )}
              </div>
            )}
            <button className="btn sm primary" onClick={() => setShowModal(true)}>
              <Plus size={13} />{t.compliance.newAnalysisBtn}
            </button>
          </>
        }
      />

      {showModal && (
        <NewAnalysisModal
          onClose={() => setShowModal(false)}
          onSubmit={(fd, meta) => run(fd, meta)}
        />
      )}

      {/* Status bar */}
      {(isStreaming || isDone || isError) && (
        <div style={{ padding: '0 24px' }}>
          <div className={`compliance-status-bar ${state.status}`}>
            <div className="status-dot" />
            <span className="status-bar-label">
              {isStreaming ? t.compliance.statusAnalyzing : isDone ? t.compliance.statusComplete : t.compliance.statusError}
            </span>
            <span className="status-bar-sub">{state.stageLabel}</span>
          </div>
        </div>
      )}

      {/* Empty state */}
      {isIdle && (
        <div className="analysis-empty">
          <div className="analysis-empty-icon"><Plus size={24} /></div>
          <h3>{t.compliance.emptyTitle}</h3>
          <p>{t.compliance.emptyDesc}</p>
        </div>
      )}

      {/* Workspace */}
      {!isIdle && (
        <>
          {/* Analysis Header */}
          {state.meta && (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '10px 24px', borderBottom: '1px solid var(--border)',
              fontSize: 13,
            }}>
              <span style={{ fontWeight: 600, color: 'var(--fg)' }}>{state.meta.title}</span>
              <span style={{ color: 'var(--muted)', fontSize: 11 }}>·</span>
              <span style={{ color: 'var(--muted)', fontSize: 11 }}>{SOURCE_TYPE_LABEL[state.meta.sourceType]}</span>
              <span style={{ color: 'var(--muted)', fontSize: 11 }}>·</span>
              <span style={{ color: 'var(--muted)', fontSize: 11 }}>{formatTs(state.meta.startedAt)}</span>
              {isDone && state.done && (
                <>
                  <span style={{ color: 'var(--muted)', fontSize: 11 }}>·</span>
                  <span className={`risk-score-badge ${riskClass(state.done.risk_score)}`}
                    style={{ width: 28, height: 28, fontSize: 11 }}
                    title="Risk score">
                    {state.done.risk_score}
                  </span>
                </>
              )}
            </div>
          )}

          <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
            <HistoryRail
              refreshTrigger={historyRefresh}
              onSelect={handleSelectHistory}
              selectedId={state.analysisId}
            />
            <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
              <div className="compliance-workspace" style={{ position: 'relative' }}>

            {/* Column 1: Retrieved Regulations */}
            <div className="comp-col source-col">
              <div className="col-header">
                {t.compliance.stageRetrieval} {state.sources.length > 0 && `(${state.sources.length})`}
              </div>
              {state.sources.length === 0 && isStreaming && (
                <div style={{ padding: '20px 16px', color: 'var(--muted)', fontSize: 12 }}>
                  {t.compliance.retrievingMsg}
                </div>
              )}
              {state.sources.map((s: SourceEvent, i: number) => (
                <div key={i} className="source-item card">
                  <div className="source-top">
                    <span className="source-std">{s.standard || t.compliance.defaultRegulation}</span>
                    <span className={`status ${s.status === 'retrieved' ? 'ok' : s.status}`}>
                      {STATUS_LABEL[s.status] ?? 'Retrieved'}
                    </span>
                  </div>
                  {s.clause && <div className="source-helper">{s.clause}</div>}
                  {s.score > 0 && (
                    <div className="source-scores">
                      <span className="score-pill">
                        {s.score <= 1 ? Math.round(s.score * 100) : Math.round(s.score)}{t.compliance.matchSuffix}
                      </span>
                    </div>
                  )}
                  {s.full_content && (
                    <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 6, lineHeight: 1.5 }}>
                      {s.full_content.slice(0, 120)}…
                    </div>
                  )}
                </div>
              ))}
            </div>

            {/* Column 2: Paragraph Under Review + Stages */}
            <div className="comp-col review-col">
              <div className="col-header">{t.compliance.colParagraph}</div>

              <div className="card para-card">
                {isDone && state.done?.para_text ? (
                  <p className="para-text">
                    {highlightText(state.done.para_text, state.done.highlight_terms ?? [])}
                  </p>
                ) : (
                  <p className="para-text" style={{ color: 'var(--muted)' }}>
                    {isStreaming ? t.compliance.extractingMsg : t.compliance.noTextExtracted}
                  </p>
                )}
              </div>

              <div className="card stages-card">
                <div className="card-header">{t.compliance.stagesHeader}</div>
                {(() => {
                  const STAGE_KEYS = ['extracting', 'splitting', 'analyzing', 'concluding'];
                  const STAGE_LABELS = [t.compliance.stageExtraction, t.compliance.stageClauseSplit, t.compliance.stageRetrieval, t.compliance.stageSynthesis];
                  const curIdx = STAGE_KEYS.indexOf(state.stageKey);
                  return STAGE_KEYS.map((key, idx) => {
                    const pct = isDone ? 100 : idx < curIdx ? 100 : idx === curIdx ? 60 : 0;
                    const stStatus = pct === 100 ? 'ok' : pct > 0 ? 'running' : 'info';
                    return (
                      <div key={key} className={`stage-row${stStatus === 'running' ? ' stage-running' : ''}`}>
                        <div className="stage-label-row">
                          <span className="stage-label">{STAGE_LABELS[idx]}</span>
                          <span className="stage-pct">{pct}%</span>
                        </div>
                        <div className="stage-bar">
                          <div className={`stage-fill stage-${stStatus}`} style={{ width: `${pct}%` }} />
                        </div>
                      </div>
                    );
                  });
                })()}
              </div>
            </div>

            {/* Column 3: Findings + Conclusion */}
            <div className="comp-col findings-col">
              <div className="col-header">
                Findings {state.findings.length > 0 && `(${state.findings.length})`}
                {/* Real per-clause progress bar during streaming */}
                {isStreaming && state.progress && state.progress.total > 0 && (
                  <span style={{
                    marginLeft: 8, fontSize: 10, color: 'var(--muted)',
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                  }}>
                    <span style={{
                      display: 'inline-block', width: 60, height: 4,
                      background: 'var(--border)', borderRadius: 2, overflow: 'hidden',
                    }}>
                      <span style={{
                        display: 'block', height: '100%',
                        width: `${Math.round((state.progress.done / state.progress.total) * 100)}%`,
                        background: 'var(--accent)', transition: 'width 0.3s ease',
                      }} />
                    </span>
                    {state.progress.done}/{state.progress.total}
                  </span>
                )}
              </div>

              {state.findings.length === 0 && isStreaming && (
                <div style={{ padding: '20px 16px', color: 'var(--muted)', fontSize: 12 }}>
                  {t.compliance.gapInProgress}
                </div>
              )}

              {state.findings.map((f: FindingEvent, i: number) => (
                <div key={i} className="finding-item card">
                  <div className="finding-top">
                    <span className="finding-title">{f.title}</span>
                    <span className={`status ${f.status}`}>{STATUS_LABEL[f.status] ?? f.status}</span>
                  </div>
                  <p className="finding-desc">{f.desc}</p>

                  {/* Source refs: which retrieved chunks informed this finding */}
                  {f.source_refs && f.source_refs.length > 0 && (
                    <div style={{ marginTop: 4, display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                      {f.source_refs.map((sr, si) => (
                        <span key={si} style={{
                          fontSize: 10, padding: '1px 6px',
                          background: 'var(--bg)', border: '1px solid var(--border)',
                          borderRadius: 4, color: 'var(--muted)',
                        }} title={sr.clause}>
                          📄 {sr.standard ? sr.standard.slice(0, 20) : '—'}
                          {sr.score > 0 && ` · ${Math.round(sr.score * 100)}%`}
                        </span>
                      ))}
                    </div>
                  )}

                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      {f.clause_ref && (
                        <div style={{ fontSize: 11, color: 'var(--muted)' }}>Ref: {f.clause_ref}</div>
                      )}
                      {/* Confidence dot: green ≥0.7, amber 0.4–0.7, red <0.4 */}
                      {f.confidence !== undefined && (
                        <span
                          style={{
                            fontSize: 10, color: 'var(--muted)',
                            display: 'inline-flex', alignItems: 'center', gap: 3,
                          }}
                          title={`Retrieval confidence: ${Math.round(f.confidence * 100)}%`}
                        >
                          <span style={{
                            width: 6, height: 6, borderRadius: '50%',
                            background: f.confidence >= 0.7 ? '#22c55e' : f.confidence >= 0.4 ? '#f59e0b' : '#ef4444',
                          }} />
                          {Math.round(f.confidence * 100)}%
                        </span>
                      )}
                    </div>
                    {/* Single consolidated chat button — only when analysis is saved */}
                    {state.analysisId ? (
                      <button
                        className="btn sm"
                        style={{ marginLeft: 'auto', fontSize: 11, padding: '3px 8px', gap: 4 }}
                        onClick={() => setDrawerFinding({ idx: i, finding: f })}
                      >
                        <MessageSquare size={11} />{t.compliance.chatBtn}
                      </button>
                    ) : (
                      /* Fallback for unsaved analyses: show disabled chat hint */
                      <span style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--muted)' }}>
                        {t.compliance.askAIBtn}
                      </span>
                    )}
                  </div>
                </div>
              ))}

              {/* Cross-clause conflicts panel */}
              {state.conflicts && state.conflicts.length > 0 && (
                <div className="card" style={{ borderLeft: '3px solid #f59e0b', marginTop: 8 }}>
                  <div className="card-header" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <AlertTriangle size={12} color="#f59e0b" />
                    <span style={{ fontSize: 12, fontWeight: 600 }}>Cross-Clause Issues ({state.conflicts.length})</span>
                  </div>
                  {state.conflicts.map((c, ci) => (
                    <div key={ci} style={{ fontSize: 11, color: 'var(--muted)', padding: '4px 0', borderTop: ci ? '1px solid var(--border)' : 'none' }}>
                      <span style={{
                        fontWeight: 600,
                        color: c.type === 'contradiction' ? '#ef4444' : c.type === 'cumulative_risk' ? '#f59e0b' : 'var(--fg)',
                      }}>
                        [{c.type.replace('_', ' ')}]
                      </span>
                      {' '}Finding #{c.finding_a}{c.finding_b ? ` ↔ #${c.finding_b}` : ''}: {c.desc}
                    </div>
                  ))}
                </div>
              )}

              {/* Conclusion */}
              {isDone && state.done && (
                <div className="card conclusion-box">
                  <div className="card-header" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span>{t.compliance.conclusionHeader}</span>
                    <div
                      className={`risk-score-badge ${riskClass(state.done.risk_score)}`}
                      title={t.compliance.riskScoreTooltip}
                    >
                      {state.done.risk_score}
                    </div>
                  </div>
                  <div className="risk-meter">
                    <span style={{ fontSize: 11, color: 'var(--muted)', width: 24 }}>0</span>
                    <div className="risk-bar-track">
                      <div className="risk-bar-fill" style={{ width: `${state.done.risk_score}%` }} />
                    </div>
                    <span style={{ fontSize: 11, color: 'var(--muted)', width: 24, textAlign: 'right' }}>100</span>
                  </div>
                  <p className="conclusion-text">{state.done.conclusion}</p>
                  <div className="action-items">
                    {state.done.actions.map((a, i) => (
                      <div key={i} className="action-item">
                        <span className="action-label">{a.label}</span>
                        <span className={`action-value${a.risk ? ' risk-text' : ''}`}>{a.value}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {isError && (
                <div className="card" style={{ borderColor: 'var(--danger)', padding: '14px 16px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: 'var(--danger)', fontSize: 13, fontWeight: 600 }}>
                    <AlertTriangle size={14} /> {t.compliance.analysisFailed}
                  </div>
                  <p style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>{state.errorText}</p>
                </div>
              )}
            </div>
            </div>
            </div>
          </div>

          {/* ── Finding Chat Drawer (single consolidated UI) ───────────── */}
          {drawerFinding !== null && state.analysisId && (
            <FindingChatDrawerWrapper
              analysisId={state.analysisId}
              findingIndex={drawerFinding.idx}
              finding={{
                title: drawerFinding.finding.title,
                desc: drawerFinding.finding.desc,
                status: drawerFinding.finding.status,
                clause_ref: drawerFinding.finding.clause_ref,
              }}
              onClose={() => setDrawerFinding(null)}
            />
          )}
        </>
      )}
    </div>
  );
}
