// Perdura — Data Import (Stage 6). Standalone page for ongoing workbook uploads
// after onboarding: the shared WorkbookUploader (validate → tie-out report →
// import), a downloadable canonical template, and a history of past imports
// (recorded in import_runs). Re-uploads replace idempotently (forceReseed).
//
// Generic — no industry/customer-conditional logic. Route: /<tenant>/data-import.

(function () {
  const R = window.React;
  if (!R) return;
  const { useState, useEffect, useCallback } = R;
  const db = () => window.supabaseClient;

  function StatusBadge({ status }) {
    const s = status || "success";
    const ok = s === "success";
    const warn = s === "success_with_warnings";
    const color = ok ? "#10b981" : warn ? "#b7791f" : "#c0392b";
    return R.createElement("span", {
      style: { fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.3, color, background: color + "1a", padding: "2px 8px", borderRadius: 999 },
    }, s.replace(/_/g, " "));
  }

  function DataImportPage(props) {
    const companyId = props.scopedCompanyId || (props.companyProfile && props.companyProfile.id);
    const [history, setHistory] = useState(null);

    const loadHistory = useCallback(async () => {
      if (!companyId) return;
      try {
        const { data } = await db().from("import_runs")
          .select("id,file_name,status,counts,gates,data_min,data_max,created_at")
          .eq("company_id", companyId).order("created_at", { ascending: false }).limit(50);
        setHistory(data || []);
      } catch (_e) { setHistory([]); }
    }, [companyId]);
    useEffect(() => { loadHistory(); }, [loadHistory]);

    async function recordRun(report) {
      if (!companyId || !report) return;
      let userId = null;
      try { const { data } = await db().auth.getUser(); userId = data && data.user ? data.user.id : null; } catch (_e) { /* ignore */ }
      const dr = report.data_range || {};
      try {
        await db().from("import_runs").insert({
          company_id: companyId,
          file_name: (report.profile && report.profile.name) || "workbook",
          uploaded_by: userId,
          status: report.status || "success",
          counts: report.counts || {},
          gates: report.gates || {},
          data_min: dr.min || null, data_max: dr.max || null,
        });
      } catch (_e) { /* history is best-effort; ingestion already succeeded */ }
      loadHistory();
    }

    if (!companyId) return R.createElement("div", { className: "pc-page" }, R.createElement("div", { style: { padding: 40, color: "var(--text-3)" } }, "Select a company to import data."));

    return R.createElement("div", { className: "pc-page" },
      R.createElement("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 16 } },
        R.createElement("div", null,
          R.createElement("h1", { style: { fontSize: 22, fontWeight: 800, margin: 0 } }, "Data Import"),
          R.createElement("div", { style: { fontSize: 13, color: "var(--text-3)", marginTop: 4 } },
            "Upload your books as the canonical Excel workbook. We validate the tie-outs and import on the spot; re-uploading replaces your data without duplicating.")),
        window.PerduraIngest ? R.createElement("button", { className: "pc-btn pc-btn-ghost", style: { fontSize: 12.5 }, onClick: () => window.PerduraIngest.downloadTemplate() }, "Download canonical template") : null),

      R.createElement("div", { className: "pc-card", style: { padding: 18, marginBottom: 18 } },
        window.WorkbookUploader
          ? R.createElement(window.WorkbookUploader, { companyId, forceReseed: true, onImported: recordRun })
          : R.createElement("div", { style: { color: "var(--text-3)" } }, "Uploader loading…")),

      R.createElement("div", { className: "pc-card", style: { padding: 0 } },
        R.createElement("div", { className: "pc-card-hd" }, R.createElement("div", { className: "pc-card-title" }, "Import history")),
        history == null
          ? R.createElement("div", { style: { padding: 24, color: "var(--text-3)" } }, "Loading…")
          : (history.length === 0
            ? R.createElement("div", { style: { padding: 24, color: "var(--text-3)", fontSize: 13 } }, "No imports yet. Upload a workbook above to get started.")
            : R.createElement("div", { className: "pc-adm-table-wrap" },
              R.createElement("table", { className: "pc-adm-table" },
                R.createElement("thead", null, R.createElement("tr", null,
                  ["When", "File", "Status", "GL rows", "Accounts", "Data range"].map((h, i) => R.createElement("th", { key: i }, h)))),
                R.createElement("tbody", null,
                  history.map((r) => R.createElement("tr", { key: r.id },
                    R.createElement("td", { style: { fontSize: 12, color: "var(--text-3)" } }, r.created_at ? String(r.created_at).slice(0, 16).replace("T", " ") : "—"),
                    R.createElement("td", { style: { fontWeight: 600 } }, r.file_name || "—"),
                    R.createElement("td", null, R.createElement(StatusBadge, { status: r.status })),
                    R.createElement("td", { style: { fontFamily: "ui-monospace,monospace", fontSize: 12.5 } }, (r.counts && r.counts.gl_transactions != null) ? Number(r.counts.gl_transactions).toLocaleString() : "—"),
                    R.createElement("td", { style: { fontFamily: "ui-monospace,monospace", fontSize: 12.5 } }, (r.counts && r.counts.accounts != null) ? r.counts.accounts : "—"),
                    R.createElement("td", { style: { fontSize: 12, color: "var(--text-3)", fontFamily: "ui-monospace,monospace" } }, `${r.data_min || "—"} → ${r.data_max || "—"}`))))))))
    );
  }

  window.DataImportPage = DataImportPage;
})();
