/* ============================================================
   editdrawer.jsx — slide-in editor for an existing instrument.
   Edits merge into a per-code override (persisted in App).
   ============================================================ */
function EFGroup({ title, children }) {
  return (
    <div style={{ marginBottom: 6 }}>
      <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)', margin: '18px 0 12px' }}>{title}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>{children}</div>
    </div>
  );
}
function EFField({ label, value, onChange, full, type, placeholder, list }) {
  return (
    <div style={full ? { gridColumn: '1 / -1' } : {}}>
      <label className="field-label">{label}</label>
      <input className="input" type={type || 'text'} value={value} placeholder={placeholder || ''} list={list} onChange={e => onChange(e.target.value)} />
    </div>
  );
}

// fixed decommission-reason choices; "อื่น ๆ" opens a free-text field below it
const DECOMM_REASONS = ['ชำรุด/ซ่อมไม่คุ้ม', 'ครบอายุการใช้งาน', 'มีเครื่องใหม่ทดแทน', 'จำหน่าย/บริจาคออก'];

// รอบสอบเทียบ/PM ตรง ๆ จากตรงนี้แทนการให้ผู้ใช้ไปแก้ในชีตเอง — '' คือยังไม่ระบุ (ไม่ต่างจากเดิม),
// '-' คือยกเว้นจริง ๆ (shared.jsx _freqExempt อ่านค่านี้)
const _freqNumOptions = () => [1, 2, 3, 4, 6].map(n => ({ v: String(n), label: `${n} ครั้ง/ปี (ทุก ${Math.round(12 / n)} เดือน)` }));
const CAL_FREQ_OPTIONS = [{ v: '', label: '(ยังไม่ระบุ)' }, { v: '-', label: 'ไม่ต้องสอบเทียบ' }, ..._freqNumOptions()];
const PM_FREQ_OPTIONS = [{ v: '', label: '(ยังไม่ระบุ)' }, { v: '-', label: 'ไม่ต้อง PM' }, ..._freqNumOptions()];

/* shrink a picture in the browser before upload: longest side ≤ maxSide, as
   JPEG. Resolves to the base64 body (no "data:" prefix) — a phone photo of
   several MB becomes a few hundred KB. */
function shrinkImage(file, maxSide, quality) {
  return new Promise((resolve, reject) => {
    const url = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      try {
        const k = Math.min(1, maxSide / Math.max(img.naturalWidth, img.naturalHeight));
        const w = Math.max(1, Math.round(img.naturalWidth * k)), h = Math.max(1, Math.round(img.naturalHeight * k));
        const c = document.createElement('canvas');
        c.width = w; c.height = h;
        const g = c.getContext('2d');
        g.fillStyle = '#fff'; g.fillRect(0, 0, w, h);   // a transparent PNG gets a white background, not black
        g.drawImage(img, 0, 0, w, h);
        URL.revokeObjectURL(url);
        resolve(c.toDataURL('image/jpeg', quality).split(',')[1]);
      } catch (e) { URL.revokeObjectURL(url); reject(e); }
    };
    img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('เปิดไฟล์รูปนี้ไม่ได้ — ลองใช้ไฟล์ JPG หรือ PNG')); };
    img.src = url;
  });
}

