// screen-debts-reports.jsx — Hutang/Piutang + Laporan

// ─── DEBTS / HUTANG-PIUTANG ──────────────────────────────────────
function ScreenDebts({ theme, accent, scenario, auth }) {
  const [realDebts, setRealDebts] = React.useState(null);
  const familyId = auth && auth.family && auth.family.id;
  React.useEffect(function() {
    if (!familyId || !window.sbGetDebts) return;
    sbGetDebts(familyId).then(function(r) { if (!r.error) setRealDebts(r.data||[]); });
  }, [familyId]);
  const isAuth = !!(auth && auth.family);
  const [showAdd, setShowAdd] = React.useState(false);
  const [dKind, setDKind]     = React.useState('hutang');
  const [dWho, setDWho]       = React.useState('');
  const [dAmount, setDAmount] = React.useState('');
  const [dNote, setDNote]     = React.useState('');
  const [dDue, setDDue]       = React.useState('');
  const [dSaving, setDSaving] = React.useState(false);

  async function handleAddDebt() {
    if (!dWho || !dAmount) return;
    setDSaving(true);
    var amount = parseInt(dAmount.replace(/\D/g,''), 10);
    if (window.sbAddDebt && auth && auth.family && auth.user) {
      await sbAddDebt(auth.family.id, auth.user.id, {
        kind: dKind, who: dWho, amount: amount,
        note: dNote, due: dDue || null,
      });
      var r = await sbGetDebts(auth.family.id);
      if (!r.error) setRealDebts(r.data||[]);
    }
    setShowAdd(false); setDWho(''); setDAmount(''); setDNote(''); setDDue('');
    setDSaving(false);
  }

  const [tab, setTab] = React.useState('all');
  const totals = {
    hutang:  (isAuth?(realDebts||[]):scenario.debts).filter((d) => (d.kind||d.type) === 'hutang')
                  .reduce((a, d) => a + d.amount, 0),
    piutang: (isAuth?(realDebts||[]):scenario.debts).filter((d) => (d.kind||d.type) === 'piutang')
                  .reduce((a, d) => a + d.amount, 0),
  };
  function normDebt(d) {
    if (d.original_amount !== undefined) {
      return {
        id: d.id, kind: d.type, who: d.counterparty,
        amount: d.original_amount, paid: d.paid_amount||0,
        status: d.status, due: d.due_date,
        desc: d.description, isReal: true,
        outstanding: d.original_amount - (d.paid_amount||0),
      };
    }
    return d;
  }
  let items = (isAuth ? (realDebts||[]) : scenario.debts).map(normDebt);
  if (tab !== 'all') items = items.filter((d) => d.kind === tab);

  return (
    <div style={{ background: theme.bg, paddingBottom: 100 }}>
      <div style={{ padding: '56px 20px 16px',
                    display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800,
                       letterSpacing: '-0.025em', color: theme.fg1 }}>Hutang & Piutang</h1>
          <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 500, marginTop: 2 }}>
            {items.length} catatan aktif
          </div>
        </div>
        <button style={iconBtn2(theme)} onClick={() => setShowAdd(true)}>
          <Icon name="plus" size={18} color={theme.fg1} stroke={2} />
        </button>
      </div>

      {/* Two summary cards */}
      <div style={{ padding: '0 20px 16px', display: 'flex', gap: 10 }}>
        <DebtSummary theme={theme} kind="hutang"  amount={totals.hutang} />
        <DebtSummary theme={theme} kind="piutang" amount={totals.piutang} />
      </div>

      {/* Tabs */}
      <div style={{ padding: '0 20px 14px', display: 'flex', gap: 8 }}>
        {[
          { id: 'all',     label: 'Semua' },
          { id: 'hutang',  label: 'Hutang' },
          { id: 'piutang', label: 'Piutang' },
        ].map((t) => (
          <Chip key={t.id} active={tab === t.id} onClick={() => setTab(t.id)} theme={theme}>
            {t.label}
          </Chip>
        ))}
      </div>

      {/* List */}
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((d) => <DebtRow key={d.id} debt={d} theme={theme} accent={accent} />)}
        {items.length === 0 && <EmptyState theme={theme} icon="check-check"
                                title="Tidak ada catatan" hint="Bersih, semua sudah lunas." />}
      </div>
      <ScreenDebtAddModal show={showAdd} onClose={()=>setShowAdd(false)}
        dKind={dKind} setDKind={setDKind} dWho={dWho} setDWho={setDWho}
        dAmount={dAmount} setDAmount={setDAmount} dNote={dNote} setDNote={setDNote}
        dDue={dDue} setDDue={setDDue} onSave={handleAddDebt} saving={dSaving}
        theme={theme} accent={accent} />
    </div>
  );
}

