import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';
import * as XLSX from 'xlsx';
import Swal from 'sweetalert2';
import axios from 'axios';

export const handleDownloadOptions = async (endpoint, params, columns, mapRow, downloadType, apiUrl, apiHeaderJson) => {
    try {
        const headers = apiHeaderJson;

        Swal.fire({
            title: "Please wait...",
            html: "Your file is being prepared for download.",
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            },
        });

        const response = await axios.get(`${apiUrl}${endpoint}`, {
            params: params,
            headers: headers,
        });

        if (response.data.success) {
            const rows = response.data.data;
            const data = rows.map(mapRow);

            // Define date and time string before the switch
            const date = new Date();
            const dateString = date.toLocaleDateString().replace(/\//g, '-');
            const timeString = date.toLocaleTimeString().replace(/:/g, '-');

            switch (downloadType) {
                case 'excel':
                    const wb = XLSX.utils.book_new();
                    const ws = XLSX.utils.json_to_sheet(data, {
                        header: columns.map((column) => column.header),
                    });
                    ws["!cols"] = columns.map((column) => ({ wch: column.width }));
                    XLSX.utils.book_append_sheet(wb, ws, "Report");

                    XLSX.writeFile(wb, `Report_${dateString}_${timeString}.xlsx`);

                    Swal.close();
                    Swal.fire({
                        title: "Excel File Ready!",
                        text: "Your Excel file has been generated and downloaded successfully.",
                        icon: "success",
                    });
                    break;

                case 'csv':
                    const csvRows = [];
                    const headers = columns.map((col) => col.header);
                    csvRows.push(headers.join(","));
                    data.forEach((row) => {
                        const rowData = columns.map((col) => (row[col.header] ?? "").toString());
                        csvRows.push(rowData.join(","));
                    });
                    const csvContent = csvRows.join("\n");
                    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });

                    const fileNameCSV = `Report_${dateString}_${timeString}.csv`;
                    const linkCSV = document.createElement("a");
                    linkCSV.href = URL.createObjectURL(blob);
                    linkCSV.download = fileNameCSV;
                    linkCSV.click();

                    Swal.close();
                    Swal.fire({
                        title: "CSV File Ready!",
                        text: "Your CSV file has been generated and downloaded successfully.",
                        icon: "success",
                    });
                    break;

                // case 'pdf':
                //     const doc = new jsPDF();
                //     const pdfHeaders = columns.map((col) => col.header);
                //     doc.autoTable({
                //         head: [pdfHeaders],
                //         body: data.map((row) => columns.map((col) => row[col.header] ?? "-")),
                //         margin: { top: 20 },
                //     });

                //     const fileNamePDF = `Report_${dateString}_${timeString}.pdf`;
                //     doc.save(fileNamePDF);

                //     Swal.close();
                //     Swal.fire({
                //         title: "PDF File Ready!",
                //         text: "Your PDF file has been generated and downloaded successfully.",
                //         icon: "success",
                //     });
                //     break;

                case 'pdf':
  const doc = new jsPDF();
  // Attach autoTable to jsPDF instance (important!)
  autoTable(doc, {
    head: [columns.map((col) => col.header)],
    body: data.map((row) => columns.map((col) => row[col.header] ?? "-")),
    margin: { top: 20 },
  });

  const fileNamePDF = `Report_${dateString}_${timeString}.pdf`;
  doc.save(fileNamePDF);

  Swal.close();
  Swal.fire({
    title: "PDF File Ready!",
    text: "Your PDF file has been generated and downloaded successfully.",
    icon: "success",
  });
  break;

                case 'print':
                    // Open a new tab for the print preview
                    const printWindow = window.open('', '_blank', 'height=600,width=800');

                    // Generate HTML for the report
                    let html = "<h3>Report</h3><table border='1'><thead><tr>";
                    columns.forEach((col) => {
                        html += `<th>${col.header}</th>`;
                    });
                    html += "</tr></thead><tbody>";
                    data.forEach((row) => {
                        html += "<tr>";
                        columns.forEach((col) => {
                            html += `<td>${row[col.header] ?? "-"}</td>`;
                        });
                        html += "</tr>";
                    });
                    html += "</tbody></table>";

                    // Write the HTML to the new print window
                    printWindow.document.write(html);

                    // Close the SweetAlert loading modal
                    Swal.close();

                    // Wait for the print window to finish printing
                    printWindow.onafterprint = () => {
                        Swal.fire({
                            title: "Print Preview",
                            text: "Your report is ready for printing.",
                            icon: "success",
                        });
                    };

                    printWindow.document.close();
                    printWindow.print();
                    break;


                case 'copy':
                    // Copy CSV content to clipboard
                    const copyRows = [];
                    const copyHeaders = columns.map((col) => col.header);
                    copyRows.push(copyHeaders.join(","));
                    data.forEach((row) => {
                        const rowData = columns.map((col) => (row[col.header] ?? "").toString());
                        copyRows.push(rowData.join(","));
                    });
                    const copyContent = copyRows.join("\n");

                    // Use Clipboard API to copy text to clipboard
                    await navigator.clipboard.writeText(copyContent);

                    Swal.close();
                    Swal.fire({
                        title: "Copied to Clipboard!",
                        text: "The report data has been copied to your clipboard. You can now paste it wherever you like.",
                        icon: "success",
                    });
                    break;

                default:
                    Swal.close();
                    Swal.fire({
                        title: "Error",
                        text: "Invalid download type selected.",
                        icon: "error",
                    });
                    return;
            }
        } else {
            Swal.close();
            Swal.fire({
                title: "Error",
                text: response.data.message,
                icon: "error",
            });
        }
    } catch (error) {
        Swal.close();
        Swal.fire({
            title: "Error",
            text: error.message,
            icon: "error",
        });
    }
};