import { Button } from "@/components/ui/button";
import { useLazyGetLeadsQuery } from "@/store/api/leadsApi";
import { __ } from "@wordpress/i18n";
import { Download } from "lucide-react";

/** One CSV field, quoted, with formula-looking values defused. */
const field = (value) => {
  const text = String(value ?? "");
  const safe = /^[=+\-@]/.test(text) ? `'${text}` : text;
  return `"${safe.replace(/"/g, '""')}"`;
};

/**
 * "Download leads (CSV)": shoppers who ticked "send me offers" when they
 * emailed themselves a comparison.
 */
const LeadsDownload = () => {
  const [load, { isFetching }] = useLazyGetLeadsQuery();

  const download = async () => {
    const rows = await load().unwrap();
    const csv = [
      ["email", "product", "date"],
      ...rows.map((r) => [r.email, r.product, r.date]),
    ]
      .map((row) => row.map(field).join(","))
      .join("\n");
    const url = URL.createObjectURL(new Blob([csv], { type: "text/csv" }));
    const link = Object.assign(document.createElement("a"), {
      href: url,
      download: "comparison-leads.csv",
    });
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <Button
      variant="outline"
      size="sm"
      onClick={download}
      disabled={isFetching}
    >
      <Download aria-hidden="true" />
      {__("Download leads (CSV)", "product-comparison-for-woocommerce")}
    </Button>
  );
};

export default LeadsDownload;