function DebtSummary({ theme, kind, amount }) {
  const isHutang = kind === 'hutang';
  const color = isHutang ? theme.danger : theme.success;
  const soft = isHutang ? theme.dangerSoft : theme.successSoft;
  return (
    <div style={{
      flex: 1, position: 'relative', overflow: 'hidden',
      background: theme.surface,
      border: `0.5px solid ${theme.border}`,
      borderRadius: 16, padding: 14,
      boxShadow: theme.shadow1,
    }}>
      <div style={{
        position: 'absolute', top: -10, right: -10,
        width: 70, height: 70, borderRadius: '50%',
        background: soft, opacity: 0.6,
      }} />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
          <div style={{
            width: 24, height: 24, borderRadius: 8,
            background: soft,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name={isHutang ? 'arrow-up-right' : 'arrow-down-left'}
                  size={13} color={color} stroke={2.2} />
          </div>
          <span style={{ fontSize: 11, fontWeight: 600, color: theme.fg2,
                         letterSpacing: '0.02em' }}>
            {isHutang ? 'Hutang' : 'Piutang'}
          </span>
        </div>
        <div style={{
          fontSize: 18, fontWeight: 800, color: theme.fg1,
          letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums',
        }}>{fmtRp(amount, { short: true })}</div>
        <div style={{ fontSize: 11, color: theme.fg3, fontWeight: 500, marginTop: 2 }}>
          {isHutang ? 'yang harus dibayar' : 'yang akan diterima'}
        </div>
      </div>
    </div>
  );
}

function DebtRow({ debt, theme, accent }) {
  const isHutang = debt.kind === 'hutang';
  const isOver = debt.status === 'overdue';
  const due = new Date(debt.due);
  const daysLeft = Math.round((due - new Date()) / 86400000);
  return (
    <Card theme={theme} padding={14}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 42, height: 42, borderRadius: 14,
          background: isHutang ? theme.dangerSoft : theme.successSoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name={isHutang ? 'arrow-up-right' : 'arrow-down-left'}
                size={20} stroke={1.9}
                color={isHutang ? theme.danger : theme.success} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: theme.fg1,
                           letterSpacing: '-0.005em' }}>{debt.who}</span>
            {isOver && <Badge theme={theme} color="danger">Telat</Badge>}
            {!isOver && daysLeft <= 7 && <Badge theme={theme} color="warning">{daysLeft}h lagi</Badge>}
          </div>
          <div style={{
            fontSize: 12, color: theme.fg2, fontWeight: 500, marginTop: 2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{debt.note}</div>
          <div style={{ fontSize: 11, color: theme.fg3, fontWeight: 500, marginTop: 2 }}>
            Jatuh tempo {fmtDateLong(debt.due)}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{
            fontSize: 15, fontWeight: 800,
            color: isHutang ? theme.danger : theme.success,
            fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em',
          }}>{fmtRp(debt.amount, { short: true })}</div>
          <button style={{
            appearance: 'none', border: 0, cursor: 'pointer',
            marginTop: 4, padding: '4px 10px', borderRadius: 8,
            background: theme.surfaceAlt, color: theme.fg2,
            fontSize: 10, fontWeight: 700,
          }}>{isHutang ? 'Bayar' : 'Tagih'}</button>
        </div>
      </div>
    </Card>
  );
}

// ─── REPORTS / LAPORAN ───────────────────────────────────────────

function ScreenDebtAddModal({ show, onClose, dKind, setDKind, dWho, setDWho, dAmount, setDAmount, dNote, setDNote, dDue, setDDue, onSave, saving, theme, accent }) {
  if (!show) return null;
  return (
    <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,0.5)',display:'flex',alignItems:'flex-end',justifyContent:'center'}}
      onClick={e => { if(e.target===e.currentTarget) onClose(); }}>
      <div style={{background:theme.surface,borderRadius:'24px 24px 0 0',padding:'24px 20px 48px',width:'100%',maxWidth:480,maxHeight:'90vh',overflowY:'auto'}}>
        <div style={{width:40,height:4,background:theme.border,borderRadius:99,margin:'0 auto 20px'}}/>
        <div style={{fontSize:18,fontWeight:800,color:theme.fg1,marginBottom:16}}>Catat Hutang/Piutang</div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:14,padding:4,background:theme.surfaceAlt,borderRadius:12}}>
          {['hutang','piutang'].map(function(t){
            return <button key={t} onClick={()=>setDKind(t)}
              style={{height:40,borderRadius:10,border:0,cursor:'pointer',fontWeight:700,fontSize:13,fontFamily:'inherit',
                background:dKind===t?(t==='hutang'?'#ef4444':'#10b981'):'transparent',
                color:dKind===t?'#fff':theme.fg2}}>
              {t==='hutang'?'🔴 Hutang (kita)':'🟢 Piutang (orang)'}
            </button>;
          })}
        </div>
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>{dKind==='hutang'?'Nama Pemberi Hutang':'Nama Peminjam'}</div>
          <input type="text" placeholder="Misal: Pak Budi, BCA..." value={dWho} onChange={e=>setDWho(e.target.value)} autoFocus
            style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+theme.border,background:theme.bg,color:theme.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Jumlah</div>
          <div style={{display:'flex',alignItems:'center',gap:8,background:theme.bg,border:'1.5px solid '+theme.border,borderRadius:12,padding:'0 14px'}}>
            <span style={{color:theme.fg3,fontSize:13}}>Rp</span>
            <input type="text" inputMode="numeric" placeholder="0" value={dAmount}
              onChange={e=>setDAmount(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'))}
              style={{flex:1,height:48,border:0,outline:'none',background:'transparent',fontSize:16,fontWeight:700,color:theme.fg1,fontFamily:'inherit'}}/>
          </div>
        </div>
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Keterangan (opsional)</div>
          <input type="text" placeholder="Untuk apa..." value={dNote} onChange={e=>setDNote(e.target.value)}
            style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+theme.border,background:theme.bg,color:theme.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>
        <div style={{marginBottom:16}}>
          <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Jatuh Tempo (opsional)</div>
          <input type="date" value={dDue} onChange={e=>setDDue(e.target.value)}
            style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+theme.border,background:theme.bg,color:theme.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>
        <button onClick={onSave} disabled={!dWho||!dAmount||saving}
          style={{width:'100%',height:50,borderRadius:14,border:0,cursor:'pointer',
            background:dWho&&dAmount&&!saving?'linear-gradient(135deg,'+(dKind==='hutang'?'#ef4444,#dc2626':'#10b981,#059669')+')':'#ccc',
            color:'#fff',fontSize:15,fontWeight:700}}>
          {saving ? 'Menyimpan...' : (dKind==='hutang'?'🔴':'🟢')+' Simpan'}
        </button>
      </div>
    </div>
  );
}

