// ADM-PROC-23 · Bulk import farmers (CSV)  (Addendum Update A)
// Admin Web · Procurement Manager / System Admin · P0 · 1440×900
// Four-step wizard: upload → map columns → validate → confirm → complete.
// Registered as window.Pages.farmerImport.  Tweak fmImportStep drives the step.

const Ic23 = window.Icons;

const SRC_COLS = [
  ["Name", "Primary name", true],
  ["Phone", "Primary phone", true],
  ["Type", "Supplier type", false],
  ["County", "District", true],
  ["Village", "Village", false],
  ["Acres", "Land size", false],
  ["Variety", "Main variety", false],
];
const PREVIEW = [
  ["Jane Wanjiku", "+254 722 100 200", "Farmer", "Murang'a", "Kangema", "4.2", "Hass"],
  ["Embu Fresh Traders", "+254 733 400 500", "Middleman", "Embu", "Central", "—", "Fuerte"],
  ["Peter Otieno", "+254 711 900 800", "Farmer", "Nyeri", "Othaya", "2.8", "Hass"],
];

const FarmerImport = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const step = tweaks?.fmImportStep || "upload";
  const order = ["upload", "map", "validate", "confirm", "complete"];
  const idx = Math.max(0, order.indexOf(step));

  const STEPS = [{ t: "Upload" }, { t: "Map columns" }, { t: "Validate" }, { t: "Confirm & import" }];

  return (
    <div className="page">
      <div className="cr-head" style={{ maxWidth: 920, margin: "0 auto", width: "100%" }}>
        <div className="row" style={{ gap: 12, alignItems: "center" }}>
          <IconButton variant="ghost" icon={Ic23.ArrowLeft} onClick={() => go("ADM-PROC-20.html")}/>
          <div className="cr-head-title"><h1 className="cr-title">Bulk import farmers</h1>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>Onboard an existing supplier base from CSV or Excel.</div></div>
        </div>
      </div>

      <div className="fm-stepper" style={{ maxWidth: 920, width: "100%", margin: "0 auto 20px" }}>
        {STEPS.map((s, i) => (
          <React.Fragment key={s.t}>
            <span className={`fm-step ${i === Math.min(idx, 3) ? "on" : i < idx ? "done" : ""}`}><span className="n">{i < idx ? <Ic23.Check size={13}/> : i + 1}</span>{s.t}</span>
            {i < STEPS.length - 1 && <span className="fm-step-line"/>}
          </React.Fragment>
        ))}
      </div>

      <div className="fm-form" style={{ maxWidth: 920, margin: "0 auto" }}>
        {step === "upload" && (
          <div className="fm-section"><div className="fm-section-body">
            <div className="fm-drop">
              <span className="di"><Ic23.Upload size={24}/></span>
              <div style={{ fontWeight: 600, fontSize: 14.5 }}>Drop your CSV or Excel file here</div>
              <div className="muted" style={{ fontSize: 12.5 }}>or click to browse · max 10,000 rows per import</div>
              <Button variant="outline" size="sm" icon={Ic23.File} style={{ marginTop: 6 }}>Choose file</Button>
            </div>
            <div className="row" style={{ justifyContent: "space-between", marginTop: 16, flexWrap: "wrap", gap: 10 }}>
              <Button variant="ghost" size="sm" icon={Ic23.Download} onClick={() => toast({ title: "Template downloaded", desc: "Pre-formatted CSV with headers + sample rows." })}>Download template</Button>
              <Button variant="primary" icon={Ic23.ArrowRight} onClick={() => toast({ title: "Upload a file to continue", desc: "Use the Tweaks panel to preview later steps." })}>Next</Button>
            </div>
          </div></div>
        )}

        {step === "map" && (
          <div className="fm-section">
            <div className="fm-section-head"><div className="st"><Ic23.Layers size={16}/>Map columns</div><div className="sd">We auto-detected these. Confirm or override each mapping.</div></div>
            <div className="fm-section-body">
              <div className="tbl-wrap"><table className="tbl">
                <thead><tr><th>Source column</th><th>Maps to AMOMS field</th><th>Sample</th></tr></thead>
                <tbody>{SRC_COLS.map(([src, dst, req], i) => (
                  <tr key={src}><td className="mono" style={{ fontSize: 12.5 }}>{src}</td>
                    <td><select className="input" defaultValue={dst} style={{ maxWidth: 220 }}>
                      <option>{dst}{req ? "  (required)" : ""}</option><option>— skip this column —</option>
                    </select></td>
                    <td className="muted" style={{ fontSize: 12.5 }}>{PREVIEW[0][i]}</td></tr>
                ))}</tbody>
              </table></div>
              <div className="fm-grid2" style={{ marginTop: 16 }}>
                <label className="fm-field"><span>Default type (if column missing)</span><select className="input" defaultValue="Farmer"><option>Farmer</option><option>Middleman</option><option>Cooperative</option><option>Agent</option></select></label>
                <label className="fm-field"><span>Add all to group (optional)</span><select className="input"><option>None</option>{window.FM.GROUPS.map(g => <option key={g.id}>{g.name}</option>)}</select></label>
              </div>
              <div className="row" style={{ justifyContent: "space-between", marginTop: 18 }}><Button variant="outline">Back</Button><Button variant="primary" icon={Ic23.ArrowRight}>Validate</Button></div>
            </div>
          </div>
        )}

        {step === "validate" && (
          <div className="fm-section">
            <div className="fm-section-head"><div className="st"><Ic23.CheckCircle size={16}/>Validation report</div><div className="sd">1,204 rows processed.</div></div>
            <div className="fm-section-body">
              <div className="fm-kpis" style={{ marginBottom: 16 }}>
                <div className="fm-kpi"><div className="k" style={{ color: "var(--success-fg)" }}>Valid rows</div><div className="v">1,142</div></div>
                <div className="fm-kpi"><div className="k" style={{ color: "var(--warning-fg)" }}>With issues</div><div className="v">62</div></div>
              </div>
              <div className="tbl-wrap"><table className="tbl">
                <thead><tr><th>Issue type</th><th className="num">Rows</th><th>Action</th></tr></thead>
                <tbody>
                  {[["Missing required field", 18], ["Duplicate phone", 24], ["Invalid phone format", 14], ["Invalid district", 6]].map(([n, c]) => (
                    <tr key={n}><td>{n}</td><td className="num">{c}</td><td className="muted" style={{ fontSize: 12.5 }}>Excluded from import</td></tr>
                  ))}
                </tbody>
              </table></div>
              <div className="row" style={{ justifyContent: "space-between", marginTop: 16 }}>
                <Button variant="ghost" size="sm" icon={Ic23.Download}>Download 62 error rows</Button>
                <div className="row" style={{ gap: 8 }}><Button variant="outline">Back</Button><Button variant="primary" icon={Ic23.ArrowRight}>Continue</Button></div>
              </div>
            </div>
          </div>
        )}

        {step === "confirm" && (
          <div className="fm-section">
            <div className="fm-section-head"><div className="st"><Ic23.Upload size={16}/>Confirm & import</div></div>
            <div className="fm-section-body">
              <div className="fm-banner info"><Ic23.Info size={16} className="bi"/><div><b>1,142 valid records</b> will be imported. 62 rows with issues are excluded. Duplicate handling: <b>Skip</b>.</div></div>
              <label className="fm-field" style={{ maxWidth: 320, marginBottom: 16 }}><span>On duplicate phone</span>
                <select className="input" defaultValue="Skip"><option>Skip (safer)</option><option>Update existing (destructive)</option><option>Fail import</option></select></label>
              <div className="row" style={{ justifyContent: "space-between" }}><Button variant="outline">Back</Button>
                <Button variant="primary" icon={Ic23.Check} onClick={() => toast({ title: "Import started", desc: "Server-side batch — safe to close this tab." })}>Import 1,142 records</Button></div>
            </div>
          </div>
        )}

        {step === "complete" && (
          <div className="fm-section"><div className="fm-section-body" style={{ textAlign: "center", padding: "40px 24px" }}>
            <div style={{ width: 56, height: 56, borderRadius: 16, background: "var(--success-soft)", color: "var(--success-fg)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 12 }}><Ic23.CheckCircle size={28}/></div>
            <div style={{ fontWeight: 600, fontSize: 18 }}>Import complete</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>1,142 farmers imported · 62 rows failed and were skipped.</div>
            <div className="row" style={{ justifyContent: "center", gap: 8, marginTop: 18 }}>
              <Button variant="ghost" size="sm" icon={Ic23.Download}>Download error log</Button>
              <Button variant="primary" icon={Ic23.Users} onClick={() => go("ADM-PROC-20.html")}>View imported farmers</Button>
            </div>
          </div></div>
        )}
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { farmerImport: FarmerImport });
