"use client"
import { Menu, MenuItem, ListItemIcon, ListItemText } from "@mui/material"
import { PictureAsPdf as PdfIcon, TableChart as CsvIcon, Print as PrintIcon } from "@mui/icons-material"
import type { IEmail } from "@/shared/types/email"
import { jsPDF } from "jspdf"
import "jspdf-autotable"
import { formatDateTime } from "@/utils/format-time"

interface EmailExportProps {
  anchorEl: HTMLElement | null
  open: boolean
  onClose: () => void
  emails: IEmail[]
}

export default function EmailExport({ anchorEl, open, onClose, emails }: EmailExportProps) {
  const handleExportPDF = () => {
    const doc = new jsPDF()

    // Add title
    doc.setFontSize(16)
    doc.text("Historique des Emails", 14, 15)

    // Add date
    doc.setFontSize(10)
    doc.text(`Exporté le ${formatDateTime(new Date().toISOString())}`, 14, 22)

    // Create table
    const tableColumn = ["Date/Heure", "Destinataire", "Objet", "Statut"]
    const tableRows = emails.map((email) => [
      formatDateTime(email.dateHeure),
      `${email.destinataire} (${email.destinataireEmail})`,
      email.objet,
      email.status,
    ])

    // @ts-ignore
    doc.autoTable({
      head: [tableColumn],
      body: tableRows,
      startY: 30,
      styles: { fontSize: 8, cellPadding: 2 },
      headStyles: { fillColor: [41, 128, 185], textColor: 255 },
      alternateRowStyles: { fillColor: [245, 245, 245] },
    })

    doc.save("historique-emails.pdf")
    onClose()
  }

  const handleExportCSV = () => {
    // Create CSV content
    const headers = ["Date/Heure", "Destinataire", "Email", "Objet", "Statut"]
    const rows = emails.map((email) => [
      formatDateTime(email.dateHeure),
      email.destinataire,
      email.destinataireEmail,
      email.objet,
      email.status,
    ])

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

    // Create download link
    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" })
    const url = URL.createObjectURL(blob)
    const link = document.createElement("a")
    link.setAttribute("href", url)
    link.setAttribute("download", "historique-emails.csv")
    link.style.visibility = "hidden"
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    onClose()
  }

  const handlePrint = () => {
    window.print()
    onClose()
  }

  return (
    <Menu anchorEl={anchorEl} open={open} onClose={onClose}>
      <MenuItem onClick={handleExportPDF}>
        <ListItemIcon>
          <PdfIcon fontSize="small" color="error" />
        </ListItemIcon>
        <ListItemText>Exporter en PDF</ListItemText>
      </MenuItem>
      <MenuItem onClick={handleExportCSV}>
        <ListItemIcon>
          <CsvIcon fontSize="small" color="success" />
        </ListItemIcon>
        <ListItemText>Exporter en CSV</ListItemText>
      </MenuItem>
      <MenuItem onClick={handlePrint}>
        <ListItemIcon>
          <PrintIcon fontSize="small" color="primary" />
        </ListItemIcon>
        <ListItemText>Imprimer</ListItemText>
      </MenuItem>
    </Menu>
  )
}