function ScreenReport({ theme, accent, scenario, auth }) {
  const [realTx, setRealTx]     = React.useState(null);
  const [realBudgets, setRealBudgets] = React.useState(null);
  const familyId = auth && auth.family && auth.family.id;
  React.useEffect(function() {
    if (!familyId) return;
    if (window.sbGetTransactions) sbGetTransactions(familyId).then(function(r){ if(!r.error) setRealTx(r.data||[]); });
    if (window.sbGetBudgets)      sbGetBudgets(familyId).then(function(r){ if(!r.error) setRealBudgets(r.data||[]); });
  }, [familyId]);
  const isAuth = !!(auth && auth.family);
  const [period, setPeriod] = React.useState('month');

  // Build category breakdown from transactions
  const expensesByCat = {};
  (isAuth?(realTx||[]):scenario.transactions).filter(function(t){ return (t.kind||t.type)==='expense'; }).forEach((t) => {
    expensesByCat[t.cat] = (expensesByCat[t.cat] || 0) + t.amount;
  });
  // Also add budget.used so categories without recent tx still show
  (isAuth?(realBudgets||[]):scenario.budgets).forEach((b) => {
    expensesByCat[b.cat] = Math.max(expensesByCat[b.cat] || 0, b.used);
  });
  const topCats = Object.entries(expensesByCat)
    .sort((a, b) => b[1] - a[1]).slice(0, 6);
  const totalExpense = Object.values(expensesByCat).reduce((a, v) => a + v, 0);

  // Build last-6-month bars (mock by varying current values)
  const months = ['Des','Jan','Feb','Mar','Apr','Mei'];
  const realIncome  = isAuth ? (realTx||[]).filter(function(t){return (t.kind||t.type)==='income';}).reduce(function(a,t){return a+t.amount;},0) : scenario.monthlyIncome;
  const incomeSeries  = isAuth ? [0,0,0,0,0,realIncome] : [0.78, 0.82, 0.91, 0.88, 0.96, 1.00].map((f) => scenario.monthlyIncome * f);
  const realExpense = isAuth ? (realTx||[]).filter(function(t){return (t.kind||t.type)==='expense';}).reduce(function(a,t){return a+t.amount;},0) : scenario.monthlyExpense;
  const expenseSeries = isAuth ? [0,0,0,0,0,realExpense] : [0.71, 0.85, 0.78, 0.92, 0.88, 1.00].map((f) => scenario.monthlyExpense * f);

  return (
    <div style={{ background: theme.bg, paddingBottom: 100 }}>
      <div style={{ padding: '56px 20px 16px' }}>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800,
                     letterSpacing: '-0.025em', color: theme.fg1 }}>Laporan</h1>
        <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 500, marginTop: 2 }}>
          Analisis keuangan keluarga
        </div>
      </div>

      {/* Period segmented control */}
      <div style={{ padding: '0 20px 16px' }}>
        <div style={{
          display: 'flex', padding: 4, background: theme.surfaceAlt, borderRadius: 12,
          position: 'relative',
        }}>
          {['week','month','year'].map((p, i) => {
            const labels = { week: 'Minggu', month: 'Bulan', year: 'Tahun' };
            const on = period === p;
            return (
              <button key={p} onClick={() => setPeriod(p)} style={{
                flex: 1, appearance: 'none', border: 0, cursor: 'pointer',
                padding: '8px 0', borderRadius: 9, zIndex: 1,
                background: on ? theme.surface : 'transparent',
                color: on ? theme.fg1 : theme.fg2,
                fontSize: 13, fontWeight: 700,
                boxShadow: on ? theme.shadow1 : 'none',
                transition: 'all 200ms',
              }}>{labels[p]}</button>
            );
          })}
        </div>
      </div>

      {/* In vs Out bar chart */}
      <div style={{ padding: '0 20px 16px' }}>
        <Card theme={theme} padding={18}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
                        marginBottom: 14 }}>
            <div>
              <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 600,
                            letterSpacing: '0.02em' }}>Pemasukan vs Pengeluaran</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: theme.fg1,
                            letterSpacing: '-0.02em', marginTop: 2 }}>
                6 bulan terakhir
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5,
                            fontSize: 11, color: theme.fg2, fontWeight: 600 }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: accent[500] }} />
                Pemasukan
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 5,
                            fontSize: 11, color: theme.fg2, fontWeight: 600 }}>
                <span style={{ width: 8, height: 8, borderRadius: 2, background: theme.fg4 }} />
                Pengeluaran
              </div>
            </div>
          </div>
          <BarChartInOut theme={theme} accent={accent}
                         months={months}
                         income={incomeSeries} expense={expenseSeries} />
        </Card>
      </div>

      {/* Top categories */}
      <SectionHeader title="Top kategori pengeluaran" action="Detail" theme={theme} />
      <div style={{ padding: '0 20px' }}>
        <Card theme={theme} padding={4}>
          {topCats.map(([catId, val], i) => {
            const c = CATEGORIES[catId];
            const pct = (val / totalExpense) * 100;
            return (
              <div key={catId} style={{
                padding: '12px',
                borderBottom: i < topCats.length - 1 ? `0.5px solid ${theme.border}` : 'none',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                  <CatDisc cat={c} size={32} />
                  <div style={{ flex: 1, fontSize: 13, fontWeight: 700, color: theme.fg1,
                                letterSpacing: '-0.005em' }}>{c.label}</div>
                  <div style={{
                    fontSize: 13, fontWeight: 800, color: theme.fg1,
                    fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em',
                  }}>{fmtRp(val, { short: true })}</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 42 }}>
                  <div style={{ flex: 1 }}>
                    <ProgressBar value={val} max={totalExpense} theme={theme} height={4}
                                 color={c.color} />
                  </div>
                  <span style={{ fontSize: 11, color: theme.fg3, fontWeight: 600,
                                 fontVariantNumeric: 'tabular-nums', minWidth: 32, textAlign: 'right' }}>
                    {pct.toFixed(0)}%
                  </span>
                </div>
              </div>
            );
          })}
        </Card>
      </div>
    </div>
  );
}

