import type { CellValue } from "@/components/grid/types";

/** Parse clipboard text copied out of Excel / Google Sheets into a matrix. */
export function parseClipboardMatrix(text: string): string[][] {
  const normalized = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  const rows = normalized.split("\n").filter((line, i, arr) => line.trim() !== "" || i < arr.length - 1);
  return rows
    .filter((line) => line.trim() !== "")
    .map((line) => (line.includes("\t") ? line.split("\t") : splitCsvLine(line)).map((c) => c.trim()));
}

function splitCsvLine(line: string): string[] {
  const out: string[] = [];
  let cur = "";
  let quoted = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i]!;
    if (ch === '"') {
      if (quoted && line[i + 1] === '"') {
        cur += '"';
        i++;
      } else quoted = !quoted;
    } else if (ch === "," && !quoted) {
      out.push(cur);
      cur = "";
    } else cur += ch;
  }
  out.push(cur);
  return out;
}

export function toMatrixText(matrix: (CellValue)[][]): string {
  return matrix.map((row) => row.map((c) => (c === null || c === undefined ? "" : String(c))).join("\t")).join("\n");
}

export function toCsv(headers: string[], rows: CellValue[][]): string {
  const esc = (v: CellValue) => {
    const s = v === null || v === undefined ? "" : String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  return [headers.map(esc).join(","), ...rows.map((r) => r.map(esc).join(","))].join("\n");
}

export function download(filename: string, content: string, mime = "text/csv;charset=utf-8;") {
  if (typeof document === "undefined") return;
  const blob = new Blob(["\uFEFF" + content], { type: mime });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

export async function copyToClipboard(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}

/** Fuzzy-match a pasted Excel header to a grid column key. */
export function matchHeader(header: string, columns: { key: string; header: string }[]): string | null {
  const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
  const h = norm(header);
  if (!h) return null;
  const exact = columns.find((c) => norm(c.header) === h || norm(c.key) === h);
  if (exact) return exact.key;
  const partial = columns.find((c) => norm(c.header).includes(h) || h.includes(norm(c.key)));
  return partial?.key ?? null;
}

export function formatMoney(value: CellValue) {
  const n = Number(value ?? 0);
  if (Number.isNaN(n)) return String(value ?? "");
  return `₹${n.toLocaleString("en-IN")}`;
}
