// ADM-PROC-03 · Create requirement (AMOMS Module 1)
// Admin Web · Procurement Manager / Officer · P0 · 1440×900
// Components: C-109 Form section · C-003 Text input · C-004 Number stepper · C-005 Select
//             C-006 Date picker · C-009 Radio · C-001 Button · C-106 Inline error banner
// Registered as window.Pages.createReq

const Ic3 = window.Icons;
const BUILT_03 = window.BUILT_PAGES;
const KES3 = (n) => "KSh " + (Number(n) || 0).toLocaleString("en-US");

const iso = (d) => d.toISOString().slice(0, 10);
const TODAY_03 = new Date(2026, 4, 12);
const addDays = (base, n) => { const d = new Date(base); d.setDate(d.getDate() + n); return d; };
const prettyDate = (s) => {
  if (!s) return "—";
  const d = new Date(s + "T00:00:00");
  return d.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", year: "numeric" });
};

const PRODUCTS_03 = ["Hass", "Fuerte", "Pinkerton", "Local"];
const RATE_TYPES = [
  { 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" },
];

// ── 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 ──
const Field = ({ label, required, hint, error, children, style }) => (
  <div className="field" style={style}>
    {label && <label className="label">{label}{required && <span className="req">*</span>}</label>}
    {children}
    {error ? <div className="cr-err"><Ic3.Warning size={12} />{error}</div> : hint && <div className="field-hint">{hint}</div>}
  </div>
);

// ── Number stepper (C-004) ──
const Stepper = ({ 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>
  );
};

// ── Radio group (C-009, segmented) ──
const RadioCards = ({ 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>
);

// ── Live preview card (farmer-facing) ──
const PreviewCard = ({ f }) => {
  const hasContent = f.product || f.qty;
  const rateLabel = f.type === "ceiling" ? "up to" : f.type === "floor" ? "from" : "around";
  return (
    <div className="cr-rail">
      <div className="cr-rail-head">
        <Ic3.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-phone">
        <div className="cr-phone-top">
          <span className="cr-brand"><span className="cr-brand-mark"><Ic3.Leaf size={11} /></span>AMOMS</span>
          {f.priority === "urgent" && <span className="badge badge-soil" style={{ fontSize: 10 }}><Ic3.Bolt size={10} />Urgent</span>}
        </div>
        {!hasContent ? (
          <div className="cr-phone-empty">
            <Ic3.Procurement size={26} />
            <div style={{ fontWeight: 600, fontSize: 13 }}>Add product to preview</div>
            <div className="muted" style={{ fontSize: 12 }}>Fill in the form and your broadcast will appear here.</div>
          </div>
        ) : (
          <div className="cr-phone-body">
            <div className="cr-ph-title">New buying request</div>
            <div className="cr-ph-product">{f.product || "—"} avocados{f.spec ? ` · ${f.spec}` : ""}</div>

            <div className="cr-ph-stat">
              <span className="muted">We need</span>
              <b>{f.qty ? Number(f.qty).toLocaleString("en-US") : "—"} kg{f.variance ? ` (±${f.variance}%)` : ""}</b>
            </div>
            <div className="cr-ph-stat">
              <span className="muted">Rate</span>
              <b>{rateLabel} {KES3(f.rate)}/kg</b>
            </div>
            <div className="cr-ph-stat">
              <span className="muted">Deliver between</span>
              <b>{f.start ? prettyDate(f.start).replace(/, \d{4}$/, "") : "—"} – {f.end ? prettyDate(f.end).replace(/, \d{4}$/, "") : "—"}</b>
            </div>
            <div className="cr-ph-cta">
              <span>Respond by {f.deadline ? prettyDate(f.deadline).replace(/^.+?, /, "") : "—"}</span>
            </div>
          </div>
        )}
      </div>
      <div className="cr-rail-note muted">
        <Ic3.Info size={12} />Internal notes &amp; reference code are never shown to farmers.
      </div>
    </div>
  );
};

// ── Page ──
const CreateRequirement = ({ tweaks }) => {
  const toast = useToast();
  const formState = (tweaks && tweaks.formState) || "empty";
  const go = (file) => { if (BUILT_03.includes(file)) window.location.href = file; else toast({ title: `${file.replace(".html", "")} isn't part of this prototype`, desc: "Specced but not built here.", tone: "danger" }); };

  const seed = formState === "empty"
    ? { product: "", spec: "", qty: "", variance: 10, rate: "", type: "ceiling", start: iso(addDays(TODAY_03, 1)), end: iso(addDays(TODAY_03, 8)), deadline: iso(TODAY_03), priority: "normal", notes: "", ref: "" }
    : { product: "Hass", spec: "Min 200g/fruit, grade A, dry matter ≥ 24%", qty: 28000, variance: 10, rate: 95, type: "ceiling", start: iso(addDays(TODAY_03, 3)), end: iso(addDays(TODAY_03, 10)), deadline: iso(addDays(TODAY_03, 1)), priority: "normal", notes: "Prioritise Kangema & Kandara groups — strong last cycle.", ref: "WK3-2026" };

  const [f, setF] = useState(seed);
  const [submitted, setSubmitted] = useState(formState === "errors");
  const [saveLabel, setSaveLabel] = useState(formState === "autosaved" ? "Draft saved · just now" : "");
  const [discardOpen, setDiscardOpen] = useState(false);
  const dirty = useRef(false);
  const saveTimer = useRef(null);

  const set = (key, val) => {
    dirty.current = true;
    setF(prev => {
      const next = { ...prev, [key]: val };
      // Urgent shifts default response deadline to start − 1 day
      if (key === "priority" && val === "urgent") next.deadline = iso(addDays(new Date(next.start + "T00:00:00"), -1));
      // Keep end ≥ start
      if (key === "start" && next.end < val) next.end = iso(addDays(new Date(val + "T00:00:00"), 7));
      return next;
    });
    // Auto-save 1.5s after last keystroke
    setSaveLabel("Saving…");
    clearTimeout(saveTimer.current);
    saveTimer.current = setTimeout(() => setSaveLabel("Draft saved · just now"), 1500);
  };
  useEffect(() => () => clearTimeout(saveTimer.current), []);

  // ── 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 (min 1 kg).";
  if (Number(f.qty) > 1_000_000) errors.qty = "Maximum is 1,000,000 kg.";
  if (f.rate === "" || Number(f.rate) <= 0) errors.rate = "Enter an expected rate.";
  if (!f.start) errors.start = "Pick a delivery start date.";
  else if (f.start < iso(addDays(TODAY_03, 1))) errors.start = "Must be at least tomorrow.";
  if (!f.end) errors.end = "Pick a delivery end date.";
  else if (f.end < f.start) errors.end = "Must be on or after the start date.";
  if (!f.deadline) errors.deadline = "Pick a response deadline.";
  else if (f.deadline < iso(TODAY_03)) errors.deadline = "Cannot be in the past.";
  else if (f.deadline >= f.start) errors.deadline = "Must be before the delivery start.";
  const errorList = Object.entries(errors);
  const startIsToday = f.start === iso(TODAY_03);

  const showErr = (key) => submitted && errors[key];

  const saveDraft = () => { setSaveLabel("Draft saved · just now"); toast({ title: "Draft saved", desc: f.product ? `${f.product} · ${f.qty || 0} kg` : "New requirement" }); };
  const saveContinue = () => {
    setSubmitted(true);
    if (errorList.length) { toast({ title: "Fix the highlighted fields", desc: `${errorList.length} field${errorList.length > 1 ? "s" : ""} need attention`, tone: "danger" }); return; }
    toast({ title: "Draft saved — opening broadcast" });
    go("ADM-PROC-07.html");
  };

  return (
    <div className="page cr-page">
      {/* Header bar */}
      <div className="cr-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => dirty.current ? setDiscardOpen(true) : go("ADM-PROC-02.html")}>
          <Ic3.ChevronLeft size={18} />
        </button>
        <div className="cr-head-title">
          <h1 className="cr-title">New requirement</h1>
          <div className="cr-autosave">
            {saveLabel
              ? <><span className={`cr-save-dot${saveLabel.startsWith("Saving") ? " saving" : ""}`} />{saveLabel}</>
              : <span className="muted">Not saved yet — changes auto-save as you type</span>}
          </div>
        </div>
        <div className="cr-head-actions">
          <button className="cr-discard" onClick={() => setDiscardOpen(true)}>Discard</button>
          <Button variant="outline" icon={Ic3.File} onClick={saveDraft}>Save draft</Button>
          <Button variant="primary" icon={Ic3.Bolt} onClick={saveContinue}>Save &amp; continue to broadcast</Button>
        </div>
      </div>

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

      <div className="cr-grid">
        {/* Left — form */}
        <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 }}>
              <Field label="Product category" required error={showErr("product")}>
                <select className="select" value={f.product} onChange={(e) => set("product", e.target.value)}>
                  <option value="">Select a variety</option>
                  {PRODUCTS_03.map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </Field>
              <Field label="Reference / project code" hint="Optional linkage to upstream planning.">
                <input className="input" placeholder="e.g. WK3-2026" value={f.ref} onChange={(e) => set("ref", e.target.value)} />
              </Field>
            </div>
            <Field label="Product specification" hint="Free-text guidance shown to farmers." style={{ marginTop: 16 }}>
              <textarea className="textarea" placeholder="e.g. Min 200g/fruit, grade A" value={f.spec} onChange={(e) => set("spec", e.target.value)} />
            </Field>
          </FormSection>

          <FormSection n={2} title="Quantity & rate" desc="How much, and the price you're offering.">
            <div className="grid-2" style={{ gap: 16 }}>
              <Field label="Target quantity" required hint="1 – 1,000,000 kg" error={showErr("qty")}>
                <Stepper value={f.qty} onChange={(v) => set("qty", v)} min={0} max={1_000_000} step={500} suffix="kg" placeholder="0" error={showErr("qty")} />
              </Field>
              <Field label="Acceptable variance" hint="Allowed delivery variance (0–50%).">
                <Stepper value={f.variance} onChange={(v) => set("variance", v)} min={0} max={50} step={1} suffix="%" placeholder="10" />
              </Field>
              <Field label="Expected rate" required hint="The maximum rate you're willing to pay." error={showErr("rate")}>
                <Stepper value={f.rate} onChange={(v) => set("rate", v)} min={0} max={100000} step={1} suffix="KSh/kg" placeholder="0.00" error={showErr("rate")} />
              </Field>
              <Field label="Rate type" required>
                <RadioCards value={f.type} onChange={(v) => set("type", v)} options={RATE_TYPES} />
              </Field>
            </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 }}>
              <Field label="Delivery start" required error={showErr("start")}>
                <input type="date" className="input" value={f.start} min={iso(addDays(TODAY_03, 1))} onChange={(e) => set("start", e.target.value)} />
              </Field>
              <Field label="Delivery end" required error={showErr("end")}>
                <input type="date" className="input" value={f.end} min={f.start} onChange={(e) => set("end", e.target.value)} />
              </Field>
              <Field label="Response deadline" required error={showErr("deadline")}>
                <input type="date" className="input" value={f.deadline} min={iso(TODAY_03)} max={f.start} onChange={(e) => set("deadline", e.target.value)} />
              </Field>
            </div>
            {startIsToday && f.priority !== "urgent" && (
              <div className="alert alert-warning" style={{ marginTop: 14 }}>
                <span className="alert-icon"><Ic3.Warning size={16} /></span>
                <div className="alert-body">
                  <div className="alert-title">Same-day delivery needs Urgent priority</div>
                  <div className="alert-desc">A delivery start of today is only allowed for Urgent requirements. Set priority to Urgent or move the start out by a day.</div>
                </div>
              </div>
            )}
            <Field label="Priority" style={{ marginTop: 16, maxWidth: 360 }}>
              <RadioCards 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" },
              ]} />
            </Field>
          </FormSection>

          <FormSection n={4} title="Internal notes" desc="Visible only to the procurement team.">
            <Field>
              <textarea className="textarea" placeholder="Context for your team — sourcing strategy, preferred groups, constraints…" value={f.notes} onChange={(e) => set("notes", e.target.value)} />
            </Field>
          </FormSection>
        </div>

        {/* Right — live preview rail */}
        <div className="cr-side">
          <PreviewCard f={f} />
        </div>
      </div>

      {/* Discard confirm */}
      <Modal open={discardOpen} onClose={() => setDiscardOpen(false)} title="Discard this draft?" sub="Your in-progress changes will be lost."
        footer={<>
          <Button variant="outline" onClick={() => setDiscardOpen(false)}>Keep editing</Button>
          <Button variant="destructive" onClick={() => go("ADM-PROC-02.html")}>Discard draft</Button>
        </>}>
        <div className="muted" style={{ fontSize: 13 }}>This requirement hasn't been broadcast. Discarding deletes the in-progress draft and returns you to the requirement list.</div>
      </Modal>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { createReq: CreateRequirement });
