// ADM-PROC-22 · Create / edit farmer  (Addendum Update A)
// Admin Web · Procurement Manager / Officer · P0 · 1440×900
// Multi-section create form with conditional sections per supplier type.
// Registered as window.Pages.farmerCreate.
// Tweaks: fmCreateType (farmer/middleman/cooperative/agent) · fmCreateState (empty/duplicate/nosource/gps)

const F22 = window.FM;
const Ic22 = window.Icons;

const Field22 = ({ label, req, hint, children, col2 }) => (
  <label className={`fm-field ${col2 ? "col2" : ""}`}>
    <span>{label}{req && <b>*</b>}{hint && <span className="hint"> · {hint}</span>}</span>
    {children}
  </label>
);

const FarmerCreate = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const initType = tweaks?.fmCreateType || "farmer";
  const cstate = tweaks?.fmCreateState || "empty";
  const [type, setType] = useState(initType);
  useEffect(() => { setType(initType); }, [initType]);

  const showDuplicate = cstate === "duplicate";
  const showGps = cstate === "gps";
  const showNoSource = cstate === "nosource" && type === "middleman";

  const SECTIONS = [
    { n: 1, t: "Type" }, { n: 2, t: "Identity" }, { n: 3, t: "Location" },
    { n: 4, t: "Farm profile" }, { n: 5, t: "Groups & tags" },
  ];

  return (
    <div className="page">
      <div className="cr-head">
        <div className="row" style={{ gap: 12, alignItems: "center" }}>
          <IconButton variant="ghost" icon={Ic22.ArrowLeft} onClick={() => go("ADM-PROC-20.html")}/>
          <div className="cr-head-title">
            <h1 className="cr-title">Add farmer</h1>
            <div className="cr-autosave"><span className="cr-save-dot"/>Draft saved locally · recovers on refresh</div>
          </div>
        </div>
        <div className="cr-head-actions">
          <button className="cr-discard" onClick={() => go("ADM-PROC-20.html")}>Discard</button>
          <Button variant="outline">Save draft</Button>
          <Button variant="primary" icon={Ic22.Check} onClick={() => { toast({ title: "Farmer saved", desc: "Routing to profile…" }); go("ADM-PROC-21.html"); }}>Save & continue</Button>
        </div>
      </div>

      {/* Stepper */}
      <div className="fm-stepper">
        {SECTIONS.map((s, i) => (
          <React.Fragment key={s.n}>
            <span className={`fm-step ${i === 0 ? "on" : "done"}`}><span className="n">{s.n}</span>{s.t}</span>
            {i < SECTIONS.length - 1 && <span className="fm-step-line"/>}
          </React.Fragment>
        ))}
      </div>

      <div className="fm-form">
        {/* Section 1 — Type */}
        <div className="fm-section">
          <div className="fm-section-head"><div className="st"><Ic22.Users size={16}/>Supplier type</div><div className="sd">Determines which sections you need to fill in below.</div></div>
          <div className="fm-section-body">
            <div className="fm-typegrid">
              {F22.TYPE_LIST.map(tp => (
                <div key={tp.key} className={`fm-typecard ${type === tp.key ? "on" : ""}`} onClick={() => setType(tp.key)}>
                  <span className="radio"/>
                  <div><div className="tt">{tp.label}</div><div className="td">{tp.desc}</div></div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Section 2 — Identity */}
        <div className="fm-section">
          <div className="fm-section-head"><div className="st"><Ic22.User size={16}/>Identity</div></div>
          <div className="fm-section-body">
            <div className="fm-grid2">
              <Field22 label={type === "farmer" ? "Full name" : "Primary contact name"} req col2>
                <input className="input" placeholder="e.g. Jane Wanjiku" defaultValue={cstate !== "empty" ? "Jane Wanjiku" : ""}/>
              </Field22>
              {type !== "farmer" && (
                <Field22 label="Trading / entity name" col2 hint={type === "cooperative" ? "Registered co-op name" : "Business name"}>
                  <input className="input" placeholder={type === "middleman" ? "e.g. Embu Fresh Traders" : "e.g. Kiriaini Growers SACCO"}/>
                </Field22>
              )}
              <Field22 label="Primary phone" req hint="+256/+254 · unique">
                <input className="input" placeholder="+254 7…" defaultValue={cstate !== "empty" ? "+254 722 905 318" : ""}/>
              </Field22>
              <Field22 label="Alt phone"><input className="input" placeholder="+254 7…"/></Field22>
              <Field22 label="Email"><input className="input" placeholder="name@example.com"/></Field22>
              <Field22 label="NIN" hint="optional, recommended for KYC"><input className="input" placeholder="National ID number"/></Field22>
              <Field22 label="Preferred language">
                <select className="input" defaultValue="English"><option>English</option><option>Kikuyu</option><option>Kiswahili</option><option>Luganda</option></select>
              </Field22>
            </div>
            {showDuplicate && (
              <div className="fm-banner warn" style={{ marginTop: 14, marginBottom: 0 }}><Ic22.Warning size={16} className="bi"/>
                <div>This phone is already registered as <b>Mary Wairimu (F-2731)</b>. Merge, edit that record, or continue with a new record.
                  <div className="row" style={{ gap: 8, marginTop: 8 }}><Button size="sm" variant="outline">Merge</Button><Button size="sm" variant="ghost" onClick={() => go("ADM-PROC-21.html")}>Edit existing</Button></div></div></div>
            )}
          </div>
        </div>

        {/* Conditional — Cooperative details */}
        {type === "cooperative" && (
          <div className="fm-section">
            <div className="fm-section-head"><div className="st"><Ic22.Layers size={16}/>Cooperative details</div><div className="sd">Registration required for KYC (2020 Cooperative Societies Act).</div></div>
            <div className="fm-section-body"><div className="fm-grid2">
              <Field22 label="Registration #" req><input className="input" placeholder="CS/…"/></Field22>
              <Field22 label="Primary contact"><select className="input"><option>Select from contacts…</option><option>Chairperson</option><option>Treasurer</option><option>Secretary</option></select></Field22>
            </div></div>
          </div>
        )}

        {/* Conditional — Source farmers (middleman) */}
        {type === "middleman" && (
          <div className="fm-section">
            <div className="fm-section-head"><div className="st"><Ic22.Users size={16}/>Source farmers</div><div className="sd">Link existing farmer records so origin can be audited.</div></div>
            <div className="fm-section-body">
              <div className="proc-search" style={{ maxWidth: 420, marginBottom: 12 }}><Ic22.Search size={15}/><input className="input" placeholder="Search farmers to link…"/></div>
              <div className="fm-chips">
                {["Peter Kariuki (F-2790)", "James Maina (F-2688)"].map(s => <span key={s} className="fm-chip"><Ic22.User size={12}/>{s}<button className="rm"><Ic22.X size={12}/></button></span>)}
                <button className="fm-chip-add"><Ic22.Plus size={12}/>Link farmer</button>
              </div>
              {showNoSource && (
                <div className="fm-banner warn" style={{ marginTop: 14, marginBottom: 0 }}><Ic22.Warning size={16} className="bi"/><div>Middlemen without source farmers cannot be audited on origin. Add at least one before saving. <span className="muted">(Soft warning — not blocking.)</span></div></div>
              )}
            </div>
          </div>
        )}

        {/* Section 3 — Location */}
        <div className="fm-section">
          <div className="fm-section-head"><div className="st"><Ic22.MapPin size={16}/>Location</div></div>
          <div className="fm-section-body">
            <div className="fm-grid3" style={{ marginBottom: 14 }}>
              <Field22 label="District / County" req><select className="input"><option>Murang'a</option><option>Nyeri</option><option>Embu</option><option>Kirinyaga</option></select></Field22>
              <Field22 label="Parish / Ward"><input className="input" placeholder="e.g. Kangema"/></Field22>
              <Field22 label="Village"><input className="input" placeholder="Village name"/></Field22>
            </div>
            <div className="fm-map"><Ic22.MapPin size={16}/>{showGps ? "GPS captured — 0.7264° S, 37.1503° E · district auto-filled" : "Farm location — drop a pin or capture GPS"}</div>
            <div style={{ marginTop: 10 }}><Button variant="outline" size="sm" icon={Ic22.Crosshair} onClick={() => toast({ title: "GPS captured", desc: "0.7264° S, 37.1503° E" })}>Capture GPS</Button></div>
          </div>
        </div>

        {/* Section 4 — Farm profile */}
        <div className="fm-section">
          <div className="fm-section-head"><div className="st"><Ic22.Leaf size={16}/>Farm profile</div></div>
          <div className="fm-section-body"><div className="fm-grid2">
            <Field22 label="Land size" hint="acres"><input className="input" inputMode="decimal" placeholder="0.0"/></Field22>
            <Field22 label="Existing avocado trees"><input className="input" inputMode="numeric" placeholder="0"/></Field22>
            <Field22 label="Estimated capacity" hint="kg / season, informational"><input className="input" inputMode="numeric" placeholder="0"/></Field22>
            <Field22 label="Current crops"><input className="input" placeholder="Hass, Fuerte, maize…"/></Field22>
          </div></div>
        </div>

        {/* Section 5 — Groups & tags */}
        <div className="fm-section">
          <div className="fm-section-head"><div className="st"><Ic22.Layers size={16}/>Initial groups & tags</div><div className="sd">Optional — place this supplier in groups for broadcast targeting.</div></div>
          <div className="fm-section-body">
            <div className="fm-chips" style={{ marginBottom: 12 }}>
              {F22.GROUPS.slice(0, 2).map(g => <span key={g.id} className="fm-chip"><Ic22.Layers size={12}/>{g.name}<button className="rm"><Ic22.X size={12}/></button></span>)}
              <button className="fm-chip-add"><Ic22.Plus size={12}/>Add to group</button>
            </div>
            <div className="fm-chips">
              <button className="fm-chip-add"><Ic22.Tag size={12}/>Add tag</button>
            </div>
          </div>
        </div>

        <div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 4, marginBottom: 40 }}>
          <Button variant="outline">Save draft</Button>
          <Button variant="primary" icon={Ic22.Check} onClick={() => { toast({ title: "Farmer saved" }); go("ADM-PROC-21.html"); }}>Save & continue</Button>
        </div>
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { farmerCreate: FarmerCreate });
