"use client";

interface CsvGeneratorProps {
  accountNo: string;
  balance: string;
  txns: any[];
}

export const generateCSV = (
  accountNo: string,
  balance: string,
  txns: any[]
) => {
  // CSV Header
  let csv = `Bank Statement\n`;
  csv += `Account No:,${accountNo}\n`;
  csv += `Available Balance:,${balance}\n`;
  csv += `Generated:,${new Date().toLocaleString()}\n\n`;

  // Column headers
  csv += "Date,Name,Type,Amount\n";

  // Rows
  txns.forEach((txn) => {
    csv += `${txn.date},${txn.name},${txn.type.toLowerCase()},${txn.amount}\n`;
  });

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

  const link = document.createElement("a");
  link.setAttribute("href", url);
  link.setAttribute("download", `statement_${accountNo}.csv`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export default function CsvGenerator({
  accountNo,
  balance,
  txns,
}: CsvGeneratorProps) {
  return (
    <button
      onClick={() => generateCSV(accountNo, balance, txns)}
      style={{
        padding: "6px 12px",
        borderRadius: "6px",
        background: "#02a355",
        color: "white",
        border: "none",
        cursor: "pointer",
      }}
    >
      Download CSV
    </button>
  );
}