function EditDrawer({ inst, onClose, onSave, config, instruments }) {
  const meta = useMemo(() => instrumentMeta(inst), [inst]);
  // standard locations from ตั้งค่าข้อมูลหลัก → datalist choices (free-text still allowed)
  const masterLocations = useMemo(() => (window.readMasterLocations ? window.readMasterLocations(config) : []), [config]);
  // instruments this device can be linked to as its replacement — active only,
  // but keep the current value visible even if it now points to a retired/missing code
  // (never let a saved link vanish silently from the dropdown)
  const replaceOptions = useMemo(() => {
    const all = (instruments || []).filter(i => i.code !== inst.code);
    const active = all.filter(i => !isDecommissioned(i));
    if (meta.replacedBy && !active.some(i => i.code === meta.replacedBy)) {
      const cur = all.find(i => i.code === meta.replacedBy);
      if (cur) active.push(cur);
    }
    return active.sort((a, b) => a.code.localeCompare(b.code));
  }, [instruments, inst.code, meta.replacedBy]);
  const [f, setF] = useState({
    type: inst.type || '', brand: inst.brand || '', model: inst.model === '-' ? '' : inst.model || '',
    serial: inst.serial === '-' ? '' : inst.serial || '', asset: inst.asset === '-' ? '' : inst.asset || '',
    note: inst.note === '-' ? '' : inst.note || '',
    cal: inst.cal || '', exp: inst.exp || '', calPerYear: String(inst.calPerYear ?? '').trim(),
    opKey: inst.opKey || 'up', location: inst.location || '', owner: inst.owner || '',
    provider: inst.provider || '', certNo: inst.certNo || '', pmLast: inst.pmLast || '', pmNext: inst.pmNext || '',
    pmPerYear: String(inst.pmPerYear ?? '').trim(),
    condition: meta.condition || '', commissionDate: meta.commissionDate || '', acceptance: meta.acceptance || '', vendor: meta.vendor || '',
    vendorContact: meta.vendorContact || '', firmware: meta.firmware === '—' ? '' : (meta.firmware || ''),
    warrantyEnd: meta.warrantyEnd || '', serviceContract: meta.serviceContract || '', manualRef: meta.manualRef || '',
    lifecycle: meta.lifecycle || 'active', decommissionDate: meta.decommissionDate || '',
    // decommissionReason is stored as one plain string; split into a dropdown
    // choice + optional free text here only so the "อื่น ๆ" field can show it
    decommissionReasonKind: meta.decommissionReason && !DECOMM_REASONS.includes(meta.decommissionReason) ? 'อื่น ๆ' : (meta.decommissionReason || ''),
    decommissionReasonOther: meta.decommissionReason && !DECOMM_REASONS.includes(meta.decommissionReason) ? meta.decommissionReason : '',
    replacedBy: meta.replacedBy || '',
    photo: inst.photo || '',
    videoLink: inst.videoLink || '', retrainLink: inst.retrainLink || '',
    calPoint: inst.calPoint || '', mpe: inst.mpe || '', useRange: inst.useRange || '', calResult: inst.calResult || '',
  });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  // instrument photo: pick or take a picture → shrunk in the browser → uploaded
  // to Drive through the same file_upload the attachments use (the server only
  // lets an admin do this) → its link goes into the `photo` field. Nothing
  // changes on the instrument until "บันทึก" is pressed.
  const photoRef = useRef(null);
  const [photoUp, setPhotoUp] = useState({ busy: false, err: '', done: false, preview: '' });
  const uploadPhoto = async (file) => {
    if (!file || photoUp.busy) return;
    setPhotoUp({ busy: true, err: '', done: false, preview: '' });
    try {
      const dataBase64 = await shrinkImage(file, 1600, 0.85);
      const res = await window.Backend.fileUpload({ code: inst.code, name: inst.code + '-photo-' + Date.now() + '.jpg', mime: 'image/jpeg', type: 'photo', dataBase64 });
      if (!res || !res.ok || !res.doc || !res.doc.url) throw new Error((res && res.message) || 'อัปโหลดไม่สำเร็จ ลองใหม่อีกครั้ง');
      if (window.Docs) window.Docs.addLocal(res.doc);
      set('photo', res.doc.url);
      // preview from the picture itself — Drive can take a moment before it serves a new file
      setPhotoUp({ busy: false, err: '', done: true, preview: 'data:image/jpeg;base64,' + dataBase64 });
    } catch (e) {
      setPhotoUp({ busy: false, err: (e && e.message) || String(e), done: false, preview: '' });
    }
  };

  const save = () => {
    const newPhoto = f.photo.trim();
    // uploaded photos of this instrument that are not its photo after this save
    // (the one being replaced, or an upload that was changed again before saving)
    const oldPhotos = (window.Docs ? window.Docs.forCode(inst.code) : []).filter(d => d.type === 'photo' && String(d.url || '') !== newPhoto);
    const saved = onSave(inst.code, {
      type: f.type, brand: f.brand, model: f.model || '-', serial: f.serial || '-', asset: f.asset || '-',
      note: f.note || '-', cal: f.cal || null, exp: f.exp || null, calPerYear: f.calPerYear,
      opKey: f.opKey, location: f.location || null, owner: f.owner || null, provider: f.provider, certNo: f.certNo,
      pmLast: f.pmLast || null, pmNext: f.pmNext || null, pmPerYear: f.pmPerYear,
      condition: f.condition || null, commissionDate: f.commissionDate || null, acceptance: f.acceptance || null, vendor: f.vendor || null,
      vendorContact: f.vendorContact || null, firmware: f.firmware || null,
      warrantyEnd: f.warrantyEnd || null, serviceContract: f.serviceContract || null, manualRef: f.manualRef || null,
      lifecycle: f.lifecycle, decommissionDate: f.lifecycle === 'decommissioned' ? (f.decommissionDate || null) : null,
      decommissionReason: f.lifecycle === 'decommissioned'
        ? (f.decommissionReasonKind === 'อื่น ๆ' ? (f.decommissionReasonOther.trim() || 'อื่น ๆ') : (f.decommissionReasonKind || null))
        : null,
      replacedBy: f.lifecycle === 'decommissioned' ? (f.replacedBy || null) : null,
      photo: f.photo.trim() || null,
      videoLink: f.videoLink.trim() || null, retrainLink: f.retrainLink.trim() || null,
      calPoint: f.calPoint.trim() || null, mpe: f.mpe.trim() || null,
      useRange: f.useRange.trim() || null, calResult: f.calResult.trim() || null,
    });
    // remove their files only once the change is really saved — until then the
    // sheet may still point at one of them
    if (oldPhotos.length && saved && saved.then) {
      saved.then(res => {
        if (!res || res.ok === false) return;
        oldPhotos.forEach(d => {
          window.Backend.docDelete(d.id, { action: 'doc_delete', code: inst.code, target: d.name, detail: 'ลบรูปเครื่องมือเดิม' })
            .then(r => { if (r && r.ok !== false && window.Docs) window.Docs.removeLocal(d.id); })
            .catch(() => {});
        });
      });
    }
    onClose();
  };

  const Group = EFGroup;
  const fld = (label, k, opts = {}) => <EFField label={label} value={f[k]} onChange={v => set(k, v)} full={opts.full} type={opts.type} list={opts.list} />;

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="drawer">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
          <span style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center' }}><I.edit size={18} /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 16 }}>แก้ไขเครื่องมือ</div>
            <div className="code page-sub">{inst.code}</div>
          </div>
          <button className="btn btn-icon btn-ghost" onClick={onClose}><I.close size={18} /></button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 22px 22px' }}>
          <Group title="ข้อมูลเครื่องมือ">
            {fld('ชนิด/ชื่อเครื่องมือ', 'type', { full: true })}
            {fld('ยี่ห้อ (Brand)', 'brand')}
            {fld('รุ่น / Model', 'model')}
            {fld('Serial No.', 'serial')}
            {fld('รหัสครุภัณฑ์', 'asset')}
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">รูปภาพเครื่องมือ</label>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 8 }}>
                <input ref={photoRef} type="file" accept="image/*" style={{ display: 'none' }}
                  onChange={e => { const fl = e.target.files && e.target.files[0]; e.target.value = ''; uploadPhoto(fl); }} />
                <button type="button" className="btn btn-sm" disabled={photoUp.busy} onClick={() => photoRef.current && photoRef.current.click()}>
                  {photoUp.busy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังอัปโหลด…</> : <><I.plus size={15} /> เลือกรูป / ถ่ายรูป</>}
                </button>
                {f.photo.trim() && !photoUp.busy && (
                  <button type="button" className="btn btn-sm" onClick={() => { set('photo', ''); setPhotoUp({ busy: false, err: '', done: false, preview: '' }); }}>ไม่ใช้รูปนี้</button>
                )}
                {photoUp.done && <span className="pill ok" style={{ whiteSpace: 'normal' }}><span className="dot"></span>อัปโหลดแล้ว — กด “บันทึก” เพื่อใช้รูปนี้</span>}
                {photoUp.err && <span className="pill danger" role="alert" style={{ whiteSpace: 'normal' }}><span className="dot"></span>อัปโหลดไม่สำเร็จ — {photoUp.err}</span>}
              </div>
              <input className="input" type="url" value={f.photo} placeholder="หรือวางลิงก์รูป https://… (เว้นว่าง = ใช้รูปจริงในระบบ/ตามประเภทอัตโนมัติ)"
                onChange={e => { set('photo', e.target.value); setPhotoUp(s => (s.preview || s.done) ? { ...s, done: false, preview: '' } : s); }} />
              <div style={{ marginTop: 10, height: 150, borderRadius: 10, overflow: 'hidden', border: '1px solid var(--line)', background: '#fff', padding: 6 }}>
                <img src={photoUp.preview || (f.photo.trim() ? window.normalizeImageUrl(f.photo.trim()) : '') || ((inst && inst.code && window.PHOTO_MANIFEST && window.PHOTO_MANIFEST[inst.code]) ? ('photos/' + window.PHOTO_MANIFEST[inst.code]) : '') || (window.instrumentTypeImg ? window.instrumentTypeImg(inst) : '') || ''}
                  alt="พรีวิว" onError={e => { e.target.style.display = 'none'; }}
                  onLoad={e => { e.target.style.display = 'block'; }}
                  style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6, lineHeight: 1.6 }}>
                ถ้าเว้นว่าง ระบบจะใช้รูปตามประเภทเครื่องให้อัตโนมัติ · ต้องเป็น <b>ลิงก์รูปโดยตรง</b> (ไม่ใช่ลิงก์โฟลเดอร์)<br />
                <b>Google Drive:</b> แชร์ <u>ไฟล์รูป</u> แบบ "ทุกคนที่มีลิงก์" แล้วใช้รูปแบบ <span className="code" style={{ fontSize: 'var(--fs-xs)' }}>https://drive.google.com/thumbnail?id=FILE_ID&amp;sz=w1000</span> (FILE_ID คือรหัสไฟล์จากลิงก์แชร์)
              </div>
            </div>
          </Group>

          <Group title="ที่ตั้ง & ผู้รับผิดชอบ">
            {fld('ที่ตั้ง (อาคาร/ห้อง)', 'location', { full: true, list: 'edit-locations' })}
            <datalist id="edit-locations">{masterLocations.map(l => <option key={l} value={l} />)}</datalist>
            {fld('ผู้รับผิดชอบ', 'owner', { full: true })}
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">สถานะการใช้งาน</label>
              <div className="seg" style={{ display: 'flex' }}>
                {[['up', 'ใช้งานได้'], ['repair', 'รอซ่อมบำรุง'], ['down', 'งดใช้ชั่วคราว']].map(([k, l]) =>
                  <button key={k} className={f.opKey === k ? 'on' : ''} style={{ flex: 1 }} onClick={() => set('opKey', k)}>{l}</button>)}
              </div>
            </div>
            {fld('หมายเหตุ', 'note', { full: true })}
          </Group>

          <Group title="การสอบเทียบ">
            {fld('วันสอบเทียบล่าสุด', 'cal', { type: 'date' })}
            {fld('วันครบกำหนดถัดไป', 'exp', { type: 'date' })}
            {fld('หน่วยงานสอบเทียบ', 'provider', { full: true })}
            {fld('เลขที่ใบรับรอง', 'certNo', { full: true })}
            {fld('จุดสอบเทียบ (Calibration point)', 'calPoint', { full: true })}
            {fld('พิสัยการใช้งาน', 'useRange', { full: true })}
            {fld('ค่า MPE / เกณฑ์ยอมรับ', 'mpe', { full: true })}
            {fld('ผลการสอบเทียบ (ผ่าน/รอดำเนินการ)', 'calResult', { full: true })}
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">รอบสอบเทียบ (ครั้ง/ปี)</label>
              <select className="input" value={f.calPerYear} onChange={e => set('calPerYear', e.target.value)}>
                {CAL_FREQ_OPTIONS.map(o => <option key={o.v} value={o.v}>{o.label}</option>)}
              </select>
            </div>
          </Group>

          <Group title="บำรุงรักษา (PM)">
            {fld('PM ล่าสุด', 'pmLast', { type: 'date' })}
            {fld('PM ครั้งถัดไป', 'pmNext', { type: 'date' })}
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">รอบ PM (ครั้ง/ปี)</label>
              <select className="input" value={f.pmPerYear} onChange={e => set('pmPerYear', e.target.value)}>
                {PM_FREQ_OPTIONS.map(o => <option key={o.v} value={o.v}>{o.label}</option>)}
              </select>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>เลือก "ไม่ต้อง PM" เพื่อซ่อนการ์ด PM ในหน้าเครื่องอัตโนมัติ</div>
            </div>
          </Group>

          <Group title="ทะเบียน (ISO 15189)">
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">สถานะทะเบียน</label>
              <div className="seg" style={{ display: 'flex' }}>
                {[['active', 'ใช้งาน (In service)'], ['decommissioned', 'ปลดระวาง (Decommissioned)']].map(([k, l]) =>
                  <button key={k} className={f.lifecycle === k ? 'on' : ''} style={{ flex: 1 }} onClick={() => set('lifecycle', k)}>{l}</button>)}
              </div>
            </div>
            {f.lifecycle === 'decommissioned' && fld('วันปลดระวาง', 'decommissionDate', { type: 'date' })}
            {f.lifecycle === 'decommissioned' && (
              <div>
                <label className="field-label">เหตุผลปลดระวาง</label>
                <select className="input" value={f.decommissionReasonKind} onChange={e => set('decommissionReasonKind', e.target.value)}>
                  <option value="">— ยังไม่ระบุ —</option>
                  {DECOMM_REASONS.map(r => <option key={r} value={r}>{r}</option>)}
                  <option value="อื่น ๆ">อื่น ๆ</option>
                </select>
              </div>
            )}
            {f.lifecycle === 'decommissioned' && f.decommissionReasonKind === 'อื่น ๆ' && fld('ระบุเหตุผล', 'decommissionReasonOther', { full: true })}
            {f.lifecycle === 'decommissioned' && (
              <div style={{ gridColumn: '1 / -1' }}>
                <label className="field-label">ถูกทดแทนด้วย</label>
                <select className="input" value={f.replacedBy} onChange={e => set('replacedBy', e.target.value)}>
                  <option value="">— ไม่มี —</option>
                  {replaceOptions.map(i => <option key={i.code} value={i.code}>{i.code} — {i.type}</option>)}
                </select>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 6 }}>เลือกเครื่องที่มาทดแทนเครื่องนี้ (ถ้ามี) — เลือกได้เฉพาะเครื่องที่ยังใช้งานอยู่</div>
              </div>
            )}
            <div>
              <label className="field-label">สภาพเมื่อรับเข้า</label>
              <select className="input" value={f.condition} onChange={e => set('condition', e.target.value)}>
                <option value="">— ยังไม่ระบุ —</option>
                {['ใหม่ (New)', 'ปรับปรุงสภาพ (Reconditioned)', 'รับโอน (Transferred-in)'].map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            {fld('วันเริ่มใช้งาน', 'commissionDate', { type: 'date' })}
            <div>
              <label className="field-label">ผลตรวจรับเข้า</label>
              <select className="input" value={f.acceptance} onChange={e => set('acceptance', e.target.value)}>
                <option value="">— ยังไม่ระบุ —</option>
                {['ผ่านการตรวจรับ (Accepted)', 'มีเงื่อนไข (Conditional)', 'ไม่ผ่าน (Rejected)'].map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            {fld('ผู้แทนจำหน่าย', 'vendor', { full: true })}
            {fld('ติดต่อผู้แทนฯ', 'vendorContact')}
            {fld('Software / Firmware', 'firmware')}
            {fld('วันหมดประกัน', 'warrantyEnd', { type: 'date' })}
            {fld('สัญญาบำรุงรักษา', 'serviceContract')}
            {fld('คู่มือการใช้งาน', 'manualRef', { full: true })}
          </Group>

          <Group title="ลิงก์ & สื่ออบรม">
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">ลิงก์วิดีโอสอนใช้เครื่อง (URL)</label>
              <input className="input" type="url" value={f.videoLink} placeholder="เช่น https://youtu.be/…" onChange={e => set('videoLink', e.target.value)} />
            </div>
            <div style={{ gridColumn: '1 / -1' }}>
              <label className="field-label">ลิงก์วิดีโอ Retraining (URL)</label>
              <input className="input" type="url" value={f.retrainLink} placeholder="เช่น https://youtu.be/…" onChange={e => set('retrainLink', e.target.value)} />
            </div>
          </Group>
        </div>

        <div style={{ display: 'flex', gap: 10, padding: '14px 22px', borderTop: '1px solid var(--line)' }}>
          <button className="btn" style={{ flex: 1 }} onClick={onClose}>ยกเลิก</button>
          <button className="btn btn-primary" style={{ flex: 1 }} onClick={save}><I.check size={17} /> บันทึกการแก้ไข</button>
        </div>
      </div>
    </>
  );
}
window.EditDrawer = EditDrawer;
