// ============ Expense Log — บันทึกค่าใช้จ่ายจริงรายเดือน ============
// ต่างจาก db.overhead (งบประมาณคงที่) → นี่คือรายการที่จ่ายจริงแต่ละเดือน

const EXP_CATS = [
  { value: 'rent',        label: '🏠 ค่าเช่า',            color: 'var(--purple)' },
  { value: 'utilities',   label: '💡 ค่าไฟ/น้ำ',          color: 'var(--accent)' },
  { value: 'labor',       label: '👷 ค่าแรงงาน',          color: 'var(--green)' },
  { value: 'marketing',   label: '📢 การตลาด',            color: 'var(--teal)' },
  { value: 'maintenance', label: '🔧 ซ่อมบำรุง',          color: 'var(--orange)' },
  { value: 'supplies',    label: '📦 อุปกรณ์/สิ้นเปลือง', color: 'var(--ink-2)' },
  { value: 'other',       label: '📝 อื่นๆ',              color: 'var(--ink-3)' },
];

function expCatMeta(v) {
  return EXP_CATS.find(c => c.value === v) || { label: v || 'อื่นๆ', color: 'var(--ink-3)' };
}

function expenseMonthTotal(db, monthKey) {
  return (db.expenseEvents || [])
    .filter(e => String(e.paidAt || e.createdAt || '').startsWith(monthKey))
    .reduce((s, e) => s + (Number(e.amount) || 0), 0);
}

