"use client";
import Link from "next/link";
import { useState } from "react";
import Papa from "papaparse";
import { ArrowLeft, Download, FileSpreadsheet, Upload } from "lucide-react";
import { Badge, Button, Card, Field, Input, PageHeader, Select, api, useUI } from "@/components/ui";
import { useApi } from "@/components/hooks";

const BASE_FIELDS = [
  { value: "skip", label: "— Skip column —" }, { value: "name", label: "Full name" }, { value: "first_name", label: "First name" }, { value: "last_name", label: "Last name" },
  { value: "phone", label: "Phone" }, { value: "email", label: "Email" }, { value: "city", label: "City" }, { value: "project", label: "Project" }, { value: "source", label: "Source" }, { value: "tags", label: "Tags (comma separated)" },
];

function guess(col: string) {
  const c = col.toLowerCase().replace(/[^a-z]/g, "");
  if (/^(fullname|name|customername|contactname)$/.test(c)) return "name";
  if (/first/.test(c)) return "first_name";
  if (/last|surname/.test(c)) return "last_name";
  if (/phone|mobile|cell|whatsapp|contactno|number/.test(c)) return "phone";
  if (/email|mail/.test(c)) return "email";
  if (/city|district|area/.test(c)) return "city";
  if (/project|property/.test(c)) return "project";
  if (/source|channel/.test(c)) return "source";
  if (/tag/.test(c)) return "tags";
  return "skip";
}

