import { ExportFormat } from "@/components/ExportModal";

interface CallLog {
  time: string;
  customer: string;
  intent: string;
  outcome: string;
  duration: string;
  sentiment: string;
  cost: string;
  outcomeColor?: string;
  sentimentColor?: string;
}

/**
 * Export call logs to CSV format
 */
export function exportToCSV(data: CallLog[], filename: string = "call-logs"): void {
  // Define CSV headers
  const headers = ["Time", "Customer", "Intent", "Outcome", "Duration", "Sentiment", "Cost"];

  // Convert data to CSV rows
  const rows = data.map((log) => [
    log.time,
    log.customer,
    log.intent,
    log.outcome,
    log.duration,
    log.sentiment,
    log.cost,
  ]);

  // Combine headers and rows
  const csvContent = [
    headers.join(","),
    ...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
  ].join("\n");

  // Create and download file
  downloadFile(csvContent, `${filename}.csv`, "text/csv;charset=utf-8;");
}

/**
 * Export call logs to JSON format
 */
export function exportToJSON(data: CallLog[], filename: string = "call-logs"): void {
  // Clean data by removing color properties (outcomeColor, sentimentColor)
  const cleanData = data.map(({ outcomeColor, sentimentColor, ...rest }) => rest);

  const jsonContent = JSON.stringify(cleanData, null, 2);

  downloadFile(jsonContent, `${filename}.json`, "application/json;charset=utf-8;");
}

/**
 * Export call logs to Excel format (XLSX)
 * Note: This creates a simple XML-based Excel file format
 */
export function exportToExcel(data: CallLog[], filename: string = "call-logs"): void {
  // Define headers
  const headers = ["Time", "Customer", "Intent", "Outcome", "Duration", "Sentiment", "Cost"];

  // Create Excel XML content
  let excelContent = `<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <Worksheet ss:Name="Call Logs">
  <Table>
   <Row>`;

  // Add headers
  headers.forEach((header) => {
    excelContent += `<Cell><Data ss:Type="String">${escapeXML(header)}</Data></Cell>`;
  });
  excelContent += `</Row>`;

  // Add data rows
  data.forEach((log) => {
    excelContent += `<Row>
     <Cell><Data ss:Type="String">${escapeXML(log.time)}</Data></Cell>
     <Cell><Data ss:Type="String">${escapeXML(log.customer)}</Data></Cell>
     <Cell><Data ss:Type="String">${escapeXML(log.intent)}</Data></Cell>
     <Cell><Data ss:Type="String">${escapeXML(log.outcome)}</Data></Cell>
     <Cell><Data ss:Type="String">${escapeXML(log.duration)}</Data></Cell>
     <Cell><Data ss:Type="String">${escapeXML(log.sentiment)}</Data></Cell>
     <Cell><Data ss:Type="String">${escapeXML(log.cost)}</Data></Cell>
    </Row>`;
  });

  excelContent += `
  </Table>
 </Worksheet>
</Workbook>`;

  downloadFile(
    excelContent,
    `${filename}.xls`,
    "application/vnd.ms-excel;charset=utf-8;"
  );
}

/**
 * Main export function that delegates to format-specific functions
 */
export function exportCallLogs(
  data: CallLog[],
  format: ExportFormat,
  filename: string = "call-logs"
): void {
  switch (format) {
    case "csv":
      exportToCSV(data, filename);
      break;
    case "json":
      exportToJSON(data, filename);
      break;
    case "excel":
      exportToExcel(data, filename);
      break;
    default:
      throw new Error(`Unsupported export format: ${format}`);
  }
}

/**
 * Helper function to download a file
 */
function downloadFile(content: string, filename: string, mimeType: string): void {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

/**
 * Helper function to escape XML special characters
 */
function escapeXML(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}
