"use client"

import jsPDF from "jspdf"
import autoTable from "jspdf-autotable"
import { Download, FileText, FileSpreadsheet } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

type MonthlySales = {
  month: string
  sales: number
}

type TopProduct = {
  name: string
  sales: number
  revenue: number
}

type CategoryData = {
  name: string
  value: number
  amount: number
}

type ReportExportButtonProps = {
  monthlySales: MonthlySales[]
  topProducts: TopProduct[]
  categoryData: CategoryData[]
}

export default function ReportExportButton({ monthlySales, topProducts, categoryData }: ReportExportButtonProps) {
  const handleExportPDF = () => {
    try {
      const doc = new jsPDF()
      const dateStr = new Date().toLocaleDateString('fr-MA')
      
      // Title
      doc.setFontSize(20)
      doc.text("Rapport des Ventes", 14, 22)
      doc.setFontSize(11)
      doc.setTextColor(100)
      doc.text(`Date de génération: ${dateStr}`, 14, 30)

      let currentY = 40

      // Table 1: Ventes Mensuelles
      doc.setFontSize(14)
      doc.setTextColor(0)
      doc.text("Ventes Mensuelles", 14, currentY)
      autoTable(doc, {
        startY: currentY + 4,
        head: [['Mois', 'Total Ventes (DH)']],
        body: monthlySales.map(s => [s.month, s.sales.toLocaleString()]),
        theme: 'striped',
        headStyles: { fillColor: [13, 148, 136] }, // Tailwind teal-600
        margin: { bottom: 20 }
      })

      // @ts-ignore
      currentY = doc.lastAutoTable.finalY + 15

      // Table 2: Top Produits
      doc.text("Top Produits", 14, currentY)
      autoTable(doc, {
        startY: currentY + 4,
        head: [['Produit', 'Quantité Vendue', 'Revenu (DH)']],
        body: topProducts.map(p => [p.name, p.sales.toString(), p.revenue.toLocaleString()]),
        theme: 'striped',
        headStyles: { fillColor: [13, 148, 136] },
        margin: { bottom: 20 }
      })

      // @ts-ignore
      currentY = doc.lastAutoTable.finalY + 15

      // If we don't have enough space for the 3rd table, add a new page
      if (currentY > 250) {
        doc.addPage()
        currentY = 20
      }

      // Table 3: Catégories
      doc.text("Ventes par Catégorie", 14, currentY)
      autoTable(doc, {
        startY: currentY + 4,
        head: [['Catégorie', 'Pourcentage (%)', 'Montant (DH)']],
        body: categoryData.map(c => [c.name, c.value.toString(), c.amount.toLocaleString()]),
        theme: 'striped',
        headStyles: { fillColor: [13, 148, 136] },
      })

      doc.save(`rapport_export_${new Date().toISOString().split('T')[0]}.pdf`)
    } catch (error) {
      console.error("Failed to generate PDF:", error)
      alert("Erreur lors de la génération du PDF")
    }
  }
  const handleExportCSV = () => {
    try {
      // Create CSV Headers
      const headers = ["Section", "Donnee", "Valeur"]
      const rows = []

      // Section: Ventes Mensuelles
      rows.push(["Ventes Mensuelles", "", ""])
      monthlySales.forEach(s => {
        rows.push(["", s.month, s.sales])
      })
      rows.push(["", "", ""])

      // Section: Top Produits
      rows.push(["Top Produits", "Quantite", "Revenu"])
      topProducts.forEach(p => {
        rows.push([p.name, p.sales, p.revenue])
      })
      rows.push(["", "", ""])

      // Section: Ventes par categorie
      rows.push(["Ventes par categorie", "Pourcentage", "Montant"])
      categoryData.forEach(c => {
        rows.push([c.name, `${c.value}%`, c.amount])
      })

      // Convert to CSV string format
      const csvContent = [
        headers.join(","),
        ...rows.map(row => row.join(","))
      ].join("\n")

      // Add UTF-8 BOM so Excel opens it correctly
      const blob = new Blob(["\uFEFF" + csvContent], { type: 'text/csv;charset=utf-8;' })
      
      const link = document.createElement("a")
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob)
        link.setAttribute("href", url)
        link.setAttribute("download", `rapport_export_${new Date().toISOString().split('T')[0]}.csv`)
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    } catch (error) {
      console.error("Failed to export CSV:", error)
      alert("Erreur lors de l'exportation CSV")
    }
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button className="print:hidden">
          <Download className="mr-2 h-4 w-4" />
          Exporter
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        <DropdownMenuItem onClick={handleExportPDF} className="cursor-pointer">
          <FileText className="mr-2 h-4 w-4" />
          <span>Exporter PDF</span>
        </DropdownMenuItem>
        <DropdownMenuItem onClick={handleExportCSV} className="cursor-pointer">
          <FileSpreadsheet className="mr-2 h-4 w-4" />
          <span>Exporter CSV</span>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
