/**
 * Export utilities for Analytics Panel
 * Handles CSV and PDF generation for dashboard data exports
 */

/**
 * Convert an array of objects to CSV and trigger download
 */
export function exportToCSV(
  data: Record<string, string | number | boolean | null | undefined>[],
  filename: string,
  headers?: Record<string, string>
): void {
  if (data.length === 0) return;

  const keys = Object.keys(headers || data[0]);
  const headerRow = keys.map((k) => headers?.[k] || k).join(",");

  const rows = data.map((row) =>
    keys
      .map((key) => {
        const val = row[key];
        if (val === null || val === undefined) return "";
        const str = String(val);
        // Escape commas and quotes in CSV
        if (str.includes(",") || str.includes('"') || str.includes("\n")) {
          return `"${str.replace(/"/g, '""')}"`;
        }
        return str;
      })
      .join(",")
  );

  const csv = [headerRow, ...rows].join("\n");
  const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8;" }); // BOM for Excel Arabic support
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `${filename}.csv`;
  link.click();
  URL.revokeObjectURL(url);
}

/**
 * Build the HTML string for the revenue PDF report
 */
function buildRevenueHTML(data: {
  title: string;
  period: string;
  currency: string;
  totalRevenue: number;
  depositsCollected: number;
  depositsPending: number;
  topServices: Array<{ service: string; count: number; revenue: number }>;
  bookingSources: Record<string, number>;
  isAr: boolean;
}): string {
  const dir = data.isAr ? "rtl" : "ltr";
  const fontFamily = data.isAr
    ? "'Segoe UI', 'Arial', sans-serif"
    : "'Segoe UI', sans-serif";

  const serviceRows = data.topServices
    .map(
      (s, i) =>
        `<tr><td>${i + 1}</td><td>${s.service}</td><td>${s.count}</td><td>${data.currency} ${s.revenue.toLocaleString()}</td></tr>`
    )
    .join("");

  return `<!DOCTYPE html>
<html dir="${dir}" lang="${data.isAr ? "ar" : "en"}">
<head>
  <meta charset="utf-8">
  <title>${data.title}</title>
  <style>
    body { font-family: ${fontFamily}; padding: 40px; color: #1e293b; direction: ${dir}; }
    h1 { color: #059669; font-size: 24px; margin-bottom: 4px; }
    .subtitle { color: #64748b; font-size: 14px; margin-bottom: 32px; }
    .cards { display: flex; gap: 16px; margin-bottom: 32px; }
    .card { flex: 1; padding: 16px; border: 1px solid #e2e8f0; border-radius: 8px; }
    .card-label { font-size: 12px; color: #64748b; text-transform: uppercase; }
    .card-value { font-size: 24px; font-weight: 700; margin-top: 8px; }
    .green { color: #059669; } .blue { color: #0284c7; } .amber { color: #d97706; }
    table { width: 100%; border-collapse: collapse; margin-bottom: 32px; }
    th, td { padding: 10px 12px; text-align: ${data.isAr ? "right" : "left"}; border-bottom: 1px solid #e2e8f0; }
    th { background: #f8fafc; font-size: 12px; color: #64748b; text-transform: uppercase; }
    .footer { margin-top: 40px; padding-top: 16px; border-top: 1px solid #e2e8f0; font-size: 12px; color: #94a3b8; }
    @media print { body { padding: 20px; } }
  </style>
</head>
<body>
  <h1>${data.title}</h1>
  <p class="subtitle">${data.period}</p>

  <div class="cards">
    <div class="card">
      <div class="card-label">${data.isAr ? "إجمالي الإيرادات" : "Total Revenue"}</div>
      <div class="card-value green">${data.currency} ${data.totalRevenue.toLocaleString()}</div>
    </div>
    <div class="card">
      <div class="card-label">${data.isAr ? "الإيداعات المحصلة" : "Deposits Collected"}</div>
      <div class="card-value blue">${data.currency} ${data.depositsCollected.toLocaleString()}</div>
    </div>
    <div class="card">
      <div class="card-label">${data.isAr ? "الإيداعات المعلقة" : "Deposits Pending"}</div>
      <div class="card-value amber">${data.currency} ${data.depositsPending.toLocaleString()}</div>
    </div>
  </div>

  <h2>${data.isAr ? "أفضل الخدمات" : "Top Services"}</h2>
  <table>
    <thead>
      <tr>
        <th>#</th>
        <th>${data.isAr ? "الخدمة" : "Service"}</th>
        <th>${data.isAr ? "الحجوزات" : "Bookings"}</th>
        <th>${data.isAr ? "الإيرادات" : "Revenue"}</th>
      </tr>
    </thead>
    <tbody>${serviceRows}</tbody>
  </table>

  <div class="footer">
    ${data.isAr ? "تم الإنشاء بواسطة ماودي" : "Generated by Mawidi"} • ${new Date().toLocaleDateString(data.isAr ? "ar-SA" : "en-US")}
  </div>
</body>
</html>`;
}

/**
 * Generate and download a revenue report as a printable HTML page
 */
export function exportRevenuePDF(data: {
  title: string;
  period: string;
  currency: string;
  totalRevenue: number;
  depositsCollected: number;
  depositsPending: number;
  topServices: Array<{ service: string; count: number; revenue: number }>;
  bookingSources: Record<string, number>;
  isAr: boolean;
}): void {
  const html = buildRevenueHTML(data);
  const blob = new Blob([html], { type: "text/html;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const printWindow = window.open(url, "_blank");
  if (printWindow) {
    printWindow.addEventListener("load", () => {
      printWindow.print();
      URL.revokeObjectURL(url);
    });
  } else {
    URL.revokeObjectURL(url);
  }
}
