/* ============================================================
   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 }) {
  return (
    <div style={full ? { gridColumn: '1 / -1' } : {}}>
      <label className="field-label">{label}</label>
      <input className="input" type={type || 'text'} value={value} placeholder={placeholder || ''} onChange={e => onChange(e.target.value)} />
    </div>
  );
}

function EditDrawer({ inst, onClose, onSave }) {
  const meta = useMemo(() => instrumentMeta(inst), [inst]);
  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 || '',
    opKey: meta.op.key, location: meta.location, owner: meta.owner,
    provider: meta.provider, certNo: meta.certNo, pmLast: meta.pmLast || '', pmNext: meta.pmNext || '',
    condition: meta.condition || '', commissionDate: meta.commissionDate || '', 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 || '',
  });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const save = () => {
    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,
      opKey: f.opKey, location: f.location, owner: f.owner, provider: f.provider, certNo: f.certNo,
      pmLast: f.pmLast || null, pmNext: f.pmNext || null,
      condition: f.condition || null, commissionDate: f.commissionDate || null, vendor: f.vendor || null,
      vendorContact: f.vendorContact || null, firmware: f.firmware || '—',
      warrantyEnd: f.warrantyEnd || null, serviceContract: f.serviceContract || null, manualRef: f.manualRef || null,
      lifecycle: f.lifecycle, decommissionDate: f.lifecycle === 'decommissioned' ? (f.decommissionDate || null) : null,
    });
    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} />;

  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')}
          </Group>

          <Group title="ที่ตั้ง & ผู้รับผิดชอบ">
            {fld('ที่ตั้ง (อาคาร/ห้อง)', 'location', { full: true })}
            {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>
          </Group>

          <Group title="การสอบเทียบ">
            {fld('วันสอบเทียบล่าสุด', 'cal', { type: 'date' })}
            {fld('วันครบกำหนดถัดไป', 'exp', { type: 'date' })}
            {fld('หน่วยงานสอบเทียบ', 'provider', { full: true })}
            {fld('เลขที่ใบรับรอง', 'certNo', { full: true })}
          </Group>

          <Group title="บำรุงรักษา (PM)">
            {fld('PM ล่าสุด', 'pmLast', { type: 'date' })}
            {fld('PM ครั้งถัดไป', 'pmNext', { type: 'date' })}
            {fld('หมายเหตุ', 'note', { full: true })}
          </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' })}
            <div>
              <label className="field-label">สภาพเมื่อรับเข้า</label>
              <select className="input" value={f.condition} onChange={e => set('condition', e.target.value)}>
                {['ใหม่ (New)', 'ปรับปรุงสภาพ (Reconditioned)', 'รับโอน (Transferred-in)'].map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </div>
            {fld('วันเริ่มใช้งาน', 'commissionDate', { type: 'date' })}
            {fld('ผู้แทนจำหน่าย', 'vendor', { full: true })}
            {fld('ติดต่อผู้แทนฯ', 'vendorContact')}
            {fld('Software / Firmware', 'firmware')}
            {fld('วันหมดประกัน', 'warrantyEnd', { type: 'date' })}
            {fld('สัญญาบำรุงรักษา', 'serviceContract')}
            {fld('คู่มือการใช้งาน', 'manualRef', { full: true })}
          </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;