function BarChartInOut({ theme, accent, months, income, expense }) {
  const max = Math.max(...income, ...expense);
  const barW = 12;
  const gap = 4;
  const groupW = barW * 2 + gap;
  const groupGap = 16;
  const chartW = months.length * groupW + (months.length - 1) * groupGap;
  const chartH = 130;

  return (
    <div>
      <svg viewBox={`0 0 ${chartW} ${chartH}`} width="100%" height={chartH}
           preserveAspectRatio="xMidYMid meet" style={{ display: 'block' }}>
        {months.map((m, i) => {
          const x = i * (groupW + groupGap);
          const hI = max > 0 ? (income[i] / max) * (chartH - 28) : 0;
          const hE = max > 0 ? (expense[i] / max) * (chartH - 28) : 0;
          return (
            <g key={m}>
              <rect x={x} y={chartH - 24 - hI} width={barW} height={hI}
                    rx={3} fill={accent[500]} />
              <rect x={x + barW + gap} y={chartH - 24 - hE} width={barW} height={hE}
                    rx={3} fill={theme.fg4} />
              <text x={x + groupW / 2} y={chartH - 8}
                    textAnchor="middle" fontSize="10" fill={theme.fg3}
                    fontWeight="600" fontFamily="Plus Jakarta Sans, sans-serif">
                {m}
              </text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

Object.assign(window, { ScreenDebts, ScreenReport, BarChartInOut });
