/* ============================================================
   repair.jsx — instrument repair / maintenance request log
   (FR-BM-002). Simple workflow: แจ้ง → กำลังซ่อม → เสร็จ.
   Shared FR header + standard footer. Rows live in window.Repairs
   (sync.js: localStorage + GAS 'Repairs' tab, shared by every
   device) and auto-sync the instrument's operational status.
   ============================================================ */
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]));
// column names for the audit row's "what changed" text
const RP_FIELD_LABEL = { date: 'วันเดือนปี', problem: 'อาการ/ปัญหาที่พบ', fix: 'การแก้ไขเบื้องต้น/โดยช่าง', result: 'ผลการแก้ไข', note: 'หมายเหตุ', by: 'ผู้บันทึก' };

/* 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';
}

/* a form too long for one sheet goes on paper as whole sheets, each with its own header and page
   number; left alone the browser only carries the table on. Built as printing starts (the button
   or Ctrl+P) and gone after. A form that fits one sheet is not touched */
const RP_SHEET_FITS = 992, RP_SHEET_ROOM = 940;   // px of form on one A4 landscape sheet at the print zoom
function rpSheetsDone() {
  document.querySelectorAll('.rp-print-pages').forEach(el => el.remove());
  document.body.classList.remove('rp-paged');
}
function rpSheetsForPrint() {
  rpSheetsDone();
  const sheet = document.querySelector('.repair-sheet');
  if (!sheet || !document.body.classList.contains('printing-repair')) return;
  document.body.classList.add('rp-measure');
  const box = sheet.getBoundingClientRect(), tbl = sheet.querySelector('.rp-tbl').getBoundingClientRect();
  const foot = sheet.querySelector('.lbl-foot').getBoundingClientRect().height;
  const head = tbl.top - box.top + sheet.querySelector('.rp-tbl thead').getBoundingClientRect().height;
  const rows = [...sheet.querySelectorAll('.rp-tbl tbody tr')].map(tr => tr.getBoundingClientRect().height);
  document.body.classList.remove('rp-measure');
  if (box.height <= RP_SHEET_FITS) return;
  const pages = [];
  let cur = [], used = head + foot;
  rows.forEach((h, i) => {
    if (cur.length && used + h > RP_SHEET_ROOM) { pages.push(cur); cur = []; used = head + foot; }
    cur.push(i);
    used += h;
  });
  if (used - foot + (box.bottom - tbl.bottom) > RP_SHEET_ROOM) {   // the notes and signature go on the last sheet
    const last = cur.length > 1 ? [cur.pop()] : [];
    pages.push(cur);
    cur = last;
  }
  pages.push(cur);
  const area = document.createElement('div');
  area.className = 'rp-print-pages';
  pages.forEach((keep, n) => {
    const copy = sheet.cloneNode(true);
    [...copy.querySelectorAll('.rp-tbl tbody tr')].forEach((tr, i) => { if (!keep.includes(i)) tr.remove(); });
    if (n < pages.length - 1) copy.querySelectorAll('.ts-notes, .ts-review').forEach(el => el.remove());
    const lines = copy.querySelectorAll('.lbl-doc .dl');
    lines[lines.length - 1].textContent = `หน้าที่ ${n + 1} จาก ${pages.length}`;
    area.appendChild(copy);
  });
  document.body.appendChild(area);
  document.body.classList.add('rp-paged');
}

