/* Import — CSV / XLSX upload (Seller Central, fournisseurs, banques) */

const IMPORT_TYPES = [
  { id: "seller",    label: "Seller Central — Inventaire", icon: "box",     fields: "ASIN, SKU, Title, Price, Inventory, BSR" },
  { id: "orders",    label: "Seller Central — Commandes",  icon: "shopping", fields: "Order ID, Date, ASIN, Qty, Revenue, Fees" },
  { id: "supplier",  label: "Fournisseur — Catalogue",     icon: "users",   fields: "Product, Cost, MOQ, Lead Days, Category" },
  { id: "bank",      label: "Relevé bancaire — CIBC",      icon: "dollar",  fields: "Date, Amount, Description, Reconciled" },
  { id: "ppc",       label: "Sponsored Ads — Campagnes",   icon: "target",  fields: "Campaign, Spend, Sales, ACOS, Clicks" },
];

const RECENT_IMPORTS = [
  { id: "imp-101", type: "seller", file: "inventory-2026-05-09.csv",  rows: 142, ok: 138, errors: 4,  date: "Hier 14:22",  user: "carly"   },
  { id: "imp-100", type: "bank",   file: "cibc-statement-04-2026.csv",rows: 87,  ok: 87,  errors: 0,  date: "10 mai 09:15", user: "clarens" },
  { id: "imp-099", type: "supplier",file:"foshan-pricelist-q2.xlsx",  rows: 28,  ok: 28,  errors: 0,  date: "08 mai 16:40", user: "kevin"   },
  { id: "imp-098", type: "orders", file: "orders-april-2026.csv",      rows: 412, ok: 410, errors: 2,  date: "07 mai 11:02", user: "carly"   },
];

// Minimal CSV parser — handles quoted fields, escaped quotes, CRLF
function parseCSV(text) {
  const rows = [];
  let row = [], field = "", inQuotes = false;
  for (let i = 0; i < text.length; i++) {
    const ch = text[i], next = text[i + 1];
    if (inQuotes) {
      if (ch === '"' && next === '"') { field += '"'; i++; }
      else if (ch === '"') { inQuotes = false; }
      else { field += ch; }
    } else {
      if (ch === '"') inQuotes = true;
      else if (ch === ",") { row.push(field); field = ""; }
      else if (ch === "\n") { row.push(field); rows.push(row); row = []; field = ""; }
      else if (ch === "\r") { /* skip */ }
      else { field += ch; }
    }
  }
  if (field.length || row.length) { row.push(field); rows.push(row); }
  if (!rows.length) return { headers: [], items: [] };
  const headers = rows[0].map(h => String(h || "").trim());
  const items = rows.slice(1).filter(r => r.some(c => String(c).trim()))
    .map(r => Object.fromEntries(headers.map((h, j) => [h, (r[j] || "").trim()])));
  return { headers, items };
}

// Column mappings per import type → DB column
const COL_MAP = {
  seller:   "products",
  orders:   "finances",
  supplier: "suppliers",
  bank:     "expenses",
  ppc:      "finances",
};

