/* ============================================================
   repair.jsx — instrument repair / maintenance request log
   (FR-BM-002). Simple workflow: แจ้ง → กำลังซ่อม → เสร็จ.
   Shared FR header + standard footer. Persists to localStorage
   and auto-syncs the instrument's operational status.
   ============================================================ */
const RP_KEY = 'labinstrument.repair.v1';
const RP_STATUS = [
  { key: 'open',  label: 'แจ้งซ่อม',   tone: 'warn',   op: 'repair' },
  { key: 'wip',   label: 'กำลังซ่อม',  tone: 'danger', op: 'down' },
  { key: 'done',  label: 'เสร็จ',      tone: 'ok',     op: 'up' },
];
const RP_BY_KEY = Object.fromEntries(RP_STATUS.map(s => [s.key, s]));

function loadRP() { try { return JSON.parse(localStorage.getItem(RP_KEY)) || {}; } catch (e) { return {}; } }

/* compute an instrument's operational status from its repair rows:
   any 'wip' → down · else any 'open' → repair · else up */
function opFromRows(rows) {
  if (!rows || !rows.length) return 'up';
  if (rows.some(r => r.status === 'wip')) return 'down';
  if (rows.some(r => r.status === 'open')) return 'repair';
  return 'up';
}

/* workflow stepper: แจ้งซ่อม → กำลังซ่อม → เสร็จ */
function RepairFlow({ rows }) {
  const active = (rows || []).find(r => r.status !== 'done');
  const latest = (rows || [])[0];
  const cur = active ? active.status : (latest ? 'done' : null);
  const idx = cur === 'open' ? 0 : cur === 'wip' ? 1 : cur === 'done' ? 2 : -1;
  const steps = [
    { key: 'open', label: 'แจ้งซ่อม', sub: 'รับเรื่อง · งดใช้', icon: I.bell },
    { key: 'wip', label: 'กำลังซ่อม', sub: 'ช่างดำเนินการ', icon: I.wrench },
    { key: 'done', label: 'เสร็จ', sub: 'ทวนสอบ · พร้อมใช้', icon: I.check },
  ];
  return (
    <div className="rp-flow tl-noprint">
      <div className="rp-flow-title">ขั้นตอนงานซ่อม{idx === -1 ? ' · ยังไม่มีรายการแจ้งซ่อม' : ''}</div>
      <div className="rp-flow-steps">
        {steps.map((s, i) => {
          const state = idx === -1 ? 'idle' : i < idx ? 'done' : i === idx ? 'current' : 'todo';
          return (
            <React.Fragment key={s.key}>
              <div className={`rp-step ${state}`}>
                <span className="rp-step-dot"><s.icon size={17} /></span>
                <span className="rp-step-tx"><b>{i + 1}. {s.label}</b><span>{s.sub}</span></span>
              </div>
              {i < steps.length - 1 && <span className={`rp-step-bar${i < idx ? ' done' : ''}`} />}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

function RepairLog({ instruments, onSetStatus, go }) {
  const [store, setStore] = useState(loadRP);
  const [code, setCode] = useState(instruments[0] ? instruments[0].code : '');

  const inst = instruments.find(i => i.code === code) || instruments[0];
  const meta = inst ? window.instrumentMeta(inst) : {};
  const rows = (inst && store[inst.code]) || [];

  // installation location — referenced to the 7 lab departments
  const locOptions = Object.entries(DEPT_META).map(([name, m]) => ({ value: deptLoc(name), label: deptLoc(name) }));
  const defaultLoc = inst ? deptLoc(inst.dept) : '';
  const locValue = (inst && store['loc:' + inst.code]) || defaultLoc;
  const setLoc = (v) => { const next = { ...store, ['loc:' + inst.code]: v }; persist(next); };
  // responsible person follows the selected department location
  const locDept = Object.keys(DEPT_META).find(name => deptLoc(name) === locValue) || (inst && inst.dept);
  const ownerVal = (window.DEPT_OWNER || {})[locDept] || meta.owner;

  const persist = (next) => { setStore(next); try { localStorage.setItem(RP_KEY, JSON.stringify(next)); } catch (e) {} };

  // mutate rows for current instrument + sync instrument op-status
  const mutate = (fn, syncRow) => {
    if (!inst) return;
    const next = { ...store };
    const arr = (next[inst.code] || []).map(r => ({ ...r }));
    fn(arr);
    next[inst.code] = arr;
    persist(next);
    const op = opFromRows(arr);
    if (op !== meta.op.key) onSetStatus(inst.code, op);
    if (syncRow && window.Backend && window.Backend.mode === 'gas') {
      window.Backend.rowUpsert('Repairs', { ...syncRow, code: inst.code }, { action: 'repair', code: inst.code, target: inst.type }).catch(function () {});
    }
  };

  const blankRow = () => ({ id: Date.now() + '' + Math.floor(Math.random() * 1e4), date: new Date().toLocaleDateString('en-CA'), problem: '', fix: '', result: '', note: '', by: '', status: 'open' });
  const addRow = () => { const r = blankRow(); mutate(arr => arr.unshift(r), r); };
  const setField = (id, field, val) => mutate(arr => { const r = arr.find(x => x.id === id); if (r) { r[field] = val; } }, { id, [field]: val });
  const removeRow = (id) => {
    mutate(arr => { const i = arr.findIndex(x => x.id === id); if (i >= 0) arr.splice(i, 1); });
    if (window.Backend && window.Backend.mode === 'gas') window.Backend.rowDelete('Repairs', id, { action: 'repair_delete' }).catch(function () {});
  };

  // lab-wide open repairs (across all instruments)
  const openQueue = useMemo(() => {
    const list = [];
    Object.entries(store).forEach(([c, rs]) => {
      if (c.startsWith('loc:') || !Array.isArray(rs)) return;
      const inst = instruments.find(i => i.code === c); if (!inst) return;
      const active = (rs || []).filter(r => r.status !== 'done');
      if (active.length) list.push({ inst, rows: rs, active });
    });
    return list.sort((a, b) => (a.active[0].status === 'wip' ? -1 : 1));
  }, [store, instruments]);

  const doPrint = () => {
    document.body.classList.add('printing-repair');
    const cleanup = () => { document.body.classList.remove('printing-repair'); window.removeEventListener('afterprint', cleanup); };
    window.addEventListener('afterprint', cleanup);
    setTimeout(() => window.print(), 60);
  };

  const fmt = (iso) => iso ? window.fmtDateFull(iso) : '';
  const idRows = inst ? [
    ['1. ชื่อเครื่องมือ', inst.type || '-'],
    ['2. รหัสเครื่องมือ', inst.code, true],
    ['3. หมายเลขครุภัณฑ์', inst.asset && inst.asset !== '-' ? inst.asset : '-'],
    ['4. หมายเลขเครื่อง (S/N)', inst.serial && inst.serial !== '-' ? inst.serial : '-'],
    ['5. บริษัทผู้ผลิต', inst.brand || '-'],
    ['6. รุ่น / Model', inst.model && inst.model !== '-' ? inst.model : '-'],
    ['7. สถานที่ติดตั้ง', locValue || '-'],
    ['8. ผู้รับผิดชอบ', ownerVal || '-'],
  ] : [];

  const printRows = Math.max(6, rows.length);

  return (
    <div className="enter">
      {/* lab-wide open-repair queue (not printed) */}
      <div className="rp-queue tl-noprint">
        <div className="rp-queue-head">
          <div style={{ whiteSpace: 'nowrap' }}>
            <b>งานซ่อมที่ค้างอยู่</b>
            <span className="muted" style={{ marginLeft: 8, fontSize: 13 }}>{openQueue.length} เครื่อง</span>
          </div>
          <button className="btn btn-primary btn-sm" onClick={addRow}><I.wrench size={15} /> แจ้งซ่อมเครื่องนี้</button>
        </div>
        {openQueue.length === 0 ? (
          <div className="rp-queue-empty"><I.check size={16} /> ไม่มีงานซ่อมค้าง — เครื่องมือทุกเครื่องพร้อมใช้งาน</div>
        ) : (
          <div className="rp-queue-list">
            {openQueue.map(({ inst: qi, active }) => {
              const st = RP_BY_KEY[active[0].status];
              return (
                <button key={qi.code} className={`rp-chip${qi.code === code ? ' on' : ''}`} onClick={() => setCode(qi.code)}>
                  <span className={`pill ${st.tone}`} style={{ fontSize: 11 }}><span className="dot"></span>{st.label}</span>
                  <span className="rp-chip-name">{qi.type}</span>
                  <span className="code rp-chip-code">{qi.code}</span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* controls */}
      <div className="tl-bar tl-noprint">
        <div className="fld">
          <label>เลือกเครื่องมือ</label>
          <select className="select" style={{ minWidth: 320 }} value={code} onChange={e => setCode(e.target.value)}>
            {instruments.map(i => <option key={i.code} value={i.code}>{i.code} · {i.type}</option>)}
          </select>
        </div>
        <div className="fld">
          <label>สถานที่ติดตั้ง (แผนก)</label>
          <select className="select" style={{ minWidth: 200 }} value={locValue} onChange={e => setLoc(e.target.value)}>
            {locOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>
        <div style={{ flex: 1 }} />
        <button className="btn" onClick={addRow}><I.plus size={16} /> เพิ่มรายการแจ้งซ่อม</button>
        <button className="btn btn-primary" onClick={doPrint}><I.download size={16} /> พิมพ์ฟอร์ม</button>
      </div>

      {/* workflow stepper (shows where this instrument's latest request stands) */}
      <RepairFlow rows={rows} />

      <div className="rp-hint tl-noprint">
        <I.wrench size={15} />
        <span>เปลี่ยนสถานะแต่ละรายการได้ที่คอลัมน์ <b>"สถานะ"</b> (ขวาสุดของตาราง): <b className="rp-hint-warn">แจ้งซ่อม</b> → <b className="rp-hint-danger">กำลังซ่อม</b> → <b className="rp-hint-ok">เสร็จ</b> — เมื่อเลือก "เสร็จ" เครื่องจะกลับมาสถานะ "ใช้งานได้" โดยอัตโนมัติ</span>
      </div>

      {/* printable sheet */}
      <div className="tl-sheetwrap">
        <div className="repair-sheet">
          <LabDocHeader docNo="FR-BM-002" line2={`ทบทวนล่าสุด ${fmtDateFull(TODAY.toISOString().slice(0,10))}`} />
          <div className="rp-band">แบบบันทึกการแจ้งซ่อม / ซ่อมบำรุงเครื่องมือ</div>

          {/* identity block — 8 fields */}
          <div className="rp-id">
            {idRows.map(([k, v, mono], i) => (
              <div className="rp-id-row" key={i}>
                <span className="rp-id-k">{k}</span>
                <span className={`rp-id-v${mono ? ' code' : ''}`}>{v}</span>
              </div>
            ))}
          </div>

          {/* repair log table */}
          <table className="rp-tbl">
            <thead>
              <tr>
                <th style={{ width: 40 }}>ลำดับ</th>
                <th style={{ width: 104 }}>วันเดือนปี</th>
                <th>อาการ / ปัญหาที่พบ</th>
                <th>การแก้ไขเบื้องต้น / โดยช่าง</th>
                <th style={{ width: 150 }}>ผลการแก้ไข</th>
                <th style={{ width: 112 }}>หมายเหตุ</th>
                <th style={{ width: 104 }}>ผู้บันทึก</th>
                <th style={{ width: 104 }} className="rp-stcol">สถานะ</th>
              </tr>
            </thead>
            <tbody>
              {Array.from({ length: printRows }, (_, i) => rows[i]).map((r, i) => r ? (
                <tr key={r.id}>
                  <td className="rp-c-num">{i + 1}</td>
                  <td><input type="date" className="rp-date" value={r.date} onChange={e => setField(r.id, 'date', e.target.value)} /><span className="rp-date-print">{fmt(r.date)}</span></td>
                  <td><textarea rows={1} value={r.problem} onChange={e => setField(r.id, 'problem', e.target.value)} /></td>
                  <td><textarea rows={1} value={r.fix} onChange={e => setField(r.id, 'fix', e.target.value)} /></td>
                  <td><textarea rows={1} value={r.result} onChange={e => setField(r.id, 'result', e.target.value)} /></td>
                  <td><textarea rows={1} value={r.note} onChange={e => setField(r.id, 'note', e.target.value)} /></td>
                  <td><input value={r.by} onChange={e => setField(r.id, 'by', e.target.value)} /></td>
                  <td className="rp-stcol">
                    <select className={`rp-status rp-status-${RP_BY_KEY[r.status].tone}`} value={r.status} onChange={e => setField(r.id, 'status', e.target.value)}>
                      {RP_STATUS.map(s => <option key={s.key} value={s.key}>{s.label}</option>)}
                    </select>
                    <span className="rp-status-print">{RP_BY_KEY[r.status].label}</span>
                    <button className="rp-del tl-noprint" title="ลบรายการ" onClick={() => removeRow(r.id)}><I.close size={13} /></button>
                  </td>
                </tr>
              ) : (
                <tr key={'e' + i}><td className="rp-c-num">{i + 1}</td><td></td><td></td><td></td><td></td><td></td><td></td><td className="rp-stcol"></td></tr>
              ))}
            </tbody>
          </table>

          <div className="ts-notes">
            <b>หมายเหตุ :</b> 1. เมื่อพบเครื่องมือชำรุด/ไม่พร้อมใช้งาน ให้ติดป้าย "งดใช้" และบันทึกการแจ้งซ่อมทันที &nbsp; 2. เมื่อซ่อมเสร็จและทวนสอบผลใช้งานได้ ให้เปลี่ยนสถานะเป็น "เสร็จ" เครื่องจึงกลับมาพร้อมใช้งาน
          </div>
          <div className="ts-review">ผู้ทบทวน / หัวหน้าหน่วย : ............................................. วันที่ ........./........./.........</div>
          <div className="lbl-foot">(เอกสารสำเนาอิเล็กทรอนิกส์ถูกควบคุมให้เป็นปัจจุบันเมื่ออยู่บนเว็บไซต์เท่านั้น)</div>
        </div>
      </div>
    </div>
  );
}
window.RepairLog = RepairLog;
window.repairOpFor = function (code) { const s = loadRP(); return opFromRows(s[code]); };
