/* ============================================================
   templog.jsx — fridge/freezer/incubator temperature log
   (FM-CL-00-045). Pick a temperature-controlled instrument →
   monthly grid, out-of-range highlight, corrective actions,
   print with the shared FR/FM header. Persists to localStorage.
   ============================================================ */
const TL_KEY = 'labinstrument.templog.v1';
const FRZ_TARGETS = [-20, -30, -40, -80];
const TL_MONTHS = THMONTH;

function tempProfile(inst) {
  const s = `${inst.type || ''} ${inst.typeName || ''} ${inst.code || ''}`.toLowerCase();
  const abbr = (inst.code || '').split('-')[2] || '';
  const has = (...k) => k.some(x => s.includes(x));
  if (has('เกล็ดเลือด', 'platelet') || ['PLT', 'PAG'].includes(abbr))
    return { cat: 'plt', word: 'ตู้เก็บเกล็ดเลือด', chambers: [{ key: 't', name: 'อุณหภูมิ', min: 20, max: 24 }] };
  if (has('เพาะเชื้อ', 'incubat', 'co2', ' 37') || ['INC', 'CO2', 'INB'].includes(abbr))
    return { cat: 'inc', word: 'ตู้อบเพาะเชื้อ', chambers: [{ key: 't', name: 'อุณหภูมิ', min: 35, max: 39 }] };
  if (has('แช่แข็ง', 'freez', '-20', '-30', '-40', '-80') || ['FRZ', 'FZR', 'FZ'].includes(abbr))
    return { cat: 'frz', word: 'ตู้แช่แข็ง', freezer: true, target: -20, chambers: [{ key: 'f', name: 'ช่องแช่แข็ง', min: -25, max: -15 }] };
  if (has('ตู้เย็น', 'refriger', '2-8', '2–8', 'iqc') || ['REF', 'BBR', 'BBK', 'FRG'].includes(abbr))
    return { cat: 'ref', word: 'ตู้เย็น', chambers: [{ key: 'c', name: 'ช่องแช่เย็น', min: 2, max: 8 }] };
  if (has('อุณหภูมิ', 'temp') || abbr === 'TMR')
    return { cat: 'ref', word: 'ตู้ควบคุมอุณหภูมิ', chambers: [{ key: 'c', name: 'อุณหภูมิ', min: 2, max: 8 }] };
  return null;
}

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

