// import-page.jsx — Shopify Import Orders: CSV upload, sync, progress, anomaly detection
const { useState: useStateI, useRef: useRefI } = React;

function ImportPage({ onToast, onAddExceptions }) {
  const [phase, setPhase] = useStateI("idle"); // idle | running | done
  const [stepIdx, setStepIdx] = useStateI(0);
  const [progress, setProgress] = useStateI(0);
  const [fetched, setFetched] = useStateI(0);
  const [source, setSource] = useStateI("shopify");
  const [fileName, setFileName] = useStateI("");
  const [dragOver, setDragOver] = useStateI(false);
  const [added, setAdded] = useStateI(false);
  const fileRef = useRefI(null);
  const TOTAL = 128;

  function run(src) {
    setSource(src); setPhase("running"); setStepIdx(0); setProgress(0); setFetched(0); setAdded(false);
    let p = 0;
    const timer = setInterval(() => {
      p += 2 + Math.random() * 3;
      const pct = Math.min(100, p);
      setProgress(pct);
      setFetched(Math.round((pct / 100) * TOTAL));
      setStepIdx(pct < 18 ? 0 : pct < 55 ? 1 : pct < 80 ? 2 : pct < 100 ? 3 : 4);
      if (pct >= 100) { clearInterval(timer); setTimeout(() => setPhase("done"), 450); }
    }, 130);
  }
  function onFile(f) { if (!f) return; setFileName(f.name); run("csv"); }
  function reset() { setPhase("idle"); setFileName(""); setProgress(0); setFetched(0); setStepIdx(0); }

  const sev = { high: { c: "#b91c1c", b: "#fef2f2" }, medium: { c: "#c2410c", b: "#fff7ed" }, low: { c: "#52525b", b: "#f4f4f5" } };

  return (
    <div className="p-6 max-w-[1000px]">
      <div className="flex items-start gap-3 mb-5 flex-wrap">
        <div>
          <h2 className="text-[15px] font-semibold text-zinc-900 tracking-tight">Import Orders</h2>
          <p className="text-[12.5px] text-zinc-500 mt-0.5">Sync from Shopify or upload a CSV. OpsPilot validates every order and flags operational anomalies on the way in.</p>
        </div>
        {phase === "done" && <div className="ml-auto"><Button variant="default" size="md" icon="refresh" onClick={reset}>New import</Button></div>}
      </div>

      {phase === "idle" && (
        <div className="grid md:grid-cols-2 gap-4">
          {/* Shopify */}
          <div className="bg-white rounded-xl border border-zinc-200 p-5">
            <div className="flex items-center gap-3 mb-3">
              <div className="flex items-center justify-center w-10 h-10 rounded-lg text-white font-bold text-[13px]" style={{ background: "#16a34a" }}>SH</div>
              <div>
                <div className="flex items-center gap-2"><h3 className="text-[14px] font-semibold text-zinc-800">Shopify Storefront</h3><span className="inline-flex items-center gap-1 text-[11px] font-medium text-emerald-600"><span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />Connected</span></div>
                <p className="text-[11.5px] text-zinc-400">trapo.myshopify.com · last sync 2h ago</p>
              </div>
            </div>
            <p className="text-[12.5px] text-zinc-500 leading-relaxed mb-4">Pull the latest paid &amp; fulfilled orders directly from your Shopify store. Typically completes in under a minute.</p>
            <div className="flex items-center justify-between text-[12px] text-zinc-500 mb-4 px-3 py-2 rounded-lg bg-zinc-50 border border-zinc-100">
              <span><span className="font-semibold text-zinc-800 tabular-nums">128</span> new since last sync</span>
              <span><span className="font-semibold text-zinc-800 tabular-nums">1,284</span> total tracked</span>
            </div>
            <Button variant="primary" size="md" icon="refresh" full onClick={() => run("shopify")}>Sync Shopify orders</Button>
          </div>

          {/* CSV */}
          <div className="bg-white rounded-xl border border-zinc-200 p-5">
            <div className="flex items-center gap-3 mb-3">
              <div className="flex items-center justify-center w-10 h-10 rounded-lg" style={{ background: "var(--accent-wash)", color: "var(--accent)" }}><Icon name="filetext" size={19} /></div>
              <div>
                <h3 className="text-[14px] font-semibold text-zinc-800">Upload CSV</h3>
                <p className="text-[11.5px] text-zinc-400">Orders export · .csv up to 10MB</p>
              </div>
            </div>
            <div onDragOver={e => { e.preventDefault(); setDragOver(true); }} onDragLeave={() => setDragOver(false)}
              onDrop={e => { e.preventDefault(); setDragOver(false); onFile(e.dataTransfer.files[0]); }}
              onClick={() => fileRef.current?.click()}
              className={`rounded-xl border-2 border-dashed flex flex-col items-center justify-center py-7 px-4 cursor-pointer transition-colors ${dragOver ? "bg-zinc-50" : "border-zinc-300 hover:border-zinc-400 hover:bg-zinc-50/60"}`}
              style={dragOver ? { borderColor: "var(--accent)", background: "var(--accent-wash)" } : undefined}>
              <Icon name="uploadcloud" size={28} className="text-zinc-400 mb-2" />
              <p className="text-[12.5px] text-zinc-600 font-medium">Drop your CSV here or click to browse</p>
              <p className="text-[11px] text-zinc-400 mt-1">order_id, customer, sku, car_model, status, tracking</p>
              <input ref={fileRef} type="file" accept=".csv" className="hidden" onChange={e => onFile(e.target.files[0])} />
            </div>
          </div>
        </div>
      )}

      {phase === "running" && (
        <div className="bg-white rounded-xl border border-zinc-200 p-6">
          <div className="flex items-center gap-2.5 mb-5">
            <Icon name={source === "csv" ? "filetext" : "refresh"} size={16} className={source === "csv" ? "text-zinc-500" : "text-zinc-500 animate-spin"} style={source === "csv" ? undefined : { animationDuration: "1.4s" }} />
            <span className="text-[13.5px] font-semibold text-zinc-800">{source === "csv" ? `Importing ${fileName}` : "Syncing from Shopify"}</span>
            <span className="ml-auto text-[12.5px] font-semibold text-zinc-700 tabular-nums">{Math.round(progress)}%</span>
          </div>
          <div className="h-2 rounded-full bg-zinc-100 overflow-hidden mb-1.5">
            <div className="h-full rounded-full transition-all duration-150" style={{ width: progress + "%", background: "var(--accent)" }} />
          </div>
          <div className="text-[12px] text-zinc-400 mb-5 tabular-nums">{fetched} / {TOTAL} orders processed</div>

          <div className="space-y-1">
            {IMPORT_STEPS.slice(0, 4).map((s, i) => {
              const active = i === stepIdx, doneStep = i < stepIdx;
              return (
                <div key={s.key} className={`flex items-center gap-3 px-3 py-2 rounded-lg ${active ? "bg-zinc-50" : ""}`}>
                  <span className={`flex items-center justify-center w-6 h-6 rounded-full shrink-0 ${doneStep ? "text-white" : active ? "text-white" : "bg-zinc-100 text-zinc-400"}`}
                    style={doneStep || active ? { background: "var(--accent)" } : undefined}>
                    {doneStep ? <Icon name="check" size={13} strokeWidth={2.5} /> : active ? <Icon name={s.icon} size={12} className="animate-pulse" /> : <Icon name={s.icon} size={12} />}
                  </span>
                  <span className={`text-[12.5px] ${active || doneStep ? "text-zinc-700 font-medium" : "text-zinc-400"}`}>{s.label}</span>
                  {active && <span className="ml-auto text-[11px] text-zinc-400">working…</span>}
                  {doneStep && <span className="ml-auto"><Icon name="check" size={13} className="text-emerald-500" /></span>}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {phase === "done" && (
        <div className="space-y-4">
          {/* summary tiles */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5">
            {[["Imported", 122, "text-emerald-600", "check"], ["Updated", 14, "text-blue-600", "refresh"], ["Anomalies", IMPORT_ANOMALIES.length, "text-red-600", "alert"], ["Skipped", 6, "text-zinc-500", "x"]].map(([l, v, c, ic]) => (
              <div key={l} className="bg-white rounded-xl border border-zinc-200 px-4 py-3">
                <div className="flex items-center gap-1.5 text-[11.5px] text-zinc-500"><Icon name={ic} size={13} />{l}</div>
                <div className={`text-[22px] font-semibold tabular-nums mt-0.5 ${c}`}>{v}</div>
              </div>
            ))}
          </div>

          {/* anomalies */}
          <div className="bg-white rounded-xl border border-zinc-200 overflow-hidden">
            <div className="flex items-center gap-2.5 px-5 py-3.5 border-b border-zinc-200 flex-wrap">
              <span className="flex items-center justify-center w-5 h-5 rounded-md" style={{ background: "var(--accent-wash)" }}><Icon name="sparkles" size={13} style={{ color: "var(--accent)" }} /></span>
              <div>
                <h3 className="text-[14px] font-semibold text-zinc-900">Detected anomalies</h3>
                <p className="text-[11.5px] text-zinc-400 leading-tight">{IMPORT_ANOMALIES.length} operational issues found during import · ready to convert to exceptions</p>
              </div>
              <div className="ml-auto">
                <Button variant="primary" size="sm" icon={added ? "check" : "plus"} disabled={added}
                  onClick={() => { setAdded(true); onAddExceptions && onAddExceptions(IMPORT_ANOMALIES.length); }}>
                  {added ? "Added to queue" : `Add ${IMPORT_ANOMALIES.length} to queue`}
                </Button>
              </div>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full border-collapse min-w-[760px]">
                <thead><tr className="border-b border-zinc-200">{["Anomaly", "Order", "Customer", "Detail", "Severity"].map((h, i) => (<th key={i} className="text-left px-5 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-zinc-400 whitespace-nowrap">{h}</th>))}</tr></thead>
                <tbody>
                  {IMPORT_ANOMALIES.map(a => {
                    const t = ANOMALY_TYPES[a.type], s = sev[a.severity];
                    return (
                      <tr key={a.id} className="border-b border-zinc-100 hover:bg-zinc-50 transition-colors">
                        <td className="px-5 py-3"><span className="inline-flex items-center gap-1.5 rounded-md px-2 py-0.5 text-[11.5px] font-medium" style={{ background: t.bg, color: t.color }}><Icon name={t.icon} size={12} />{t.label}</span></td>
                        <td className="px-5 py-3"><span className="font-mono text-[12px] text-zinc-600">{a.order}</span></td>
                        <td className="px-5 py-3"><div className="flex items-center gap-2"><Avatar person={a.customer} size={24} /><span className="text-[12.5px] text-zinc-700">{a.customer.name}</span></div></td>
                        <td className="px-5 py-3 max-w-[280px]"><span className="text-[12px] text-zinc-500">{a.detail}</span></td>
                        <td className="px-5 py-3"><span className="inline-flex items-center gap-1.5 rounded-md px-2 py-0.5 text-[11px] font-medium capitalize" style={{ background: s.b, color: s.c }}><span className="w-1.5 h-1.5 rounded-full" style={{ background: s.c }} />{a.severity}</span></td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ImportPage });