/* 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, admin, currentUser }) {
  const isAuditor = window.__CURRENT_ROLE === 'auditor';
  // rows live in window.Repairs (shared by every device) — see useSyncedStore
  const store = useSyncedStore(window.Repairs);
  useEffect(() => {
    window.addEventListener('beforeprint', rpSheetsForPrint);
    window.addEventListener('afterprint', rpSheetsDone);
    return () => { window.removeEventListener('beforeprint', rpSheetsForPrint); window.removeEventListener('afterprint', rpSheetsDone); rpSheetsDone(); };
  }, []);
  const firstInst = instruments[0];
  const [dept, setDept] = useState(firstInst ? firstInst.dept : '');
  const [code, setCode] = useState(firstInst ? firstInst.code : '');

  // department list (only depts that own instruments) + that dept's instruments
  const deptList = useMemo(() => Object.keys(DEPT_META).filter(d => instruments.some(i => i.dept === d)), [instruments]);
  const deptInstruments = useMemo(() => instruments.filter(i => i.dept === dept), [instruments, dept]);

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

  // pick department → jump to its first instrument; pick code → keep dept in sync
  const pickDept = (d) => { setDept(d); const first = instruments.find(i => i.dept === d); if (first) setCode(first.code); };
  const pickCode = (c) => { setCode(c); const i = instruments.find(x => x.code === c); if (i) setDept(i.dept); };

  // installation location + responsible person always follow the instrument's
  // own department, so the form can never show a mismatched department
  const locValue = inst ? deptLoc(inst.dept) : '';
  const ownerVal = (window.DEPT_OWNER || {})[inst && inst.dept] || meta.owner;

  // every change goes through window.Repairs (it saves locally at once and
  // sends to the sheet a moment after typing stops); then keep the
  // instrument's op-status in step with its rows
  const canEdit = () => window.__CURRENT_ROLE !== 'auditor' && !!inst;
  const syncOp = () => { const op = opFromRows(window.Repairs.forCode(inst.code)); if (op !== meta.op.key) onSetStatus(inst.code, op); };

  const blankRow = () => ({ id: window.Repairs.newId(), date: new Date().toLocaleDateString('en-CA'), problem: '', fix: '', result: '', note: '', by: currentUser || '', status: 'open' });
  const addRow = () => { if (!canEdit()) return; window.Repairs.add(inst.code, blankRow(), inst.type); syncOp(); };
  const setField = (id, field, val) => {
    if (!canEdit()) return;
    const cur = rows.find(x => x.id === id);
    const note = field === 'status'
      ? `สถานะ: ${cur && RP_BY_KEY[cur.status] ? RP_BY_KEY[cur.status].label : '—'} → ${RP_BY_KEY[val] ? RP_BY_KEY[val].label : val}`
      : `แก้ช่อง “${RP_FIELD_LABEL[field] || field}”`;
    window.Repairs.setField(inst.code, id, field, val, inst.type, note);
    // the recorder is the account that last wrote the row: here for the screen, the server sets the one that counts
    if (field !== 'status' && currentUser) window.Repairs.setField(inst.code, id, 'by', currentUser, inst.type);
    syncOp();
  };
  const removeRow = (id) => { if (!canEdit()) return; window.Repairs.remove(inst.code, id, inst.type); syncOp(); };

  // 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>
          {!isAuditor && <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={() => pickCode(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" aria-label="เลือกแผนก" style={{ minWidth: 230 }} value={dept} onChange={e => pickDept(e.target.value)}>
            {deptList.map(d => <option key={d} value={d}>{deptLoc(d)}</option>)}
          </select>
        </div>
        <div className="fld">
          <label>เลือกเครื่องมือ</label>
          <select className="select" aria-label="เลือกเครื่องมือ" style={{ minWidth: 320 }} value={code} onChange={e => setCode(e.target.value)}>
            {deptInstruments.map(i => <option key={i.code} value={i.code}>{i.code} · {i.type}</option>)}
          </select>
        </div>
        <div style={{ flex: 1 }} />
        <SyncPill sync={window.Repairs.sync} />
        {!isAuditor && <button className="btn" onClick={addRow}><I.plus size={16} /> เพิ่มรายการแจ้งซ่อม</button>}
        <button className="btn btn-primary" onClick={doPrint}><I.download size={16} /> พิมพ์ฟอร์ม</button>
      </div>

      {isAuditor && (
        <div className="rp-hint tl-noprint" style={{ background: 'var(--warn-soft)', borderColor: 'var(--warn)' }}>
          <I.eye size={15} />
          <span>โหมดอ่านอย่างเดียว — บัญชีผู้ตรวจประเมินดูข้อมูลได้เท่านั้น บันทึกค่าไม่ได้</span>
        </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-MO-0013" line2="แก้ไขครั้งที่ 0 : 17 มิ.ย. 2569" />
          <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} disabled={isAuditor} 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} disabled={isAuditor} onChange={e => setField(r.id, 'problem', e.target.value)} /><div className="rp-text-print">{r.problem}</div></td>
                  <td><textarea rows={1} value={r.fix} disabled={isAuditor} onChange={e => setField(r.id, 'fix', e.target.value)} /><div className="rp-text-print">{r.fix}</div></td>
                  <td><textarea rows={1} value={r.result} disabled={isAuditor} onChange={e => setField(r.id, 'result', e.target.value)} /><div className="rp-text-print">{r.result}</div></td>
                  <td><textarea rows={1} value={r.note} disabled={isAuditor} onChange={e => setField(r.id, 'note', e.target.value)} /><div className="rp-text-print">{r.note}</div></td>
                  <td><input value={r.by} disabled readOnly /><div className="rp-text-print">{r.by}</div></td>
                  <td className="rp-stcol">
                    {isAuditor ? (
                      <span className={`pill ${RP_BY_KEY[r.status].tone}`} style={{ fontSize: 11 }}><span className="dot"></span>{RP_BY_KEY[r.status].label}</span>
                    ) : (
                      <select className={`rp-status rp-status-${RP_BY_KEY[r.status].tone}`} aria-label="สถานะงานซ่อม" 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>
                    {admin && <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) { return opFromRows(window.Repairs.forCode(code)); };
