/* ============================================================
   pm.jsx — "บันทึก PM" quick-log modal for vendor on-site PM.
   No outbound dispatch (vendor visits the lab). Saving auto-rolls
   inst.pmLast / inst.pmNext, files a row in PMLogs, optionally
   uploads a service report to Drive linked to the instrument, and
   writes an audit entry.
   ============================================================ */

const PM_RESULT_OPTIONS = [
  { key: 'ผ่าน',           label: 'ผ่าน · ใช้งานได้ปกติ',     tone: 'ok' },
  { key: 'ผ่านโดยมีเงื่อนไข', label: 'ผ่าน · มีเงื่อนไข/นัดติดตาม', tone: 'warn' },
  { key: 'ซ่อม',            label: 'พบปัญหา · ต้องซ่อม',        tone: 'danger' },
];

function pmAddDays(iso, n) {
  if (!iso) return '';
  const d = new Date(iso + 'T00:00:00');
  if (isNaN(d.getTime())) return '';
  d.setDate(d.getDate() + (Number(n) || 0));
  const p = (x) => String(x).padStart(2, '0');
  return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());
}

function PMLogModal({ inst, onClose, onSaved, currentUser }) {
  const pmPerYear = Number(inst.pmPerYear) || 0;
  const cycleDays = pmPerYear > 0 ? Math.round(365 / pmPerYear) : 180;

  const [doneDate, setDoneDate] = useState(window.TODAY_ISO);
  const [vendor, setVendor]   = useState(inst.provider || '');
  const [result, setResult]   = useState('ผ่าน');
  const [note, setNote]       = useState('');
  const [nextDate, setNextDate] = useState(pmAddDays(window.TODAY_ISO, cycleDays));
  const [touchedNext, setTouchedNext] = useState(false);
  const [reportDoc, setReportDoc] = useState(null);
  const [upBusy, setUpBusy] = useState(false);
  const [upErr, setUpErr]   = useState('');
  const fileRef = useRef(null);

  // auto-roll next-date from doneDate until the user edits it directly
  useEffect(() => { if (!touchedNext) setNextDate(pmAddDays(doneDate, cycleDays)); }, [doneDate]);

  const uploadReport = async (files) => {
    setUpErr('');
    const file = files && files[0];
    if (!file) return;
    if (file.size > 12 * 1024 * 1024) { setUpErr('ไฟล์ใหญ่เกิน 12MB'); return; }
    if (window.Backend.mode !== 'gas') { setUpErr('โหมด local อัปโหลดไฟล์จริงไม่ได้'); return; }
    setUpBusy(true);
    try {
      const dataBase64 = await window.fileToBase64(file);
      const res = await window.Backend.fileUpload({ code: inst.code, name: file.name, mime: file.type || 'application/octet-stream', type: 'pm', dataBase64 });
      if (!res || !res.ok || !res.doc) throw new Error((res && res.message) || 'อัปโหลดไม่สำเร็จ');
      window.Docs.addLocal(res.doc);
      setReportDoc(res.doc);
      if (window.Audit) window.Audit.add({ action: 'doc_add', code: inst.code, target: file.name, detail: 'แนบรายงาน PM' });
    } catch (e) { setUpErr(e.message || String(e)); }
    setUpBusy(false);
    if (fileRef.current) fileRef.current.value = '';
  };

  const save = () => {
    const id = 'PM-' + inst.code + '-' + doneDate.replace(/-/g, '') + '-' + Date.now().toString(36).slice(-4).toUpperCase();
    const row = {
      id, code: inst.code, instType: inst.type || '', dept: inst.dept || '',
      doneDate, vendor: vendor.trim(), result, note: note.trim(),
      reportUrl: reportDoc ? reportDoc.url : '', reportName: reportDoc ? reportDoc.name : '',
      pmPerYear: inst.pmPerYear || '', cycleDays,
      doneBy: currentUser || '', createdAt: new Date().toISOString(),
    };
    window.PMLogs.upsert(row);
    onSaved && onSaved(inst, { doneDate, nextDate, result, vendor: vendor.trim(), note });
  };

  const footer = (
    <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
      <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
      <button className="btn btn-primary" onClick={save}><I.check size={15} /> บันทึก PM</button>
    </div>
  );

  return (
    <CJModal title="บันทึกการทำ PM (Preventive maintenance)" sub={inst.code + ' · ' + inst.type} icon={I.refresh} onClose={onClose} footer={footer}>
      <CJField label="วันที่ทำ PM">
        <input type="date" value={doneDate} onChange={e => setDoneDate(e.target.value)} style={cjInput} />
      </CJField>
      <CJField label="ผู้ให้บริการ (Vendor / ผู้ทำ PM)">
        <input value={vendor} onChange={e => setVendor(e.target.value)} placeholder="เช่น Roche · บริษัท XXX · ทีมวิศวกรรมการแพทย์" style={cjInput} />
      </CJField>
      <CJField label="ผลการทำ PM">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {PM_RESULT_OPTIONS.map(r => {
            const on = result === r.key;
            const col = r.tone === 'danger' ? 'var(--danger)' : r.tone === 'warn' ? 'var(--warn)' : 'var(--ok)';
            const soft = r.tone === 'danger' ? 'var(--danger-soft)' : r.tone === 'warn' ? 'var(--warn-soft)' : 'var(--ok-soft)';
            return (
              <button key={r.key} type="button" onClick={() => setResult(r.key)}
                style={{ padding: '8px 14px', borderRadius: 9, fontSize: 13, fontWeight: 600, cursor: 'pointer', border: '1px solid ' + (on ? col : 'var(--line)'), background: on ? soft : 'var(--surface)', color: on ? col : 'var(--ink-2)' }}>
                {r.label}
              </button>
            );
          })}
        </div>
      </CJField>
      <CJField label="ครบรอบ PM ครั้งถัดไป" hint={`คำนวณอัตโนมัติจากรอบ (${pmPerYear ? 'ทุก ' + Math.round(12/pmPerYear) + ' เดือน' : '6 เดือน'}) · ปรับได้`}>
        <input type="date" value={nextDate} onChange={e => { setTouchedNext(true); setNextDate(e.target.value); }} style={cjInput} />
      </CJField>
      <CJField label="หมายเหตุ / สิ่งที่ทำ (Service note)">
        <textarea value={note} onChange={e => setNote(e.target.value)} rows={2} placeholder="เช่น เปลี่ยน filter, calibrate flow rate, ทำความสะอาด pipeline" style={{ ...cjInput, resize: 'vertical' }} />
      </CJField>
      <CJField label="แนบรายงาน PM (Service report)" hint="ไฟล์ถูกเก็บใน Drive และผูกกับเครื่องนี้อัตโนมัติ (ดูได้ที่หน้าเครื่อง > เอกสารแนบ)">
        <input type="file" ref={fileRef} hidden accept="image/*,.pdf,.doc,.docx" onChange={e => uploadReport(e.target.files)} />
        {reportDoc ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--ok-soft)', border: '1px solid var(--ok)', borderRadius: 9, padding: '9px 12px' }}>
            <I.check size={16} style={{ color: 'var(--ok)', flex: 'none' }} />
            <a href={reportDoc.url} target="_blank" rel="noopener noreferrer" style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 600, color: 'var(--ink)', textDecoration: 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{reportDoc.name}</a>
            <button type="button" className="btn btn-icon btn-ghost" title="เปลี่ยนไฟล์" onClick={() => { setReportDoc(null); fileRef.current && fileRef.current.click(); }}><I.refresh size={15} /></button>
          </div>
        ) : (
          <button type="button" className="btn" disabled={upBusy} onClick={() => fileRef.current && fileRef.current.click()} style={{ width: '100%', justifyContent: 'center' }}>
            {upBusy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังอัปโหลด…</> : <><I.download size={15} style={{ transform: 'rotate(180deg)' }} /> เลือกไฟล์รายงาน PM (PDF / รูป)</>}
          </button>
        )}
        {upErr && <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 5 }}>{upErr}</div>}
      </CJField>

      <div style={{ background: 'var(--accent-soft)', borderRadius: 10, padding: '10px 13px', fontSize: 12.5, color: 'var(--ink-2)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
        <I.refresh size={15} style={{ flex: 'none', marginTop: 1, color: 'var(--accent-strong)' }} />
        <span>เมื่อบันทึก: ระบบจะอัปเดต <b>PM ล่าสุด / PM ครั้งถัดไป</b> ของเครื่องนี้ให้อัตโนมัติ + บันทึกประวัติ PM ในแท็บ <b>PMLogs</b> + ลง Audit</span>
      </div>
    </CJModal>
  );
}
window.PMLogModal = PMLogModal;

