"use client"

import type { TableColumn } from "@/shared/types/common"
import jsPDF from "jspdf"
import autoTable from "jspdf-autotable"

export const exportToCSV = (data: any[], tableHeader: TableColumn[], filename: string) => {
  const BOM = "\uFEFF"

  const hasIsActive = data.some((row) => "isActive" in row)

  const headers = tableHeader.filter((column) => column.id !== "").map((column) => column.label)

  if (hasIsActive && !headers.includes("Active")) {
    headers.push("Active")
    tableHeader.push({ id: "isActive", label: "Active" })
  }

  const csvRows = [
    headers.join(","),
    ...data.map((row) => {
      return tableHeader
        .filter((column) => column.id !== "")
        .map((column) => {
          if (column.id === "isActive") {
            return row[column.id] ? "Oui" : "Non"
          }
          return JSON.stringify(row[column.id] ?? "")
        })
        .join(",")
    }),
  ]

  const csvString = BOM + csvRows.join("\n")

  const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" })
  const url = URL.createObjectURL(blob)

  const link = document.createElement("a")
  link.setAttribute("href", url)
  link.setAttribute("download", `${filename}.csv`)
  link.style.visibility = "hidden"
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

export const exportToPDF = (data: any[], tableHeader: TableColumn[], filename: string) => {
  const doc = new jsPDF({
    orientation: "landscape",
    unit: "mm",
    format: "a4",
  })

  const hasIsActive = data.some((row) => "isActive" in row)

  const headers = tableHeader.filter((column) => column.id !== "").map((column) => column.label)

  if (hasIsActive && !headers.includes("Active")) {
    headers.push("Active")
    tableHeader.push({id: "isActive",
      label: "Active"})
  }

  const rows = data.map((row) => {
    return tableHeader
      .filter((column) => column.id !== "")
      .map((column) => {
        if (column.id === "isActive") {
          return row[column.id] ? "Oui" : "Non"
        }
        return row[column.id] ?? ""
      })
  })

  const pageWidth = doc.internal.pageSize.getWidth()
  const pageHeight = doc.internal.pageSize.getHeight()
  const margins = 20

  doc.setFontSize(16)
  doc.setFont("helvetica", "bold")
  doc.text("liste "+filename.charAt(0).toUpperCase() + filename.slice(1), pageWidth / 2, margins, { align: "center" })
  autoTable(doc, {
    head: [headers],
    body: rows,
    theme: "grid",
    styles: {
      fontSize: 8,
      cellPadding: 2,
      overflow: "linebreak",
      halign: "left",
      valign: "middle",
      lineWidth: 0.5,
    },
    headStyles: {
      fillColor: [116, 108, 212],
      textColor: 255,
      fontSize: 8,
      fontStyle: "bold",
      halign: "center",
      minCellHeight: 12,
    },
    columnStyles: {
      email: { cellWidth: 40 },
      telephone: { cellWidth: 25 },
      nom: { cellWidth: 30 },
      prenom: { cellWidth: 30 },
    },
    alternateRowStyles: {
      fillColor: [245, 245, 245],
    },
    margin: {
      top: margins + 8,
      right: margins,
      bottom: margins,
      left: margins,
    },
    didParseCell: (data) => {
      if (data.section === "body") {
        data.cell.styles.cellPadding = 2
      }
    },
    willDrawCell: (data) => {
      if (data.cell?.text?.join("").length > 50) {
        data.cell.text = data.cell.text.map((str) => {
          if (typeof str === "string" && str.length > 50) {
            return str.match(/.{1,50}/g)?.join("\n") || str;
          }
          return str;
        });
      }      
    },
    didDrawPage: (data) => {
      const pageCount = doc.getNumberOfPages()
      doc.setFontSize(8)
      doc.text(`Page ${data.pageNumber} sur ${pageCount}`, pageWidth / 2, pageHeight - 10, { align: "center" })
    },
  })

  doc.save(`${filename}.pdf`)
}