export default function ImportPage() {
  const { push } = useUI();
  const fields = useApi<{ data: { key: string; label: string }[] }>("/custom-fields");
  const [rows, setRows] = useState<Record<string, string>[]>([]);
  const [cols, setCols] = useState<string[]>([]);
  const [mapping, setMapping] = useState<Record<string, string>>({});
  const [fileName, setFileName] = useState("");
  const [tags, setTags] = useState("");
  const [preview, setPreview] = useState<null | { rows: number; invalid: number; duplicatesInFile: number; matchesExisting: number; willCreate: number }>(null);
  const [progress, setProgress] = useState<null | { done: number; created: number; updated: number; errors: { row: number; error: string }[]; finished: boolean }>(null);
  const [busy, setBusy] = useState(false);
  const allFields = [...BASE_FIELDS, ...(fields.data?.data ?? []).map((f) => ({ value: `custom.${f.key}`, label: `Custom: ${f.label}` }))];

  const onFile = async (file: File) => {
    setFileName(file.name); setPreview(null); setProgress(null);
    let data: Record<string, string>[] = [];
    if (/\.xlsx?$/i.test(file.name)) {
      const readXlsx = (await import("read-excel-file")).default;
      const sheet = await readXlsx(file);
      const header = (sheet[0] ?? []).map((h) => String(h ?? "").trim());
      data = sheet.slice(1).map((r) => Object.fromEntries(header.map((h, i) => [h, r[i] == null ? "" : String(r[i])])));
    } else {
      const parsed = Papa.parse<Record<string, string>>(await file.text(), { header: true, skipEmptyLines: true });
      data = parsed.data;
    }
    if (data.length > 50000) { push("error", "Files are limited to 50,000 rows per import"); return; }
    const c = Object.keys(data[0] ?? {});
    setRows(data); setCols(c); setMapping(Object.fromEntries(c.map((x) => [x, guess(x)])));
  };

  const runPreview = async () => {
    setBusy(true);
    try { setPreview((await api("/contacts/import", { body: { rows: rows.slice(0, 1000), mapping, preview: true } })).data); } catch (e) { push("error", (e as Error).message); } finally { setBusy(false); }
  };

  const runImport = async () => {
    setBusy(true);
    const state = { done: 0, created: 0, updated: 0, errors: [] as { row: number; error: string }[], finished: false };
    setProgress({ ...state });
    const tagList = tags.split(",").map((t) => t.trim()).filter(Boolean);
    try {
      for (let i = 0; i < rows.length; i += 500) {
        const r = await api("/contacts/import", { body: { rows: rows.slice(i, i + 500), mapping, offset: i, tags: tagList } });
        state.done = Math.min(rows.length, i + 500); state.created += r.data.created; state.updated += r.data.updated; state.errors.push(...r.data.errors);
        setProgress({ ...state });
      }
      state.finished = true; setProgress({ ...state });
      push("ok", `Import complete: ${state.created} created, ${state.updated} updated`);
    } catch (e) { push("error", (e as Error).message); } finally { setBusy(false); }
  };

  const errorReport = () => {
    if (!progress) return;
    const csv = ["row,error", ...progress.errors.map((e) => `${e.row},"${e.error.replace(/"/g, '""')}"`)].join("\n");
    const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv" })); a.download = "import-errors.csv"; a.click();
  };

  return (
    <>
      <Link href="/contacts" className="mb-3 inline-flex items-center gap-1 text-[12.5px] text-ink-3 hover:text-ink"><ArrowLeft className="h-3.5 w-3.5" />Contacts</Link>
      <PageHeader title="Import contacts" subtitle="CSV or XLSX up to 50,000 rows · duplicates merge on phone or email" />
      <div className="grid gap-4 lg:grid-cols-[1fr_340px]">
        <div className="space-y-4">
          <label className="card flex cursor-pointer flex-col items-center justify-center gap-2 border-2 border-dashed border-line px-6 py-10 text-center hover:border-brand/50">
            <FileSpreadsheet className="h-8 w-8 text-brand" />
            <span className="text-[14px] font-medium">{fileName || "Choose a CSV or Excel file"}</span>
            <span className="text-[12px] text-ink-3">{rows.length ? `${rows.length.toLocaleString()} rows · ${cols.length} columns` : "First row must contain column headers"}</span>
            <input type="file" accept=".csv,.xlsx,.xls" className="hidden" onChange={(e) => e.target.files?.[0] && onFile(e.target.files[0])} />
          </label>
          {cols.length > 0 && (
            <Card title="Map columns" subtitle="We guessed the mapping — adjust anything that looks wrong" bodyClass="p-0">
              <table className="table-mac">
                <thead><tr><th>Column</th><th>Sample</th><th>Maps to</th></tr></thead>
                <tbody>{cols.map((c) => (
                  <tr key={c}><td className="font-medium">{c}</td><td className="max-w-[220px] truncate text-ink-3">{rows.slice(0, 3).map((r) => r[c]).filter(Boolean).join(" · ")}</td>
                    <td><Select value={mapping[c] ?? "skip"} onChange={(e) => setMapping({ ...mapping, [c]: e.target.value })}>{allFields.map((f) => <option key={f.value} value={f.value}>{f.label}</option>)}</Select></td></tr>
                ))}</tbody>
              </table>
            </Card>
          )}
        </div>
        <div className="space-y-4">
          <Card title="Options">
            <Field label="Add tags to every imported contact" hint="Comma separated"><Input value={tags} onChange={(e) => setTags(e.target.value)} placeholder="expo-2026, imported" /></Field>
            <div className="mt-4 flex gap-2">
              <Button className="flex-1" onClick={runPreview} disabled={!rows.length || busy}>Dedupe preview</Button>
              <Button className="flex-1" variant="primary" icon={<Upload className="h-3.5 w-3.5" />} onClick={runImport} loading={busy && !!progress} disabled={!rows.length || busy || !Object.values(mapping).some((v) => ["phone", "email", "name", "first_name"].includes(v))}>Import</Button>
            </div>
          </Card>
          {preview && (
            <Card title="Dedupe preview" subtitle="Based on the first 1,000 rows">
              <dl className="grid grid-cols-2 gap-y-2 text-[13px]">
                <dt className="text-ink-3">Rows checked</dt><dd className="text-right font-medium">{preview.rows}</dd>
                <dt className="text-ink-3">New contacts</dt><dd className="text-right font-medium text-ok">{preview.willCreate}</dd>
                <dt className="text-ink-3">Match existing (update)</dt><dd className="text-right font-medium text-info">{preview.matchesExisting}</dd>
                <dt className="text-ink-3">Duplicates inside file</dt><dd className="text-right font-medium text-warn">{preview.duplicatesInFile}</dd>
                <dt className="text-ink-3">Missing identifier</dt><dd className="text-right font-medium text-bad">{preview.invalid}</dd>
              </dl>
            </Card>
          )}
          {progress && (
            <Card title={progress.finished ? "Import finished" : "Importing…"}>
              <div className="h-2 overflow-hidden rounded-full bg-ink/[.07]"><div className="h-full bg-brand transition-all" style={{ width: `${(progress.done / Math.max(rows.length, 1)) * 100}%` }} /></div>
              <p className="mt-2 text-[12.5px] text-ink-2">{progress.done.toLocaleString()} / {rows.length.toLocaleString()} rows · <Badge tone="green">{progress.created} created</Badge> <Badge tone="blue">{progress.updated} updated</Badge> <Badge tone={progress.errors.length ? "red" : "gray"}>{progress.errors.length} errors</Badge></p>
              {progress.errors.length > 0 && <Button size="sm" className="mt-3" icon={<Download className="h-3.5 w-3.5" />} onClick={errorReport}>Download error report</Button>}
            </Card>
          )}
        </div>
      </div>
    </>
  );
}
