// ============ Production Log (4C) ============
// บันทึกการผลิต → ตัดสต็อกวัตถุดิบอัตโนมัติตามสูตร

function buildProductionIngredients(db, menuId, qty) {
  // หา stock item สำหรับแต่ละวัตถุดิบในสูตร
  const stockItemMap = {};
  (db.stockItems || []).forEach(s => {
    if (s.refType === 'ingredient') stockItemMap[s.refId] = s;
  });

  const result = [];
  const cost = computeMenuCost(db, menuId);

  // วัตถุดิบจาก recipeBase
  (cost.baseLines || []).forEach(line => {
    const si = stockItemMap[line.ingId];
    if (si) result.push({ stockItemId: si.id, name: si.name || line.name, qty: -(line.qty * qty), unit: si.unit });
  });

  // วัตถุดิบจาก recipeBatch (flatten)
  (db.recipeBatch || []).filter(r => r.menuId === menuId).forEach(rb => {
    const b = (db.batchRecipes || []).find(x => x.id === rb.batchId);
    if (!b) return;
    const qtyPerBatch = rb.qty || 0;
    const outputQty = b.outputQty || 1;
    const batchesNeeded = (qtyPerBatch * qty) / outputQty;
    (db.batchRecipeLines || []).filter(l => l.batchId === rb.batchId).forEach(line => {
      const si = stockItemMap[line.ingId];
      if (si) result.push({ stockItemId: si.id, name: si.name || line.ingId, qty: -(line.qty * batchesNeeded), unit: si.unit });
    });
  });

  return result;
}

