/* ============================================================
   Media SOP — Người Order screens (Order form, My orders, Nghiệm thu)
   ============================================================ */
const { useState, useEffect } = React;

function fmtDate(s) {
  if (!s) return "—";
  const d = new Date(s);
  return d.toLocaleDateString("vi-VN", { day: "2-digit", month: "2-digit" });
}
function daysLeft(s) {
  const d = new Date(s), t = new Date(2026,4,30);
  return Math.round((d - t) / 86400000);
}
function DeadlinePill({ deadline }) {
  const dl = daysLeft(deadline);
  let cls = "badge-gray", txt = `Còn ${dl} ngày`;
  if (dl < 0) { cls = "badge-red"; txt = `Trễ ${-dl} ngày`; }
  else if (dl === 0) { cls = "badge-red"; txt = "Hôm nay"; }
  else if (dl <= 2) { cls = "badge-amber"; }
  return <Badge cls={cls}><Icon name="clock" size={12} />{txt}</Badge>;
}

// ---------------- Order Form ----------------
function OrderForm() {
  const app = window.useApp();
  const [f, setF] = useState({ title: "", vtype: "", purpose: "", deadline: "", priority: "normal", addons: [], note: "" });
  const [done, setDone] = useState(null);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const toggleAddon = (k) => setF(s => ({ ...s, addons: s.addons.includes(k) ? s.addons.filter(x => x!==k) : [...s.addons, k] }));
  const valid = f.title && f.vtype && f.deadline;

  const submit = () => {
    const order = app.createOrder({ ...f, requester: app.persona.name, dept: app.persona.dept });
    setDone(order);
    setF({ title: "", vtype: "", purpose: "", deadline: "", priority: "normal", addons: [], note: "" });
  };

  if (done) return (
    <div className="content-narrow rise" style={{ maxWidth: 600 }}>
      <div className="card card-pad" style={{ textAlign: "center", padding: "44px 32px" }}>
        <div className="brand-mark" style={{ width: 64, height: 64, borderRadius: 20, margin: "0 auto 18px", background: "linear-gradient(135deg,var(--green),var(--cyan))" }}>
          <Icon name="check" size={32} />
        </div>
        <h2 style={{ fontSize: 24 }}>Đã gửi order thành công!</h2>
        <p className="muted" style={{ fontSize: 14.5, marginTop: 8, lineHeight: 1.5 }}>
          Mã order <b className="mono" style={{ color: "var(--violet-600)" }}>{done.id}</b> đã vào hàng chờ tiếp nhận.
          Thông báo Telegram đã gửi tới Quản lý &amp; Lead Editor.
        </p>
        <div className="card" style={{ background: "var(--violet-50)", border: "1px solid var(--violet-100)", padding: 16, margin: "20px 0", textAlign: "left", borderRadius: 14 }}>
          <div className="row between"><span className="muted" style={{ fontSize: 13 }}>Ấn phẩm</span><b style={{ fontSize: 13.5 }}>{done.title}</b></div>
          <div className="divider" style={{ margin: "10px 0" }} />
          <div className="row between"><span className="muted" style={{ fontSize: 13 }}>Loại · Deadline</span><span className="row" style={{ gap: 8 }}><VChip vtype={done.vtype} /><DeadlinePill deadline={done.deadline} /></span></div>
        </div>
        <div className="row" style={{ justifyContent: "center", gap: 10 }}>
          <Btn variant="ghost" icon="inbox" onClick={() => app.go("orders")}>Xem order của tôi</Btn>
          <Btn icon="plus" onClick={() => setDone(null)}>Tạo order khác</Btn>
        </div>
      </div>
    </div>
  );

  return (
    <div className="content-narrow" style={{ maxWidth: 760 }}>
      <div className="card card-pad rise">
        <div className="card-h">
          <div className="brand-mark" style={{ width: 40, height: 40 }}><Icon name="order" size={20} /></div>
          <div>
            <h3>Form yêu cầu sản phẩm Media</h3>
            <div className="sub">Bước 1 · Điền thông tin — hệ thống sẽ tự thông báo cho Quản lý &amp; Lead</div>
          </div>
        </div>

        <div className="field">
          <label>Tên ấn phẩm / sản phẩm <span style={{ color: "var(--red)" }}>*</span></label>
          <input className="input" placeholder="VD: Recap Hội nghị Đối tác Q2" value={f.title} onChange={e => set("title", e.target.value)} />
        </div>

        <div className="field">
          <label>Loại sản phẩm <span style={{ color: "var(--red)" }}>*</span></label>
          <div className="opt-grid" style={{ gridTemplateColumns: "1fr 1fr" }}>
            {Object.values(VIDEO_TYPES).map(v => (
              <div key={v.code} className={"opt" + (f.vtype === v.code ? " sel" : "")} onClick={() => set("vtype", v.code)}>
                <span className={"vchip " + v.cls} style={{ flex: "0 0 auto" }}>{v.code}</span>
                <div style={{ minWidth: 0 }}>
                  <div className="opt-title">{v.name}</div>
                  <div className="opt-desc">{v.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="field">
          <label>Mục đích sử dụng</label>
          <textarea className="textarea" placeholder="Đăng ở đâu, dùng cho việc gì, yêu cầu đặc biệt…" value={f.purpose} onChange={e => set("purpose", e.target.value)} />
        </div>

        <div className="grid g-2" style={{ gap: 18 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Deadline <span style={{ color: "var(--red)" }}>*</span></label>
            <input type="date" className="input" value={f.deadline} onChange={e => set("deadline", e.target.value)} />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Mức ưu tiên</label>
            <div className="row wrap" style={{ gap: 8, paddingTop: 4 }}>
              {Object.values(PRIORITIES).map(p => (
                <button key={p.key} onClick={() => set("priority", p.key)}
                  className={"badge " + (f.priority === p.key ? p.cls : "badge-gray")}
                  style={{ padding: "7px 13px", fontSize: 13, cursor: "pointer", outline: f.priority === p.key ? "2px solid var(--violet-400)" : "none", outlineOffset: 1 }}>
                  {p.label}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="divider" />

        <div className="field" style={{ marginBottom: 0 }}>
          <label>Add-on (tuỳ chọn)</label>
          <div className="opt-grid" style={{ gridTemplateColumns: "1fr 1fr" }}>
            {Object.values(ADDONS).map(a => (
              <div key={a.key} className={"opt" + (f.addons.includes(a.key) ? " sel" : "")} onClick={() => toggleAddon(a.key)}>
                <div className="opt-radio" style={{ borderRadius: 6 }}>{f.addons.includes(a.key) && <Icon name="check" size={12} color="var(--violet-600)" />}</div>
                <div><div className="opt-title">{a.label}</div><div className="opt-desc">{a.note}</div></div>
              </div>
            ))}
          </div>
        </div>

        <div className="divider" />
        <div className="row between">
          <span className="hint" style={{ fontSize: 12.5 }}><Icon name="send" size={13} style={{ verticalAlign: -2 }} /> Gửi xong sẽ tự thông báo Telegram tới Quản lý &amp; Lead Editor</span>
          <Btn icon="send" disabled={!valid} onClick={submit}>Gửi order</Btn>
        </div>
      </div>
    </div>
  );
}

// ---------------- My Orders (requester view) ----------------
function MyOrders() {
  const app = window.useApp();
  const [accept, setAccept] = useState(null);
  const mine = app.orders.filter(o => o.requester === app.persona.name);
  const groups = [
    { key: "active", label: "Đang xử lý", items: mine.filter(o => !["done"].includes(o.stage) && o.stage !== "review") },
    { key: "review", label: "Chờ bạn nghiệm thu", items: mine.filter(o => o.stage === "review") },
    { key: "done", label: "Đã hoàn tất", items: mine.filter(o => o.stage === "done") },
  ];

  if (!mine.length) return <Empty icon="inbox" title="Chưa có order nào" desc="Tạo yêu cầu sản phẩm media đầu tiên của bạn." action={<Btn icon="plus" onClick={() => app.go("new")}>Tạo order</Btn>} />;

  return (
    <div className="content-narrow">
      {groups.map(g => g.items.length > 0 && (
        <div key={g.key} style={{ marginBottom: 26 }}>
          <div className="row" style={{ gap: 9, marginBottom: 12 }}>
            <h3 style={{ fontSize: 15 }}>{g.label}</h3>
            <span className="badge badge-violet">{g.items.length}</span>
            {g.key === "review" && <span className="badge badge-amber" style={{ marginLeft: -2 }}><Icon name="alert" size={12} />Cần hành động</span>}
          </div>
          <div className="grid g-2">
            {g.items.map(o => (
              <div key={o.id} className="card card-pad rise" style={{ padding: 18 }}>
                <div className="row between" style={{ marginBottom: 10 }}>
                  <span className="row" style={{ gap: 7 }}><VChip vtype={o.vtype} /><span className="mono muted" style={{ fontSize: 11.5 }}>{o.id}</span></span>
                  <PriorityBadge p={o.priority} />
                </div>
                <div style={{ fontWeight: 700, fontSize: 15.5, marginBottom: 6, textWrap: "pretty" }}>{o.title}</div>
                <div className="muted" style={{ fontSize: 13, lineHeight: 1.4, marginBottom: 12, minHeight: 18 }}>{o.purpose}</div>
                <div className="row between" style={{ marginBottom: 12 }}>
                  <StageBadge stage={o.stage} />
                  <DeadlinePill deadline={o.deadline} />
                </div>
                {o.editorId && (
                  <div className="row" style={{ gap: 8, paddingTop: 10, borderTop: "1px dashed var(--line-2)" }}>
                    <Avatar name={app.editorById(o.editorId).name} color={app.editorById(o.editorId).color} size={26} />
                    <span style={{ fontSize: 12.5, fontWeight: 600 }}>{app.editorById(o.editorId).name}</span>
                    {o.estimateHours && <span className="badge badge-gray" style={{ marginLeft: "auto" }}><Icon name="clock" size={11} />{o.estimateHours}h</span>}
                  </div>
                )}
                {o.stage === "review" && (
                  <Btn block icon="star" onClick={() => setAccept(o)} style={{ marginTop: 12 }}>Nghiệm thu &amp; đánh giá</Btn>
                )}
                {o.stage === "done" && o.rating && (
                  <div className="row between" style={{ marginTop: 12, paddingTop: 10, borderTop: "1px dashed var(--line-2)" }}>
                    <Stars value={o.rating} size={15} />
                    <Badge cls={o.deadlineMet ? "badge-green" : "badge-red"}>{o.deadlineMet ? "Đúng hạn" : "Trễ hạn"}</Badge>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      ))}
      {accept && <AcceptModal order={accept} onClose={() => setAccept(null)} />}
    </div>
  );
}

// ---------------- Nghiệm thu modal ----------------
function AcceptModal({ order, onClose }) {
  const app = window.useApp();
  const [rating, setRating] = useState(0);
  const [onTime, setOnTime] = useState(daysLeft(order.deadline) >= 0);
  const ed = app.editorById(order.editorId);

  const submit = () => {
    app.acceptOrder(order.id, rating, onTime);
    onClose();
  };

  return (
    <Modal title="Nghiệm thu sản phẩm" sub={`Bước 5 · ${order.id}`} icon="checkCircle" onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>Huỷ</Btn><Btn icon="check" disabled={!rating} onClick={submit}>Xác nhận nghiệm thu</Btn></>}>
      <div className="card" style={{ background: "var(--surface-2)", padding: 16, borderRadius: 14, marginBottom: 20 }}>
        <div className="row" style={{ gap: 9, marginBottom: 8 }}><VChip vtype={order.vtype} /><b style={{ fontSize: 15 }}>{order.title}</b></div>
        <div className="row" style={{ gap: 8 }}>
          <Avatar name={ed.name} color={ed.color} size={24} />
          <span className="muted" style={{ fontSize: 13 }}>Thực hiện bởi <b style={{ color: "var(--ink)" }}>{ed.name}</b></span>
        </div>
        {order.finalLink && <div className="row" style={{ gap: 7, marginTop: 10, fontSize: 12.5, color: "var(--violet-600)", fontWeight: 600 }}><Icon name="link" size={14} /><span className="mono">{order.finalLink}</span></div>}
      </div>

      <div className="field">
        <label>Đánh giá chất lượng (sao)</label>
        <div className="row" style={{ gap: 14 }}>
          <Stars value={rating} size={34} onChange={setRating} />
          <span className="muted" style={{ fontSize: 13 }}>{["", "Chưa đạt", "Cần sửa nhiều", "Tạm ổn", "Tốt", "Xuất sắc"][rating]}</span>
        </div>
        <div className="hint">Tỉ lệ sản phẩm ≥ 4 sao được tính vào Điểm chất lượng của editor.</div>
      </div>

      <div className="field" style={{ marginBottom: 0 }}>
        <label>Điểm Deadline</label>
        <div className="opt-grid" style={{ gridTemplateColumns: "1fr 1fr" }}>
          <div className={"opt" + (onTime ? " sel" : "")} onClick={() => setOnTime(true)}>
            <div className="opt-radio">{onTime && <span style={{ width: 9, height: 9, borderRadius: 50, background: "var(--violet-500)" }} />}</div>
            <div><div className="opt-title">Đúng deadline</div><div className="opt-desc">Giao đúng/sớm hạn</div></div>
          </div>
          <div className={"opt" + (!onTime ? " sel" : "")} onClick={() => setOnTime(false)}>
            <div className="opt-radio">{!onTime && <span style={{ width: 9, height: 9, borderRadius: 50, background: "var(--violet-500)" }} />}</div>
            <div><div className="opt-title">Trễ deadline</div><div className="opt-desc">Giao sau hạn</div></div>
          </div>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { OrderForm, MyOrders, fmtDate, daysLeft, DeadlinePill });
