// frontend/src/pages/Compliance/HistoryRail.tsx
import { useEffect, useState, useCallback } from 'react';
import { Download, Trash2 } from 'lucide-react';
import { useLanguage } from '../../contexts/LanguageContext';

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

interface HistoryItem {
  id: string;
  created_at: string;
  doc_name: string;
  standard_name: string;
  risk_score: number;
  finding_count: number;
}

interface Props {
  refreshTrigger: number;
  onSelect: (id: string) => void;
  selectedId: string | null;
}

function riskClass(score: number): string {
  if (score >= 70) return 'risk-high';
  if (score >= 40) return 'risk-medium';
  return 'risk-low';
}

export function HistoryRail({ refreshTrigger, onSelect, selectedId }: Props) {
  const [items, setItems] = useState<HistoryItem[]>([]);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const { t } = useLanguage();

  const fetchHistory = useCallback(() => {
    fetch('/api/v1/compliance/history?limit=30', { headers: authHeader() })
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) setItems(data);
      })
      .catch(() => {/* backend may not have postgres configured */});
  }, []);

  useEffect(() => { fetchHistory(); }, [fetchHistory, refreshTrigger]);

  function handleDownload(e: React.MouseEvent, item: HistoryItem) {
    e.stopPropagation();
    fetch(`/api/v1/compliance/history/${item.id}/download`, { headers: authHeader() })
      .then(r => r.blob())
      .then(blob => {
        const blobUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = `compliance-${item.doc_name.slice(0, 30)}.docx`;
        link.click();
        URL.revokeObjectURL(blobUrl);
      });
  }

  function handleDelete(e: React.MouseEvent, item: HistoryItem) {
    e.stopPropagation();
    if (!window.confirm(t.compliance.historyDeleteConfirm)) return;
    setDeletingId(item.id);
    fetch(`/api/v1/compliance/history/${item.id}`, {
      method: 'DELETE',
      headers: authHeader(),
    })
      .then(() => {
        setItems(prev => prev.filter(i => i.id !== item.id));
        setDeletingId(null);
      })
      .catch(() => setDeletingId(null));
  }

  function formatDate(iso: string): string {
    try {
      return new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
    } catch {
      return iso.slice(0, 10);
    }
  }

  if (items.length === 0) {
    return (
      <div className="history-pane" style={{ minWidth: 200, maxWidth: 220 }}>
        <div className="history-header">{t.compliance.historyHeader}</div>
        <p style={{ padding: '12px 16px', fontSize: 12, color: 'var(--muted)', lineHeight: 1.5 }}>
          {t.compliance.historyEmpty}
        </p>
      </div>
    );
  }

  return (
    <div className="history-pane" style={{ minWidth: 200, maxWidth: 220, overflowY: 'auto' }}>
      <div className="history-header">{t.compliance.historyHeader}</div>
      {items.map(item => (
        <div
          key={item.id}
          className={`quick-item${selectedId === item.id ? ' active' : ''}`}
          onClick={() => onSelect(item.id)}
          style={{ cursor: 'pointer' }}
        >
          <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 2 }}>
            {formatDate(item.created_at)}
          </div>
          <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.doc_name || 'Untitled'}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span className={`risk-badge ${riskClass(item.risk_score)}`} style={{ fontSize: 10 }}>
              {item.risk_score}
            </span>
            <span style={{ fontSize: 10, color: 'var(--muted)', flex: 1 }}>
              {item.finding_count} finding{item.finding_count !== 1 ? 's' : ''}
            </span>
            <button
              className="btn icon-btn"
              title={t.compliance.downloadReport}
              onClick={e => handleDownload(e, item)}
              style={{ padding: '2px 4px' }}
            >
              <Download size={11} />
            </button>
            <button
              className="btn icon-btn danger"
              title="Delete"
              disabled={deletingId === item.id}
              onClick={e => handleDelete(e, item)}
              style={{ padding: '2px 4px' }}
            >
              <Trash2 size={11} />
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