function ExpensePage({ go }) {
  const { fdb: db, setDb, flash, settings } = useData();
  const [tab, setTab] = React.useState('log');
  const [form, setForm] = React.useState({
    category: 'rent',
    amount: '',
    note: '',
    paidAt: new Date().toLocaleDateString('en-CA'),
  });
  const [filterMonth, setFilterMonth] = React.useState(new Date().toISOString().slice(0, 7));

  const THAI_M = ['','ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'];
  const thaiMonth = key => { if (!key) return ''; const [y,m] = key.split('-'); return `${THAI_M[+m]||m} ${+y+543}`; };

  const now = new Date();
  const last6 = Array.from({ length: 6 }, (_, i) => {
    const d = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1);
    return d.toISOString().slice(0, 7);
  });

  const expenses = (db.expenseEvents || []).slice()
    .sort((a, b) => String(b.paidAt||b.createdAt||'').localeCompare(String(a.paidAt||a.createdAt||'')));
  const thisMonth = expenses.filter(e => String(e.paidAt||e.createdAt||'').startsWith(filterMonth));
  const thisTotal = thisMonth.reduce((s, e) => s + (Number(e.amount) || 0), 0);
  const budget = overheadTotal(db);

  const byCat = EXP_CATS.map(cat => ({
    ...cat,
    total: thisMonth.filter(e => e.category === cat.value).reduce((s, e) => s + (Number(e.amount) || 0), 0),
  })).filter(c => c.total > 0);

  const allMonths = Array.from(new Set([
    ...last6,
    ...expenses.map(e => String(e.paidAt||e.createdAt||'').slice(0, 7)).filter(Boolean),
  ])).sort().reverse();
  const monthOpts = allMonths.map(m => ({ value: m, label: thaiMonth(m) }));

  const save = () => {
    const amount = Number(form.amount);
    if (!amount || amount <= 0) { flash('ใส่จำนวนเงิน', 'err'); return; }
    const id = nextCode(db.expenseEvents || [], 'EXP');
    setDb(prev => ({
      ...prev,
      expenseEvents: [...(prev.expenseEvents || []), {
        id, category: form.category, amount, note: form.note.trim(),
        paidAt: form.paidAt, createdAt: new Date().toISOString(),
      }],
    }));
    flash(`บันทึก ${expCatMeta(form.category).label} ฿${fmtB(amount)} แล้ว`);
    setForm(f => ({ ...f, amount: '', note: '' }));
  };

  const del = id => {
    setDb(prev => ({ ...prev, expenseEvents: (prev.expenseEvents || []).filter(e => e.id !== id) }));
    flash('ลบรายการแล้ว');
  };

  const TabBtn = ({ id, label }) => (
    <button onClick={() => setTab(id)} style={{
      padding: '7px 16px', borderRadius: 10, border: 'none',
      background: tab === id ? 'var(--accent)' : 'var(--chip)',
      color: tab === id ? '#fff' : 'var(--ink-2)',
      fontWeight: tab === id ? 700 : 400, fontSize: 13.5, cursor: 'pointer',
    }}>{label}</button>
  );

  return (
    <div className="view-enter" style={{ display: 'grid', gap: 18 }}>

      {/* summary */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }} className="r-2col">
        <Stat label="ค่าใช้จ่ายจริง" value={fmtB(thisTotal, 0)} icon="wallet" tone="var(--orange)"
          sub={thaiMonth(filterMonth)} />
        <Stat label="งบที่ตั้งไว้" value={budget > 0 ? fmtB(budget, 0) : '—'} icon="doc"
          sub="Master › ค่าใช้จ่าย" />
        <Stat label="ต่างจากงบ"
          value={budget > 0 && thisTotal > 0 ? `${thisTotal > budget ? '+' : ''}${fmtB(thisTotal - budget, 0)}` : '—'}
          icon="trend"
          tone={budget > 0 && thisTotal > 0 ? (thisTotal <= budget ? 'var(--green)' : 'var(--red)') : 'var(--ink-3)'}
          sub={budget > 0 && thisTotal > 0 ? (thisTotal <= budget ? 'อยู่ในงบ ✓' : 'เกินงบ') : 'ยังไม่มีข้อมูล'} />
      </div>

      <Card>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <TabBtn id="log" label="บันทึก" />
            <TabBtn id="history" label="ประวัติ" />
            <TabBtn id="compare" label="6 เดือน" />
          </div>
          <div style={{ minWidth: 160 }}>
            <Select value={filterMonth} onChange={e => setFilterMonth(e.target.value)} options={monthOpts} />
          </div>
        </div>

        {/* ---- tab: บันทึก ---- */}
        {tab === 'log' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="หมวดหมู่">
                <Select value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))}
                  options={EXP_CATS.map(c => ({ value: c.value, label: c.label }))} />
              </Field>
              <Field label="วันที่จ่าย">
                <Input type="date" value={form.paidAt} onChange={e => setForm(f => ({ ...f, paidAt: e.target.value }))} />
              </Field>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <Field label="จำนวนเงิน (บาท)">
                <Input type="number" value={form.amount} min="0"
                  onChange={e => setForm(f => ({ ...f, amount: e.target.value }))} placeholder="เช่น 15000" />
              </Field>
              <Field label="หมายเหตุ">
                <Input value={form.note} onChange={e => setForm(f => ({ ...f, note: e.target.value }))}
                  placeholder="เช่น ค่าเช่าเดือน มิ.ย." />
              </Field>
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button icon="plus" onClick={save}>บันทึกรายการ</Button>
            </div>

            {/* bar breakdown this month */}
            {byCat.length > 0 && (
              <div style={{ borderTop: '1px solid var(--line-2)', paddingTop: 14 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 10 }}>
                  {thaiMonth(filterMonth)} · รวม {fmtB(thisTotal, 0)} บาท
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                  {byCat.map(cat => (
                    <div key={cat.value} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ fontSize: 13, minWidth: 170, color: 'var(--ink-2)' }}>{cat.label}</span>
                      <div style={{ flex: 1, height: 8, borderRadius: 4, background: 'var(--chip)', overflow: 'hidden' }}>
                        <div style={{
                          height: '100%', borderRadius: 4,
                          background: cat.color,
                          width: `${thisTotal > 0 ? Math.max(2, (cat.total / thisTotal) * 100) : 0}%`,
                          transition: 'width .3s',
                        }} />
                      </div>
                      <span className="tnum" style={{ fontSize: 13.5, fontWeight: 600, minWidth: 90, textAlign: 'right' }}>
                        {fmtB(cat.total, 0)}
                      </span>
                      <span style={{ fontSize: 12, color: 'var(--ink-3)', minWidth: 36, textAlign: 'right' }}>
                        {thisTotal > 0 ? Math.round((cat.total / thisTotal) * 100) : 0}%
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {thisTotal === 0 && (
              <Empty icon="wallet" title="ยังไม่มีรายการ" sub="เพิ่มค่าใช้จ่ายจริงของเดือนนี้ เพื่อให้ KPI คำนวณกำไรสุทธิถูกต้อง" />
            )}
          </div>
        )}

        {/* ---- tab: ประวัติ ---- */}
        {tab === 'history' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {thisMonth.length === 0
              ? <Empty icon="wallet" title="ยังไม่มีรายการ" sub={`กด 'บันทึก' เพื่อเพิ่มค่าใช้จ่ายเดือน ${thaiMonth(filterMonth)}`} />
              : thisMonth.map(e => {
                  const meta = expCatMeta(e.category);
                  return (
                    <div key={e.id} style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 12,
                      borderLeft: `3px solid ${meta.color}`,
                    }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 600, fontSize: 14 }}>{meta.label}</div>
                        <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                          {e.paidAt || String(e.createdAt || '').slice(0, 10)}
                          {e.note ? ` · ${e.note}` : ''}
                        </div>
                      </div>
                      <span className="tnum" style={{ fontWeight: 700, fontSize: 16 }}>{fmtB(Number(e.amount), 0)}</span>
                      <IconBtn name="trash" danger title="ลบ" onClick={() => del(e.id)} />
                    </div>
                  );
                })}

            {thisMonth.length > 0 && (
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 10, borderTop: '1px solid var(--line-2)' }}>
                <span className="tnum" style={{ fontWeight: 700, fontSize: 15 }}>รวม {fmtB(thisTotal, 0)} บาท</span>
                <Button variant="secondary" size="sm" icon="download" onClick={() => {
                  const csv = '﻿' + ['วันที่,หมวด,จำนวน,หมายเหตุ',
                    ...thisMonth.map(e => `"${e.paidAt||''}","${expCatMeta(e.category).label}","${e.amount}","${e.note||''}"`)
                  ].join('\n');
                  const a = document.createElement('a');
                  a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
                  a.download = `expenses-${filterMonth}.csv`;
                  a.click();
                  flash('Export แล้ว');
                }}>Export CSV</Button>
              </div>
            )}
          </div>
        )}

        {/* ---- tab: 6 เดือน ---- */}
        {tab === 'compare' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ borderBottom: '2px solid var(--line)', color: 'var(--ink-3)', fontSize: 12 }}>
                    <th style={{ textAlign: 'left', padding: '6px 8px', fontWeight: 500 }}>เดือน</th>
                    <th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 500 }}>จ่ายจริง</th>
                    <th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 500 }}>งบ</th>
                    <th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 500 }}>ต่าง</th>
                    {EXP_CATS.map(c => (
                      <th key={c.value} style={{ textAlign: 'right', padding: '6px 6px', fontWeight: 500, whiteSpace: 'nowrap' }}>
                        {c.label.split(' ')[0]}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {last6.map(mKey => {
                    const actual = expenseMonthTotal(db, mKey);
                    const diff = actual - budget;
                    return (
                      <tr key={mKey}
                        style={{ borderBottom: '1px solid var(--line-2)', cursor: 'pointer', background: mKey === filterMonth ? 'var(--accent-soft)' : 'transparent' }}
                        onClick={() => { setFilterMonth(mKey); setTab('log'); }}>
                        <td style={{ padding: '9px 8px', fontWeight: 600 }}>{thaiMonth(mKey)}</td>
                        <td className="tnum" style={{ textAlign: 'right', padding: '9px 8px', fontWeight: 700 }}>
                          {actual > 0 ? fmtB(actual, 0) : <span style={{ color: 'var(--ink-3)' }}>—</span>}
                        </td>
                        <td className="tnum" style={{ textAlign: 'right', padding: '9px 8px', color: 'var(--ink-3)' }}>
                          {budget > 0 ? fmtB(budget, 0) : '—'}
                        </td>
                        <td className="tnum" style={{
                          textAlign: 'right', padding: '9px 8px', fontWeight: 600,
                          color: actual > 0 ? (diff > 0 ? 'var(--red)' : 'var(--green)') : 'var(--ink-3)',
                        }}>
                          {actual > 0 ? `${diff > 0 ? '+' : ''}${fmtB(diff, 0)}` : '—'}
                        </td>
                        {EXP_CATS.map(cat => {
                          const t = (db.expenseEvents || [])
                            .filter(e => String(e.paidAt||e.createdAt||'').startsWith(mKey) && e.category === cat.value)
                            .reduce((s, e) => s + (Number(e.amount) || 0), 0);
                          return (
                            <td key={cat.value} className="tnum" style={{ textAlign: 'right', padding: '9px 6px', color: t > 0 ? 'var(--ink)' : 'var(--ink-3)', fontSize: 12.5 }}>
                              {t > 0 ? fmtB(t, 0) : '—'}
                            </td>
                          );
                        })}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {budget === 0 && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 16px', background: 'var(--orange-soft)', borderRadius: 12, fontSize: 13.5 }}>
                <span>⚠️ ยังไม่ได้ตั้งงบรายเดือน</span>
                <Button size="sm" variant="secondary" onClick={() => go && go('master')}>ไปหน้า Master</Button>
              </div>
            )}
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { ExpensePage, expCatMeta, expenseMonthTotal });