function TempLog({ instruments }) {
  const devices = useMemo(() => instruments.map(i => ({ i, p: tempProfile(i) })).filter(x => x.p), [instruments]);
  const [code, setCode] = useState(devices[0] ? devices[0].i.code : '');
  const today = TODAY;
  const [month, setMonth] = useState(today.getMonth());
  const [year, setYear] = useState(today.getFullYear() + 543);
  const [store, setStore] = useState(loadTL);

  const dev = devices.find(d => d.i.code === code);
  const inst = dev ? dev.i : null;
  const meta = inst ? window.instrumentMeta(inst) : {};
  const ym = `${code}|${year}-${month}`;
  const rec = store[ym] || { grid: {}, corr: [], ranges: null, target: dev && dev.p.freezer ? dev.p.target : null };

  // effective chambers (apply freezer target / saved ranges)
  const chambers = useMemo(() => {
    if (!dev) return [];
    let ch = dev.p.chambers.map(c => ({ ...c }));
    if (dev.p.freezer) { const tg = rec.target ?? dev.p.target; ch = [{ key: 'f', name: 'ช่องแช่แข็ง', min: tg - 5, max: tg + 5 }]; }
    if (rec.ranges) ch = ch.map(c => ({ ...c, ...(rec.ranges[c.key] || {}) }));
    return ch;
  }, [dev, rec.target, rec.ranges]);

  const daysInMonth = new Date(year - 543, month + 1, 0).getDate();
  const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);

  const persist = (next) => { setStore(next); try { localStorage.setItem(TL_KEY, JSON.stringify(next)); } catch (e) {} };
  const update = (mut) => {
    const next = { ...store };
    const r = { ...(next[ym] || { grid: {}, corr: [], ranges: null, target: dev && dev.p.freezer ? dev.p.target : null }) };
    r.grid = { ...r.grid };
    mut(r);
    next[ym] = r; persist(next);
    if (window.Backend && window.Backend.mode === 'gas') {
      window.Backend.rowUpsert('TempLogs', { id: ym, code: code, year: year, month: month, data: JSON.stringify(r) }).catch(function () {});
    }
  };
  const setCell = (day, sess, key, val) => update(r => { r.grid[`${day}.${sess}.${key}`] = val; });
  const cell = (day, sess, key) => (store[ym] && store[ym].grid[`${day}.${sess}.${key}`]) || '';
  const setTarget = (t) => update(r => { r.target = t; });
  const setRange = (ck, field, val) => update(r => { r.ranges = { ...(r.ranges || {}) }; r.ranges[ck] = { ...(r.ranges[ck] || {}), [field]: val === '' ? undefined : +val }; });
  const addCorr = () => update(r => { r.corr = [...r.corr, { no: r.corr.length + 1, date: '', problem: '', fix: '', by: '' }]; });
  const setCorr = (idx, field, val) => update(r => { const arr = [...r.corr]; while (arr.length <= idx) arr.push({ date: '', problem: '', fix: '', by: '' }); arr[idx] = { ...arr[idx], [field]: val }; r.corr = arr; });
  const setLoc = (v) => update(r => { r.loc = v; });
  const locOptions = Object.entries(DEPT_META).map(([name, m]) => ({ value: deptLoc(name), label: deptLoc(name) }));
  const locValue = rec.loc || (inst ? deptLoc(inst.dept) : '');

  const oor = (ck, raw) => {
    if (raw === '' || raw == null) return false;
    const n = parseFloat(raw); if (isNaN(n)) return false;
    const c = chambers.find(x => x.key === ck); if (!c) return false;
    return n < c.min || n > c.max;
  };

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

  if (devices.length === 0) return <EmptyState icon={I.beaker} title="ไม่พบเครื่องควบคุมอุณหภูมิในทะเบียน" sub="เพิ่มตู้เย็น/ตู้แช่/ตู้อบเพาะเชื้อก่อน" />;

  const cnt = days.length;
  const sessions = [['am', 'เช้า'], ['pm', 'บ่าย']];
  const rangeText = chambers.map(c => `${c.name} ${c.min}°C ถึง ${c.max}°C`).join(' · ');

  return (
    <div className="enter">
      {/* controls (hidden in print) */}
      <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)}>
            {devices.map(d => <option key={d.i.code} value={d.i.code}>{d.i.code} · {d.i.type}</option>)}
          </select>
        </div>
        <div className="fld">
          <label>เดือน</label>
          <select className="select" value={month} onChange={e => setMonth(+e.target.value)}>{TL_MONTHS.map((m, i) => <option key={i} value={i}>{m}</option>)}</select>
        </div>
        <div className="fld">
          <label>พ.ศ.</label>
          <input className="input" style={{ width: 90 }} type="number" value={year} onChange={e => setYear(+e.target.value)} />
        </div>
        {dev && dev.p.freezer && (
          <div className="fld">
            <label>อุณหภูมิเป้าหมาย</label>
            <select className="select" value={rec.target ?? dev.p.target} onChange={e => setTarget(+e.target.value)}>
              {FRZ_TARGETS.map(t => <option key={t} value={t}>{t}°C (±5)</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 btn-primary" onClick={doPrint}><I.download size={16} /> พิมพ์ฟอร์ม</button>
      </div>

      {/* the sheet (editor doubles as printable form) */}
      <div className="tl-sheetwrap">
        <div className="temp-sheet">
          <LabDocHeader docNo="FR-BM-001" line2={`ทบทวนล่าสุด ${fmtDateFull(TODAY.toISOString().slice(0,10))}`} />

          <div className="ts-meta">
            <div>
              <b style={{ fontSize: 16 }}>แบบบันทึกอุณหภูมิ{dev ? dev.p.word : ''}</b> &nbsp;
              ประจำเดือน <span className="uline">{TL_MONTHS[month]}</span> พ.ศ. <span className="uline">{year}</span> &nbsp;
              หมายเลขครุภัณฑ์ <span className="uline">{inst && inst.asset !== '-' ? inst.asset : '-'}</span> &nbsp;
              ยี่ห้อ <span className="uline">{inst ? inst.brand : '-'}</span> &nbsp;
              รุ่น <span className="uline">{inst && inst.model !== '-' ? inst.model : '-'}</span>
            </div>
            <div>
              รหัสเครื่อง <span className="uline">{inst ? inst.code : '-'}</span> &nbsp;
              สถานที่ตั้ง <span className="uline">{locValue || '-'}</span> &nbsp;
              ช่วงอุณหภูมิที่ยอมรับได้ :
              {chambers.map((c, i) => (
                <span key={c.key}> &nbsp;{c.name}
                  <input type="number" value={c.min} onChange={e => setRange(c.key, 'min', e.target.value)} style={{ width: 50 }} />°C ถึง
                  <input type="number" value={c.max} onChange={e => setRange(c.key, 'max', e.target.value)} style={{ width: 50 }} />°C
                </span>
              ))}
            </div>
          </div>

          {/* grid */}
          <table className="tl-grid">
            <thead>
              <tr>
                <th colSpan={2} className="tl-rowlab" style={{ width: 130 }}>วันที่</th>
                {days.map(d => <th key={d}>{d}</th>)}
              </tr>
            </thead>
            <tbody>
              {sessions.map(([sk, sname]) => {
                const rows = [...chambers.map(c => ({ type: 'chamber', c })), { type: 'time' }, { type: 'by' }];
                return rows.map((row, ri) => (
                  <tr key={sk + ri}>
                    {ri === 0 && <td className="tl-sesslab" rowSpan={rows.length}>{sname}</td>}
                    <td className="tl-rowlab">{row.type === 'chamber' ? row.c.name : row.type === 'time' ? 'เวลา' : 'ผู้บันทึก'}</td>
                    {days.map(d => {
                      const key = row.type === 'chamber' ? row.c.key : row.type;
                      const val = cell(d, sk, key);
                      const bad = row.type === 'chamber' && oor(row.c.key, val);
                      return (
                        <td key={d} className={`tl-cell${bad ? ' oor' : ''}`}>
                          <input value={val} onChange={e => setCell(d, sk, key, e.target.value)} />
                        </td>
                      );
                    })}
                  </tr>
                ));
              })}
            </tbody>
          </table>

          <div className="ts-notes">
            <b>หมายเหตุ :</b> 1. กรณีอุณหภูมิออกนอกช่วงค่าที่กำหนด ให้ติดตามต่อไปอีก 1 ชั่วโมง หากยังไม่ได้อีกให้ติดต่อช่างงานซ่อมบำรุง &nbsp; 2. กรณีไม่ได้ใช้งาน กรุณากาเครื่องหมาย (−) เมื่อได้ปฏิบัติในข้อนั้น ๆ
          </div>

          {/* corrective action */}
          <div className="ts-corr">
            <h4>การปฏิบัติแก้ไข (Corrective action)</h4>
            <table className="tl-corr">
              <thead><tr><th style={{ width: 50 }}>ครั้งที่</th><th style={{ width: 110 }}>วันที่</th><th>ปัญหา</th><th>การแก้ไข</th><th style={{ width: 130 }}>ผู้บันทึก</th></tr></thead>
              <tbody>
                {Array.from({ length: Math.max(2, rec.corr.length) }, (_, i) => rec.corr[i] || { date: '', problem: '', fix: '', by: '' }).map((c, i) => (
                  <tr key={i}>
                    <td style={{ textAlign: 'center' }}>{i + 1}</td>
                    <td><input value={c.date} onChange={e => setCorr(i, 'date', e.target.value)} /></td>
                    <td><input value={c.problem} onChange={e => setCorr(i, 'problem', e.target.value)} /></td>
                    <td><input value={c.fix} onChange={e => setCorr(i, 'fix', e.target.value)} /></td>
                    <td><input value={c.by} onChange={e => setCorr(i, 'by', e.target.value)} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
            <button className="btn btn-sm tl-noprint" style={{ marginTop: 8 }} onClick={addCorr}><I.plus size={14} /> เพิ่มแถว</button>
          </div>

          <div className="ts-review">ทบทวนโดย : ............................................. วันที่ ........./........./.........</div>
          <div className="lbl-foot">(เอกสารสำเนาอิเล็กทรอนิกส์ถูกควบคุมให้เป็นปัจจุบันเมื่ออยู่บนเว็บไซต์เท่านั้น)</div>
        </div>
      </div>
    </div>
  );
}
window.TempLog = TempLog;
