// ADM-PROC-06 · Edit requirement / new version (AMOMS Module 1)
// Admin Web · Procurement Manager · P0 · 1440×900
// Components: same as ADM-PROC-03 · C-106 Inline error banner · C-108 Confirmation modal
// Registered as window.Pages.editReq

const Ic6 = window.Icons;
const KES6 = (n) => "KSh " + (Number(n) || 0).toLocaleString("en-US");
const iso6 = (d) => d.toISOString().slice(0, 10);
const TODAY_06 = new Date(2026, 4, 12);
const addDays6 = (base, n) => { const d = new Date(base); d.setDate(d.getDate() + n); return d; };
const prettyD6 = (s) => { if (!s) return "—"; return new Date(s + "T00:00:00").toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }); };

const REQ_ID_06 = "PR-2026-0184";
const PRODUCTS_06 = ["Hass", "Fuerte", "Pinkerton", "Local"];
const RATE_TYPES_06 = [
  { v: "ceiling", label: "Ceiling", hint: "Maximum you'll pay" },
  { v: "target",  label: "Target",  hint: "Preferred rate" },
  { v: "floor",   label: "Floor",   hint: "Minimum for premium grade" },
];

// Current persisted values — the baseline we diff against.
const BASELINE_06 = {
  product: "Hass", spec: "Min 200g/fruit, grade A, dry matter ≥ 24%", qty: 28000, variance: 10,
  rate: 95, type: "ceiling", start: iso6(addDays6(TODAY_06, 7)), end: iso6(addDays6(TODAY_06, 14)),
  deadline: iso6(addDays6(TODAY_06, 5)), priority: "normal", notes: "Prioritise Kangema & Kandara groups — strong last cycle.", ref: "WK3-2026",
};

const FIELD_LABELS_06 = {
  product: "Product", spec: "Specification", qty: "Target quantity", variance: "Variance",
  rate: "Expected rate", type: "Rate type", start: "Delivery start", end: "Delivery end",
  deadline: "Response deadline", priority: "Priority", notes: "Internal notes", ref: "Reference",
};
const fmtVal6 = (k, v) => {
  if (v === "" || v == null) return "—";
  if (k === "qty") return Number(v).toLocaleString("en-US") + " kg";
  if (k === "variance") return "±" + v + "%";
  if (k === "rate") return KES6(v) + "/kg";
  if (k === "type") return v[0].toUpperCase() + v.slice(1);
  if (k === "priority") return v[0].toUpperCase() + v.slice(1);
  if (["start", "end", "deadline"].includes(k)) return prettyD6(v);
  return String(v);
};

// ── Form section (C-109) ──
const FormSection = ({ n, title, desc, children }) => (
  <Card style={{ marginBottom: 16 }}>
    <div className="card-head" style={{ alignItems: "center" }}>
      <div className="head-text" style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
        <span className="cr-step">{n}</span>
        <div><div className="card-title">{title}</div>{desc && <div className="card-desc">{desc}</div>}</div>
      </div>
    </div>
    <div className="card-body" style={{ paddingTop: 4 }}>{children}</div>
  </Card>
);

// ── Field wrapper (with optional "Changed" tag) ──
const Field6 = ({ label, required, hint, error, changed, children, style }) => (
  <div className="field" style={style}>
    {label && <label className="label">{label}{required && <span className="req">*</span>}{changed && <span className="cr-changed">Changed</span>}</label>}
    {children}
    {error ? <div className="cr-err"><Ic6.Warning size={12} />{error}</div> : hint && <div className="field-hint">{hint}</div>}
  </div>
);

const Stepper6 = ({ value, onChange, min = 0, max = Infinity, step = 1, suffix, placeholder, error }) => {
  const set = (v) => onChange(Math.max(min, Math.min(max, v)));
  return (
    <div className={`cr-stepper${error ? " err" : ""}`}>
      <button type="button" className="cr-step-btn" onClick={() => set((Number(value) || 0) - step)} aria-label="Decrease">−</button>
      <input className="cr-step-input" inputMode="numeric" placeholder={placeholder} value={value}
        onChange={(e) => onChange(e.target.value === "" ? "" : Number(e.target.value.replace(/[^\d.]/g, "")))} />
      {suffix && <span className="cr-step-suffix">{suffix}</span>}
      <button type="button" className="cr-step-btn" onClick={() => set((Number(value) || 0) + step)} aria-label="Increase">+</button>
    </div>
  );
};

