import { getPinnedInsights } from '@/lib/evolution/history.pins';
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';

/** تصدير جميع الـ pins كـ CSV string */
export function exportPinnedAsCSV(): string {
  const pins = getPinnedInsights();
  if (!pins.length) return '';

  const header = ['Timestamp', 'Trend', 'Confidence', 'Note'];
  const rows = pins.map((p) => [
    p.timestamp,
    p.trend,
    (p.confidence * 100).toFixed(1) + '%',
    p.note,
  ]);
  return [header, ...rows].map((r) => r.join(',')).join('\n');
}

/** تنزيل CSV كملف */
export function downloadCSV() {
  const csv = exportPinnedAsCSV();
  if (!csv) {
    alert('No pinned insights to export.');
    return;
  }
  const blob = new Blob([csv], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `insights_${new Date().toISOString().slice(0, 10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

/** تنزيل تقرير PDF بهوية HUD */
export function downloadPDF() {
  const pins = getPinnedInsights();
  if (!pins.length) {
    alert('No pinned insights to export.');
    return;
  }

  const doc = new jsPDF({
    orientation: 'portrait',
    unit: 'pt',
    format: 'A4',
  });

  // 🎨 Header
  doc.setFont('helvetica', 'bold');
  doc.setFontSize(18);
  doc.setTextColor('#f47b46');
  doc.text('Jemy-dev OS — Annotated Insights Report', 40, 50);

  // 🕓 Subheader
  doc.setFontSize(10);
  doc.setTextColor('#9aa1b1');
  doc.text(`Generated: ${new Date().toLocaleString()}`, 40, 70);

  // 🧾 Data Table
  const tableData = pins.map((p, i) => [
    i + 1,
    new Date(p.timestamp).toLocaleString(),
    p.trend,
    (p.confidence * 100).toFixed(1) + '%',
    p.note || '-',
  ]);

  autoTable(doc, {
    startY: 90,
    head: [['#', 'Timestamp', 'Trend', 'Confidence', 'Note']],
    body: tableData,
    theme: 'grid',
    styles: {
      font: 'helvetica',
      fontSize: 9,
      textColor: '#e1e5f2',
      lineColor: [60, 60, 60],
      fillColor: [20, 25, 40],
      cellPadding: 5,
    },
    headStyles: {
      fillColor: [15, 60, 80],
      textColor: '#ffffff',
      fontStyle: 'bold',
    },
    alternateRowStyles: {
      fillColor: [25, 30, 50],
    },
    tableLineColor: [80, 80, 80],
    tableLineWidth: 0.3,
  });

  // ⚙️ Footer
  const pageCount = doc.getNumberOfPages();
  for (let i = 1; i <= pageCount; i++) {
    doc.setPage(i);
    doc.setFontSize(8);
    doc.setTextColor('#666');
    doc.text(`© ${new Date().getFullYear()} Jemy-dev OS — Predictive Phase 005`, 40, 810);
    doc.text(`Page ${i} of ${pageCount}`, 500, 810);
  }

  doc.save(`Jemy-dev-Insights-${new Date().toISOString().slice(0, 10)}.pdf`);
}