function ProductionLogPage({ go }) {
  const { fdb: db, setDb, logActivity, flash } = useData();
  const [tab, setTab] = React.useState('log'); // 'log' | 'history'
  const [menuSearch, setMenuSearch] = React.useState('');
  const [selectedMenu, setSelectedMenu] = React.useState(null);
  const [qty, setQty] = React.useState('1');
  const [note, setNote] = React.useState('');
  const [date, setDate] = React.useState(new Date().toLocaleDateString('en-CA'));
  const [busy, setBusy] = React.useState(false);

  const menus = React.useMemo(() => {
    return (db.menus || [])
      .filter(m => m.status !== 'inactive')
      .filter(m => !menuSearch || m.name.toLowerCase().includes(menuSearch.toLowerCase()));
  }, [db.menus, menuSearch]);

  const ingredients = React.useMemo(() => {
    if (!selectedMenu) return [];
    return buildProductionIngredients(db, selectedMenu.id, Number(qty) || 1);
  }, [db, selectedMenu, qty]);

  const hasStock = React.useMemo(() => {
    if (!selectedMenu) return true;
    const stockItemMap = {};
    (db.stockItems || []).forEach(s => { stockItemMap[s.id] = s; });
    const balances = {};
    (db.stockBalances || []).forEach(b => { balances[b.stockItemId] = Number(b.onHand) || 0; });
    return ingredients.every(ing => {
      const onHand = balances[ing.stockItemId] ?? 0;
      return onHand >= Math.abs(ing.qty);
    });
  }, [db, selectedMenu, ingredients]);

  const confirmProd = async () => {
    if (!selectedMenu) { flash('เลือกเมนูก่อน', 'err'); return; }
    const q = Number(qty);
    if (!q || q <= 0) { flash('ใส่จำนวนที่ถูกต้อง', 'err'); return; }
    setBusy(true);
    let newDb = { ...db };

    // ตัดสต็อกวัตถุดิบแต่ละตัว
    for (const ing of ingredients) {
      const updates = stockApplyMovement(newDb, ing.stockItemId, ing.qty, 'production',
        note || `ผลิต ${selectedMenu.name} ×${q}`, 'menu', selectedMenu.id,
        date + 'T' + new Date().toTimeString().slice(0, 8));
      newDb = { ...newDb, ...updates };
    }

    // บันทึก productionEvent
    const evId = nextCode(newDb.productionEvents || [], 'PROD');
    newDb.productionEvents = [...(newDb.productionEvents || []), {
      id: evId,
      menuId: selectedMenu.id,
      menuName: selectedMenu.name,
      qtyProduced: q,
      producedAt: date + 'T' + new Date().toTimeString().slice(0, 8),
      note: note || '',
      ingredientsUsed: ingredients.map(i => ({ stockItemId: i.stockItemId, name: i.name, qty: i.qty, unit: i.unit })),
    }];

    setDb(newDb);
    if (logActivity) logActivity('production.log', { entityType: 'menu', entityId: selectedMenu.id, note: `ผลิต ${selectedMenu.name} ×${q}` });
    flash(`บันทึกการผลิต ${selectedMenu.name} ×${q} แล้ว${ingredients.length ? ` · ตัดสต็อก ${ingredients.length} รายการ` : ''}`);
    setSelectedMenu(null);
    setQty('1');
    setNote('');
    setBusy(false);
  };

  const history = React.useMemo(() => {
    return [...(db.productionEvents || [])].sort((a, b) => (b.producedAt || '').localeCompare(a.producedAt || '')).slice(0, 50);
  }, [db.productionEvents]);

  const fmtDt = iso => {
    if (!iso) return '–';
    const d = new Date(iso);
    return d.toLocaleDateString('th-TH', { day: '2-digit', month: 'short' }) + ' ' + d.toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div style={{ maxWidth: 700, margin: '0 auto', paddingBottom: 80 }}>
      <Segmented value={tab} onChange={setTab} options={[{ value: 'log', label: 'บันทึกการผลิต' }, { value: 'history', label: 'ประวัติ' }]} />

      {tab === 'log' && (
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Step 1: เลือกเมนู */}
          <div style={{ background: 'var(--surface)', borderRadius: 16, padding: 16, boxShadow: 'var(--shadow)' }}>
            <div style={{ fontWeight: 600, marginBottom: 12 }}>1. เลือกเมนูที่ผลิต</div>
            <Input placeholder="ค้นหาเมนู..." value={menuSearch} onChange={e => { setMenuSearch(e.target.value); setSelectedMenu(null); }} />
            {menuSearch && (
              <div style={{ marginTop: 8, borderRadius: 10, border: '1px solid var(--line-2)', overflow: 'hidden', maxHeight: 200, overflowY: 'auto' }}>
                {menus.length === 0 && <div style={{ padding: 12, color: 'var(--ink-3)', fontSize: 13 }}>ไม่พบเมนู</div>}
                {menus.map(m => (
                  <button key={m.id} onClick={() => { setSelectedMenu(m); setMenuSearch(m.name); }}
                    style={{ width: '100%', textAlign: 'left', padding: '10px 14px', background: selectedMenu?.id === m.id ? 'var(--accent-soft)' : 'none', border: 'none', cursor: 'pointer', fontSize: 14, borderBottom: '1px solid var(--line-2)' }}>
                    {m.name}
                    <span style={{ float: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{m.category}</span>
                  </button>
                ))}
              </div>
            )}
            {selectedMenu && (
              <div style={{ marginTop: 8, padding: '10px 14px', background: 'var(--accent-soft)', borderRadius: 10, fontSize: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontWeight: 600 }}>✅ {selectedMenu.name}</span>
                <button onClick={() => { setSelectedMenu(null); setMenuSearch(''); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 18 }}>×</button>
              </div>
            )}
          </div>

          {/* Step 2: จำนวน + วันที่ */}
          <div style={{ background: 'var(--surface)', borderRadius: 16, padding: 16, boxShadow: 'var(--shadow)' }}>
            <div style={{ fontWeight: 600, marginBottom: 12 }}>2. จำนวนและวันที่ผลิต</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="จำนวนที่ผลิต">
                <Input type="number" min="1" value={qty} onChange={e => setQty(e.target.value)} placeholder="1" />
              </Field>
              <Field label="วันที่ผลิต">
                <Input type="date" value={date} onChange={e => setDate(e.target.value)} />
              </Field>
            </div>
            <div style={{ marginTop: 12 }}>
              <Field label="หมายเหตุ (ถ้ามี)">
                <Input value={note} onChange={e => setNote(e.target.value)} placeholder="เช่น ล็อตเช้า" />
              </Field>
            </div>
          </div>

          {/* Step 3: แสดงสต็อกที่จะตัด */}
          {selectedMenu && ingredients.length > 0 && (
            <div style={{ background: 'var(--surface)', borderRadius: 16, padding: 16, boxShadow: 'var(--shadow)' }}>
              <div style={{ fontWeight: 600, marginBottom: 10 }}>3. วัตถุดิบที่จะตัดสต็อก</div>
              {ingredients.map((ing, i) => {
                const balance = (db.stockBalances || []).find(b => b.stockItemId === ing.stockItemId);
                const onHand = Number(balance?.onHand) || 0;
                const need = Math.abs(ing.qty);
                const enough = onHand >= need;
                return (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: i < ingredients.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                    <span style={{ fontSize: 14 }}>{ing.name}</span>
                    <span style={{ fontSize: 13, color: enough ? 'var(--ink-2)' : 'var(--red)', fontWeight: enough ? 400 : 600 }}>
                      -{need.toFixed(2)} {ing.unit}
                      <span style={{ color: 'var(--ink-3)', marginLeft: 6 }}>(คงเหลือ {onHand} {ing.unit})</span>
                      {!enough && <span style={{ marginLeft: 6 }}>⚠️ ไม่พอ</span>}
                    </span>
                  </div>
                );
              })}
              {!hasStock && (
                <div style={{ marginTop: 10, padding: '8px 12px', background: 'var(--red-soft, #fff0f0)', borderRadius: 8, fontSize: 13, color: 'var(--red)' }}>
                  ⚠️ วัตถุดิบบางรายการไม่เพียงพอ — สามารถบันทึกได้ แต่สต็อกจะติดลบ
                </div>
              )}
            </div>
          )}

          {selectedMenu && ingredients.length === 0 && (
            <div style={{ background: 'var(--chip)', borderRadius: 12, padding: '12px 16px', fontSize: 13, color: 'var(--ink-3)' }}>
              ℹ️ เมนูนี้ไม่มีสูตรวัตถุดิบที่ track สต็อก — บันทึกได้แต่จะไม่ตัดสต็อกอัตโนมัติ
            </div>
          )}

          <Button onClick={confirmProd} disabled={!selectedMenu || busy} icon="plus">
            {busy ? 'กำลังบันทึก...' : 'บันทึกการผลิต'}
          </Button>
        </div>
      )}

      {tab === 'history' && (
        <div style={{ marginTop: 16 }}>
          {history.length === 0 && (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}>ยังไม่มีประวัติการผลิต</div>
          )}
          {history.map((ev, i) => (
            <div key={ev.id} style={{ background: 'var(--surface)', borderRadius: 14, padding: '13px 16px', marginBottom: 10, boxShadow: 'var(--shadow)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 15 }}>{ev.menuName || ev.menuId}</div>
                  <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 2 }}>
                    {fmtDt(ev.producedAt)}{ev.note ? ` · ${ev.note}` : ''}
                  </div>
                </div>
                <Badge tone="blue">×{ev.qtyProduced}</Badge>
              </div>
              {(ev.ingredientsUsed || []).length > 0 && (
                <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-3)' }}>
                  ตัดสต็อก: {ev.ingredientsUsed.map(i => `${i.name} ${Math.abs(i.qty).toFixed(2)} ${i.unit}`).join(' · ')}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ProductionLogPage });