const RadioCards6 = ({ value, onChange, options }) => (
  <div className="cr-radios">
    {options.map(o => (
      <button type="button" key={o.v} className={`cr-radio${value === o.v ? " on" : ""}`} onClick={() => onChange(o.v)}>
        <span className="cr-radio-dot" />
        <span style={{ minWidth: 0 }}>
          <span className="cr-radio-label">{o.label}</span>
          {o.hint && <span className="cr-radio-hint">{o.hint}</span>}
        </span>
      </button>
    ))}
  </div>
);

// ── Changes rail (new-version mode) ──
const ChangesRail = ({ diffs, reason }) => (
  <div className="cr-rail">
    <div className="cr-rail-head"><Ic6.Layers size={14} />This version's changes
      <span className="muted" style={{ fontWeight: 400, fontSize: 11.5, marginLeft: "auto" }}>{diffs.length} field{diffs.length === 1 ? "" : "s"}</span>
    </div>
    {diffs.length === 0 ? (
      <div className="cr-noop">No changes yet. Edit a field to create a new version.</div>
    ) : (
      <div className="cr-rail-body">
        <div className="cr-diff">
          {diffs.map(([k, oldV, newV]) => (
            <div key={k} className="cr-diff-item">
              <div className="cr-diff-label">{FIELD_LABELS_06[k]}</div>
              <div className="cr-diff-vals">
                <span className="cr-diff-old">{fmtVal6(k, oldV)}</span>
                <Ic6.ArrowRight size={12} style={{ color: "var(--muted-foreground)" }} />
                <span className="cr-diff-new">{fmtVal6(k, newV)}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    )}
    <div className="cr-rail-note"><Ic6.Bell size={12} />Existing respondents are notified when you save. {reason ? "Your reason is included in that message." : "Add a reason below — it's shown to them."}</div>
  </div>
);

// ── Farmer preview rail (draft mode) ──
const PreviewRail6 = ({ f }) => {
  const rateLabel = f.type === "ceiling" ? "up to" : f.type === "floor" ? "from" : "around";
  return (
    <div className="cr-rail">
      <div className="cr-rail-head"><Ic6.Eye size={14} />Live preview
        <span className="muted" style={{ fontWeight: 400, fontSize: 11.5, marginLeft: "auto" }}>How farmers see it</span>
      </div>
      <div className="cr-rail-body">
        <div className="cr-diff">
          <div className="cr-diff-item"><div className="cr-diff-label">Product</div><div className="cr-diff-new">{f.product} avocados</div></div>
          <div className="cr-diff-item"><div className="cr-diff-label">We need</div><div className="cr-diff-new">{Number(f.qty || 0).toLocaleString("en-US")} kg (±{f.variance}%)</div></div>
          <div className="cr-diff-item"><div className="cr-diff-label">Rate</div><div className="cr-diff-new">{rateLabel} {KES6(f.rate)}/kg</div></div>
          <div className="cr-diff-item"><div className="cr-diff-label">Deliver between</div><div className="cr-diff-new">{prettyD6(f.start)} – {prettyD6(f.end)}</div></div>
        </div>
      </div>
      <div className="cr-rail-note"><Ic6.Info size={12} />Draft edits save in place — no version bump, no notifications.</div>
    </div>
  );
};

// ── Page ──
const EditRequirement = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const mode = (tweaks && tweaks.editMode) || "newversion";
  const newVersion = mode === "newversion";

  const [f, setF] = useState({ ...BASELINE_06 });
  const [reason, setReason] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [discardOpen, setDiscardOpen] = useState(false);
  const [saveLabel, setSaveLabel] = useState("");
  const saveTimer = useRef(null);

  useEffect(() => { setF({ ...BASELINE_06 }); setReason(""); setSubmitted(false); setSaveLabel(""); }, [mode]);

  const set = (key, val) => {
    setF(prev => {
      const next = { ...prev, [key]: val };
      if (key === "start" && next.end < val) next.end = iso6(addDays6(new Date(val + "T00:00:00"), 7));
      return next;
    });
    if (!newVersion) { setSaveLabel("Saving…"); clearTimeout(saveTimer.current); saveTimer.current = setTimeout(() => setSaveLabel("Draft saved · just now"), 1200); }
  };
  useEffect(() => () => clearTimeout(saveTimer.current), []);

  // Diff against baseline
  const diffs = Object.keys(BASELINE_06)
    .filter(k => String(f[k]) !== String(BASELINE_06[k]))
    .map(k => [k, BASELINE_06[k], f[k]]);
  const changedSet = new Set(diffs.map(d => d[0]));

  // Validation
  const errors = {};
  if (!f.product) errors.product = "Choose a product variety.";
  if (!f.qty || Number(f.qty) < 1) errors.qty = "Enter a target quantity.";
  if (f.rate === "" || Number(f.rate) <= 0) errors.rate = "Enter an expected rate.";
  if (f.end < f.start) errors.end = "Must be on or after the start date.";
  if (f.deadline >= f.start) errors.deadline = "Must be before the delivery start.";
  if (newVersion && !reason.trim()) errors.reason = "A reason is required for a new version.";
  const errorList = Object.entries(errors);
  const showErr = (k) => submitted && errors[k];

  const save = () => {
    setSubmitted(true);
    if (errorList.length) { toast({ title: "Fix the highlighted fields", desc: `${errorList.length} need attention`, tone: "danger" }); return; }
    if (newVersion) {
      if (diffs.length === 0) { toast({ title: "Nothing changed", desc: "Edit a field to create v3.", tone: "danger" }); return; }
      toast({ title: `${REQ_ID_06} · v3 created`, desc: "Respondents are being notified." });
    } else {
      toast({ title: "Draft saved", desc: `${f.product} · ${Number(f.qty || 0).toLocaleString("en-US")} kg` });
    }
    go("ADM-PROC-05.html");
  };

  return (
    <div className="page cr-page">
      {/* Header */}
      <div className="cr-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => (diffs.length || reason) ? setDiscardOpen(true) : go("ADM-PROC-05.html")}>
          <Ic6.ChevronLeft size={18} />
        </button>
        <div className="cr-head-title">
          <h1 className="cr-title">{newVersion ? "New version of " : "Edit requirement "}<span className="mono" style={{ fontWeight: 600 }}>{REQ_ID_06}</span></h1>
          <div className="cr-autosave">
            {newVersion
              ? <span className="muted">Creating v3 · was v2 of 2</span>
              : (saveLabel ? <><span className={`cr-save-dot${saveLabel.startsWith("Saving") ? " saving" : ""}`} />{saveLabel}</> : <span className="muted">Editing draft in place — changes auto-save</span>)}
          </div>
        </div>
        <div className="cr-head-actions">
          <button className="cr-discard" onClick={() => setDiscardOpen(true)}>Discard</button>
          <Button variant="primary" icon={Ic6.Check} onClick={save}>{newVersion ? "Save & notify respondents" : "Save changes"}</Button>
        </div>
      </div>

      {/* New-version banner */}
      {newVersion && (
        <div className="alert" style={{ marginBottom: 16, background: "var(--info-soft)", borderColor: "oklch(from var(--info) l c h / 0.3)" }}>
          <span className="alert-icon" style={{ color: "var(--info)" }}><Ic6.Layers size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">You're creating a new version</div>
            <div className="alert-desc">This requirement is already broadcast. Saving supersedes v2 and notifies the {window.MD.RESPONSES.length} farmers who responded. The old version stays readable in the Versions tab.</div>
          </div>
        </div>
      )}

      {/* Error banner (C-106) */}
      {submitted && errorList.length > 0 && (
        <div className="alert alert-soil" style={{ marginBottom: 16 }}>
          <span className="alert-icon"><Ic6.Warning size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">{errorList.length} field{errorList.length > 1 ? "s" : ""} need attention</div>
            <div className="alert-desc">{errorList.map(([k, v]) => v).slice(0, 3).join("  ·  ")}</div>
          </div>
        </div>
      )}

      <div className="cr-grid">
        <div className="cr-main">
          <FormSection n={1} title="Product details" desc="What you want to buy and any quality guidance.">
            <div className="grid-2" style={{ gap: 16 }}>
              <Field6 label="Product category" required changed={changedSet.has("product")} error={showErr("product")}>
                <select className="select" value={f.product} onChange={(e) => set("product", e.target.value)}>
                  {PRODUCTS_06.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </Field6>
              <Field6 label="Reference / project code" changed={changedSet.has("ref")} hint="Optional linkage to upstream planning.">
                <input className="input" value={f.ref} onChange={(e) => set("ref", e.target.value)} />
              </Field6>
            </div>
            <Field6 label="Product specification" changed={changedSet.has("spec")} hint="Free-text guidance shown to farmers." style={{ marginTop: 16 }}>
              <textarea className="textarea" value={f.spec} onChange={(e) => set("spec", e.target.value)} />
            </Field6>
          </FormSection>

          <FormSection n={2} title="Quantity & rate" desc="How much, and the price you're offering.">
            <div className="grid-2" style={{ gap: 16 }}>
              <Field6 label="Target quantity" required changed={changedSet.has("qty")} hint="1 – 1,000,000 kg" error={showErr("qty")}>
                <Stepper6 value={f.qty} onChange={(v) => set("qty", v)} min={0} max={1000000} step={500} suffix="kg" error={showErr("qty")} />
              </Field6>
              <Field6 label="Acceptable variance" changed={changedSet.has("variance")} hint="Allowed delivery variance (0–50%).">
                <Stepper6 value={f.variance} onChange={(v) => set("variance", v)} min={0} max={50} step={1} suffix="%" />
              </Field6>
              <Field6 label="Expected rate" required changed={changedSet.has("rate")} hint="The maximum rate you're willing to pay." error={showErr("rate")}>
                <Stepper6 value={f.rate} onChange={(v) => set("rate", v)} min={0} max={100000} step={1} suffix="KSh/kg" error={showErr("rate")} />
              </Field6>
              <Field6 label="Rate type" required changed={changedSet.has("type")}>
                <RadioCards6 value={f.type} onChange={(v) => set("type", v)} options={RATE_TYPES_06} />
              </Field6>
            </div>
          </FormSection>

          <FormSection n={3} title="Delivery timeline" desc="When you need it and when farmers must respond by.">
            <div className="grid-3" style={{ gap: 16 }}>
              <Field6 label="Delivery start" required changed={changedSet.has("start")} error={showErr("start")}>
                <input type="date" className="input" value={f.start} onChange={(e) => set("start", e.target.value)} />
              </Field6>
              <Field6 label="Delivery end" required changed={changedSet.has("end")} error={showErr("end")}>
                <input type="date" className="input" value={f.end} min={f.start} onChange={(e) => set("end", e.target.value)} />
              </Field6>
              <Field6 label="Response deadline" required changed={changedSet.has("deadline")} error={showErr("deadline")}>
                <input type="date" className="input" value={f.deadline} max={f.start} onChange={(e) => set("deadline", e.target.value)} />
              </Field6>
            </div>
            <Field6 label="Priority" changed={changedSet.has("priority")} style={{ marginTop: 16, maxWidth: 360 }}>
              <RadioCards6 value={f.priority} onChange={(v) => set("priority", v)} options={[
                { v: "normal", label: "Normal", hint: "Standard broadcast" },
                { v: "urgent", label: "Urgent", hint: "Shows a badge to farmers" },
              ]} />
            </Field6>
          </FormSection>

          <FormSection n={4} title="Internal notes" desc="Visible only to the procurement team.">
            <Field6 changed={changedSet.has("notes")}>
              <textarea className="textarea" value={f.notes} onChange={(e) => set("notes", e.target.value)} />
            </Field6>
          </FormSection>

          {newVersion && (
            <FormSection n={5} title="Reason for this version" desc="Shown to respondents in the version-changed notification.">
              <Field6 required error={showErr("reason")}>
                <textarea className="textarea" placeholder="Why is this version needed? e.g. Raised the rate ceiling to attract more offers." value={reason} onChange={(e) => setReason(e.target.value)} />
              </Field6>
            </FormSection>
          )}
        </div>

        <div className="cr-side">
          {newVersion ? <ChangesRail diffs={diffs} reason={reason} /> : <PreviewRail6 f={f} />}
        </div>
      </div>

      <Modal open={discardOpen} onClose={() => setDiscardOpen(false)} title="Discard your changes?" sub="Edits you've made will be lost."
        footer={<>
          <Button variant="outline" onClick={() => setDiscardOpen(false)}>Keep editing</Button>
          <Button variant="destructive" onClick={() => go("ADM-PROC-05.html")}>Discard</Button>
        </>}>
        <div className="muted" style={{ fontSize: 13 }}>{newVersion ? "No new version will be created and respondents won't be notified." : "Your in-progress edits to this draft will be discarded."}</div>
      </Modal>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { editReq: EditRequirement });
