/* global React, I, UI */
// =============== ตัวกรองวันที่ (ใช้ร่วมทุกหน้าเอกสาร) ===============
// โหมด: วันนี้ / สัปดาห์นี้ / เดือนนี้ / ทั้งหมด / กำหนดเอง
const { useState: useStateDF, useRef: useRefDF, useEffect: useEffectDF } = React;

(function() {
  const TH_M = { "ม.ค.": 1, "ก.พ.": 2, "มี.ค.": 3, "เม.ย.": 4, "พ.ค.": 5, "มิ.ย.": 6, "ก.ค.": 7, "ส.ค.": 8, "ก.ย.": 9, "ต.ค.": 10, "พ.ย.": 11, "ธ.ค.": 12 };

  function toISO(d) {
    if (!d) return null;
    const s = String(d).trim();
    if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;            // ISO อยู่แล้ว
    const m = /^(\d{1,2})\s+(\S+)\s+(\d{4})$/.exec(s);       // "21 พ.ค. 2569"
    if (!m || !TH_M[m[2]]) return null;
    const y = parseInt(m[3], 10) > 2400 ? parseInt(m[3], 10) - 543 : parseInt(m[3], 10);
    return `${y}-${String(TH_M[m[2]]).padStart(2, "0")}-${String(m[1]).padStart(2, "0")}`;
  }

  function today() { return (window.DeliveryStore && window.DeliveryStore.todayStr()) || "2026-05-22"; }

  function range(mode, from, to) {
    const t = today();
    if (mode === "today") return [t, t];
    if (mode === "week") {
      const d = new Date(t + "T00:00:00");
      const day = (d.getDay() + 6) % 7;          // จันทร์ = 0
      const start = new Date(d); start.setDate(d.getDate() - day);
      const end = new Date(start); end.setDate(start.getDate() + 6);
      return [start.toISOString().slice(0, 10), end.toISOString().slice(0, 10)];
    }
    if (mode === "month") return [t.slice(0, 7) + "-01", t.slice(0, 7) + "-31"];
    if (mode === "custom") return [from || "0000-01-01", to || "9999-12-31"];
    return null; // all
  }

  // filter = { mode, from, to } · dateStr = วันที่ของเอกสาร (ไทยหรือ ISO)
  function match(filter, dateStr) {
    if (!filter || filter.mode === "all" || !filter.mode) return true;
    const iso = toISO(dateStr);
    if (!iso) return true; // อ่านวันที่ไม่ออก ไม่ตัดทิ้ง
    const r = range(filter.mode, filter.from, filter.to);
    if (!r) return true;
    return iso >= r[0] && iso <= r[1];
  }

  const MODE_LABEL = { all: "ทั้งหมด", today: "วันนี้", week: "สัปดาห์นี้", month: "เดือนนี้", custom: "กำหนดเอง" };

  window.DocDates = { toISO, today, range, match, MODE_LABEL };
})();

// ---------- ปุ่มตัวกรอง + ป็อปโอเวอร์ ----------
function DateFilter({ value, onChange, size = "sm" }) {
  const [open, setOpen] = useStateDF(false);
  const v = value || { mode: "all" };
  const L = window.DocDates.MODE_LABEL;
  const active = v.mode && v.mode !== "all";

  const pick = (mode) => {
    if (mode === "custom") { onChange({ mode: "custom", from: v.from || window.DocDates.today(), to: v.to || window.DocDates.today() }); return; }
    onChange({ mode });
    setOpen(false);
  };

  return (
    <div style={{position: "relative"}}>
      <button className={`btn ${size} ${active ? "primary" : ""}`} onClick={() => setOpen(o => !o)}>
        <I.filter size={13} className="icon"/>
        ตัวกรอง{active ? `: ${L[v.mode]}` : ""}
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{position: "fixed", inset: 0, zIndex: 70}}></div>
          <div style={{position: "absolute", top: "calc(100% + 6px)", right: 0, width: 250, zIndex: 71,
            background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 10,
            boxShadow: "var(--shadow-lg)", padding: 8}}>
            <div style={{fontSize: 10.5, color: "var(--ink-3)", padding: "2px 6px 6px", fontWeight: 600, letterSpacing: "0.04em"}}>กรองตามวันที่เอกสาร</div>
            <div style={{display: "flex", flexDirection: "column", gap: 2}}>
              {["today", "week", "month", "all", "custom"].map(mode => (
                <button key={mode} className="btn sm" onClick={() => pick(mode)}
                  style={{justifyContent: "flex-start", border: "none", background: v.mode === mode ? "var(--surface-3)" : "transparent", fontWeight: v.mode === mode ? 600 : 400}}>
                  {v.mode === mode ? <I.check size={12} className="icon"/> : <span style={{width: 12, display: "inline-block"}}></span>}
                  {L[mode]}
                </button>
              ))}
            </div>
            {v.mode === "custom" && (
              <div style={{marginTop: 8, padding: 8, borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 6}}>
                <div className="field"><label style={{fontSize: 10.5}}>ตั้งแต่</label>
                  <input className="input" type="date" style={{height: 30, fontSize: 12}} value={v.from || ""} onChange={e => onChange({ ...v, from: e.target.value })}></input>
                </div>
                <div className="field"><label style={{fontSize: 10.5}}>ถึง</label>
                  <input className="input" type="date" style={{height: 30, fontSize: 12}} value={v.to || ""} onChange={e => onChange({ ...v, to: e.target.value })}></input>
                </div>
                <button className="btn sm primary" onClick={() => setOpen(false)}>ใช้ช่วงนี้</button>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}

window.DateFilter = DateFilter;
