"use client";

import { Download, Lock } from "lucide-react";
import Link from "next/link";

interface Lead {
  id: string;
  name: string | null;
  email: string | null;
  phone: string | null;
  capturedAt: Date | string;
}

export function LeadsExportButton({ leads, botName, canExport = false }: { leads: Lead[]; botName: string; canExport?: boolean }) {
  function exportCSV() {
    if (!canExport) return;
    const rows = [
      ["Nume", "Email", "Telefon", "Data"],
      ...leads.map((l) => [
        l.name ?? "",
        l.email ?? "",
        l.phone ?? "",
        new Date(l.capturedAt).toLocaleString("ro-RO"),
      ]),
    ];
    const csv = rows.map((r) => r.map((cell) => `"${cell.replace(/"/g, '""')}"`).join(",")).join("\n");
    const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `leaduri-${botName.toLowerCase().replace(/\s+/g, "-")}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  if (!canExport) {
    return (
      <Link href="/billing"
        className="flex items-center gap-2 border border-indigo-500/30 text-indigo-400 px-4 py-2.5 rounded-xl hover:bg-indigo-500/10 transition-colors text-sm font-medium"
        title="Disponibil din planul Starter">
        <Lock className="w-4 h-4" />
        Export CSV
      </Link>
    );
  }

  return (
    <button onClick={exportCSV}
      className="flex items-center gap-2 bg-white/[0.05] border border-white/[0.1] text-white px-4 py-2.5 rounded-xl hover:bg-white/[0.08] transition-colors text-sm font-medium">
      <Download className="w-4 h-4" />
      Export CSV
    </button>
  );
}