const Import = () => {
  const [picked, setPicked] = useState(IMPORT_TYPES[0].id);
  const [dragging, setDragging] = useState(false);
  const [parsing, setParsing] = useState(false);
  const [preview, setPreview] = useState(null); // { headers, items, fileName }
  const [importStatus, setImportStatus] = useState(""); // "" | "saving" | "ok" | "error"
  const [error, setError] = useState("");
  const fileInputRef = useRef(null);
  const cur = IMPORT_TYPES.find(t => t.id === picked) || IMPORT_TYPES[0];
  const toast = (window.useToast || (() => () => {}))();

  const handleFile = async (file) => {
    if (!file) return;
    setError("");
    if (file.size > 10 * 1024 * 1024) {
      setError("Fichier trop lourd (max 10 Mo).");
      return;
    }
    setParsing(true);
    try {
      const text = await file.text();
      const { headers, items } = parseCSV(text);
      if (!items.length) {
        setError("Aucune ligne détectée. Vérifie le format CSV (séparateur virgule, première ligne = en-têtes).");
        setParsing(false);
        return;
      }
      setPreview({ headers, items, fileName: file.name });
    } catch (err) {
      setError("Erreur lecture: " + err.message);
    }
    setParsing(false);
  };

  const confirmImport = async () => {
    if (!preview) return;
    const col = COL_MAP[picked];
    if (!col) { setError("Type d'import non supporté"); return; }
    setImportStatus("saving");
    try {
      // Normalize rows → add id if missing
      const items = preview.items.map((r, i) => ({
        id: r.id || r.asin || r.sku || r.ID || `imp-${Date.now()}-${i}`,
        ...r,
      }));
      const res = await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col, items }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setImportStatus("ok");
      toast?.({ message: `${items.length} ligne(s) importée(s) dans ${col}`, tone: "success" });
      setTimeout(() => { setPreview(null); setImportStatus(""); }, 1500);
    } catch (err) {
      setImportStatus("error");
      setError("Échec sync: " + err.message);
    }
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Import</div>
          <div className="page-sub">
            CSV · XLSX · Seller Central, fournisseurs, relevés bancaires · validation auto + dry-run
          </div>
        </div>
      </div>

      {/* Type picker */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(5, 1fr)", gap: 10, marginBottom: 14 }}>
        {IMPORT_TYPES.map(t => (
          <button
            key={t.id}
            onClick={() => setPicked(t.id)}
            className="card"
            style={{
              padding: 12, textAlign: "left", cursor: "pointer",
              border: picked === t.id ? "1px solid var(--accent)" : "1px solid var(--border-subtle)",
              background: picked === t.id ? "var(--accent-soft)" : "var(--bg-1)",
              transition: "all 120ms",
            }}
          >
            <Icon name={t.icon} size={16} style={{ color: picked === t.id ? "var(--accent)" : "var(--text-dim)" }} />
            <div style={{ fontSize: 12.5, fontWeight: 550, marginTop: 8, lineHeight: 1.3 }}>{t.label}</div>
          </button>
        ))}
      </div>

      {/* Upload zone */}
      <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 14 }}>
        <div style={{ padding: 14, borderBottom: "1px solid var(--border-subtle)" }}>
          <div className="between">
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{cur.label}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 2 }}>
                Colonnes attendues: {cur.fields}
              </div>
            </div>
            <button className="btn" data-variant="ghost" onClick={() => {
              const csv = cur.fields.split(",").map(f => f.trim()).join(",") + "\n";
              const blob = new Blob([csv], { type: "text/csv" });
              const url = URL.createObjectURL(blob);
              const a = document.createElement("a");
              a.href = url; a.download = `template-${cur.id}.csv`; a.click();
              setTimeout(() => URL.revokeObjectURL(url), 1000);
            }}>
              <Icon name="download" size={12} /> Template
            </button>
          </div>
        </div>

        <div
          onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
          onDragLeave={() => setDragging(false)}
          onDrop={(e) => {
            e.preventDefault();
            setDragging(false);
            const f = e.dataTransfer?.files?.[0];
            if (f) handleFile(f);
          }}
          style={{
            padding: 40, textAlign: "center",
            background: dragging ? "var(--accent-soft)" : "transparent",
            border: dragging ? "2px dashed var(--accent)" : "2px dashed var(--border-subtle)",
            margin: 14, borderRadius: 10, transition: "all 120ms",
            cursor: "pointer",
          }}
          onClick={() => fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept=".csv,.txt,text/csv"
            style={{ display: "none" }}
            onChange={(e) => handleFile(e.target.files?.[0])}
          />
          <Icon name="upload" size={32} style={{ color: "var(--text-dim)", marginBottom: 10 }} />
          <div style={{ fontSize: 14, fontWeight: 550 }}>
            {parsing ? "Lecture du fichier…" : "Glissez votre fichier ici"}
          </div>
          <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>ou cliquez pour parcourir · CSV · max 10 Mo</div>
          <button className="btn" data-variant="primary" style={{ marginTop: 14 }}
                  onClick={(e) => { e.stopPropagation(); fileInputRef.current?.click(); }}>
            Choisir un fichier
          </button>
          {error && (
            <div style={{ marginTop: 12, color: "var(--red)", fontSize: 12 }}>{error}</div>
          )}
        </div>
      </div>

      {/* Preview + confirm */}
      {preview && (
        <div className="card" style={{ padding: 0, overflow: "hidden", marginBottom: 14 }}>
          <div className="between" style={{ padding: 12, borderBottom: "1px solid var(--border-subtle)" }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Aperçu · {preview.fileName}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 2 }}>
                {preview.items.length} ligne(s) · {preview.headers.length} colonne(s) · cible D1 : <strong>{COL_MAP[picked]}</strong>
              </div>
            </div>
            <div className="row" style={{ gap: 6 }}>
              <button className="btn" data-variant="ghost" onClick={() => { setPreview(null); setError(""); }}>
                Annuler
              </button>
              <button className="btn" data-variant="primary" onClick={confirmImport} disabled={importStatus === "saving"}>
                {importStatus === "saving" ? "Envoi…" : importStatus === "ok" ? "✓ Importé" : "Confirmer l'import"}
              </button>
            </div>
          </div>
          <div style={{ maxHeight: 280, overflow: "auto" }}>
            <table className="table" style={{ minWidth: 600 }}>
              <thead>
                <tr>{preview.headers.map((h, i) => <th key={i} className="mono" style={{ fontSize: 11 }}>{h}</th>)}</tr>
              </thead>
              <tbody>
                {preview.items.slice(0, 20).map((r, i) => (
                  <tr key={i}>
                    {preview.headers.map((h, j) => (
                      <td key={j} className="mono" style={{ fontSize: 11 }}>{String(r[h] || "")}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
            {preview.items.length > 20 && (
              <div className="muted" style={{ padding: 10, fontSize: 11, textAlign: "center" }}>
                +{preview.items.length - 20} ligne(s) supplémentaires…
              </div>
            )}
          </div>
        </div>
      )}

      {/* Recent imports */}
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: 12, borderBottom: "1px solid var(--border-subtle)", fontSize: 12, fontWeight: 600 }}>
          Imports récents
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>ID</th>
              <th>Type</th>
              <th>Fichier</th>
              <th style={{ textAlign: "right" }}>Lignes</th>
              <th style={{ textAlign: "right" }}>OK / Erreurs</th>
              <th>Date</th>
              <th>Par</th>
            </tr>
          </thead>
          <tbody>
            {RECENT_IMPORTS.map(r => {
              const t = IMPORT_TYPES.find(x => x.id === r.type) || IMPORT_TYPES[0];
              return (
                <tr key={r.id}>
                  <td className="mono">{r.id}</td>
                  <td><span className="row" style={{ gap: 6 }}><Icon name={t.icon} size={12} /> {t.label.split("—")[0].trim()}</span></td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{r.file}</td>
                  <td className="mono" style={{ textAlign: "right" }}>{r.rows}</td>
                  <td className="mono" style={{ textAlign: "right" }}>
                    <span style={{ color: "var(--green)" }}>{r.ok}</span>
                    {r.errors > 0 && <span style={{ color: "var(--red)" }}> / {r.errors}</span>}
                  </td>
                  <td className="muted" style={{ fontSize: 11.5 }}>{r.date}</td>
                  <td><span className="row" style={{ gap: 6 }}><Avatar user={r.user} size="sm" /><span style={{ textTransform: "capitalize", fontSize: 12 }}>{r.user}</span></span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

window.Import = Import;