/* ---- PM history — pop-up modal (opened from the PM card) ---- */
function PMHistoryModal({ inst, onClose }) {
  const [, bump] = useState(0);
  useEffect(() => window.PMLogs.subscribe(() => bump(x => x + 1)), []);
  const rows = window.PMLogs.forCode(inst.code).slice().sort((a, b) => String(b.doneDate || '').localeCompare(String(a.doneDate || '')));

  return (
    <CJModal wide title="ประวัติการทำ PM" sub={inst.code + ' · ' + inst.type + (rows.length ? ` · รวม ${rows.length} ครั้ง` : '')} icon={I.history} onClose={onClose}>
      {rows.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '32px 12px', color: 'var(--ink-3)' }}>
          <I.history size={36} style={{ opacity: .5, marginBottom: 10 }} />
          <div style={{ fontSize: 13.5 }}>ยังไม่มีประวัติการทำ PM</div>
          <div style={{ fontSize: 11.5, marginTop: 4 }}>กดปุ่ม "บันทึก PM" บนการ์ดเพื่อเริ่มประวัติแรก</div>
        </div>
      ) : (
        <div className="tbl-wrap" style={{ border: '1px solid var(--line)', borderRadius: 10 }}>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 120 }}>วันที่</th>
                <th style={{ width: 150 }}>ผลการบำรุงรักษา</th>
                <th>ผู้ให้บริการ (Vendor)</th>
                <th style={{ width: 160 }}>บันทึกโดย</th>
                <th style={{ width: 64, textAlign: 'center' }}>รายงาน</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(r => {
                const fail = r.result === 'ซ่อม';
                const cond = r.result === 'ผ่านโดยมีเงื่อนไข';
                const col = fail ? 'var(--danger)' : cond ? 'var(--warn)' : 'var(--ok)';
                const soft = fail ? 'var(--danger-soft)' : cond ? 'var(--warn-soft)' : 'var(--ok-soft)';
                return (
                  <React.Fragment key={r.id}>
                    <tr style={r.note ? { borderBottom: 'none' } : null}>
                      <td className="tnum" style={{ fontWeight: 600 }}>{window.fmtDateFull(r.doneDate)}</td>
                      <td><span className="pill" style={{ background: soft, color: col, fontSize: 11, fontWeight: 700 }}><span className="dot" />{r.result || '—'}</span></td>
                      <td>{r.vendor || <span className="muted">—</span>}</td>
                      <td style={{ color: 'var(--ink-2)' }}>{r.doneBy || '—'}</td>
                      <td style={{ textAlign: 'center' }}>
                        {r.reportUrl
                          ? <a href={r.reportUrl} target="_blank" rel="noopener noreferrer" className="btn btn-icon btn-ghost" title="เปิดรายงาน PM" style={{ textDecoration: 'none', color: 'var(--accent-strong)' }}><I.copy size={15} /></a>
                          : <span className="muted">—</span>}
                      </td>
                    </tr>
                    {r.note && (
                      <tr>
                        <td colSpan={5} style={{ paddingTop: 0, fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>
                          <b style={{ color: 'var(--ink-2)', fontWeight: 600 }}>รายละเอียด:</b> {r.note}
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </CJModal>
  );
}
window.PMHistoryModal = PMHistoryModal;
