// Transactions page — list + add modal + filters.

const PageTransactions = () => {
  const { state, addTransaction, deleteTransaction, loadDemo } = useAppState();
  const [showAdd, setShowAdd] = React.useState(false);
  const [filter, setFilter] = React.useState('all'); // all | income | expense
  const [memberFilter, setMemberFilter] = React.useState('all');

  let txs = [...state.transactions];
  if (filter !== 'all') txs = txs.filter(t => t.type === filter);
  if (memberFilter !== 'all') txs = txs.filter(t => t.memberId === memberFilter);
  txs.sort((a, b) => new Date(b.date) - new Date(a.date));

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title">Transactions</h1>
          <div className="page-sub">{state.transactions.length} entries · {fmtDate(today())}</div>
        </div>
        <div className="row" style={{gap:8}}>
          {state.transactions.length === 0 && (
            <button className="btn" onClick={loadDemo}><IPlay size={13}/> Load demo</button>
          )}
          <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> Add transaction</button>
        </div>
      </div>

      <div className="row" style={{gap:8, marginBottom:16}}>
        <div className="tabs" style={{margin:0, border:'none'}}>
          {[
            {id:'all', label:'All'},
            {id:'income', label:'Income'},
            {id:'expense', label:'Spending'},
          ].map(t => (
            <button key={t.id} className={`tab ${filter === t.id ? 'active' : ''}`} onClick={() => setFilter(t.id)}>{t.label}</button>
          ))}
        </div>
        {state.mode === 'household' && (
          <div style={{marginLeft:'auto'}}>
            <select className="select" value={memberFilter} onChange={e => setMemberFilter(e.target.value)} style={{width:'auto', paddingRight: 30}}>
              <option value="all">Everyone</option>
              {state.members.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
            </select>
          </div>
        )}
      </div>

      {txs.length === 0 ? (
        <div className="empty">
          <div className="empty-icon"><IList size={22}/></div>
          <h3 className="serif" style={{fontSize:22}}>No transactions yet</h3>
          <p>Track every Rand in and out — you'll see patterns appear within a week.</p>
          <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> Add your first</button>
        </div>
      ) : (
        <div className="card fade-up" style={{overflow:'hidden'}}>
          <table className="table">
            <thead>
              <tr>
                <th>Description</th>
                <th>Type</th>
                <th>Category</th>
                {state.mode === 'household' && <th>Member</th>}
                <th>Date</th>
                <th style={{textAlign:'right'}}>Amount</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {txs.map((t, i) => {
                const cat = t.type === 'expense' ? categoryById(t.category) : null;
                const src = t.type === 'income' ? INCOME_SOURCES.find(s => s.id === t.source) : null;
                const member = state.members.find(m => m.id === t.memberId);
                return (
                  <tr key={t.id} className="row-hov" style={{animation: `fadeUp 0.35s ${Math.min(i, 12) * 0.025}s both`}}>
                    <td>
                      <div style={{fontWeight:500}}>{t.note || (cat?.label || src?.label)}</div>
                      {t.recurring && <div style={{fontSize:11, color:'var(--ink-3)', marginTop:2}}>Recurring · day {t.dayOfMonth}</div>}
                    </td>
                    <td data-label="Type">
                      <span className={`pill ${t.type === 'income' ? 'pill-mint' : 'pill-coral'}`}>
                        {t.type === 'income' ? <IArrowDown size={11}/> : <IArrowUp size={11}/>}
                        {t.type === 'income' ? 'In' : 'Out'}
                      </span>
                    </td>
                    <td data-label={t.type === 'income' ? 'Source' : 'Category'}>
                      {cat ? (
                        <span className="row" style={{gap:6}}>
                          <span className="dot" style={{background:`var(${cat.cssVar})`}}></span>
                          <span style={{fontSize:12.5}}>{cat.label}</span>
                        </span>
                      ) : <span style={{color:'var(--ink-3)', fontSize:12.5}}>{src?.label || '—'}</span>}
                    </td>
                    {state.mode === 'household' && (
                      <td data-label="Member">
                        {member && (
                          <span className="row" style={{gap:6}}>
                            <span className="avatar" style={{background:member.color, width:22, height:22, fontSize:10}}>{member.initials}</span>
                            <span style={{fontSize:12.5}}>{member.name}</span>
                          </span>
                        )}
                      </td>
                    )}
                    <td data-label="Date" className="mono" style={{color:'var(--ink-3)', fontSize:12.5}}>{fmtDate(new Date(t.date))}</td>
                    <td data-label="Amount" className="mono" style={{textAlign:'right', fontWeight:500, color: t.type === 'income' ? 'var(--mint-deep)' : 'var(--ink)'}}>
                      {t.type === 'income' ? '+' : '−'}{fmtZAR(t.amount).replace('R ','R ')}
                    </td>
                    <td>
                      <button className="btn btn-ghost btn-sm" onClick={() => deleteTransaction(t.id)} title="Delete">
                        <ITrash size={13}/>
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {showAdd && <AddTransactionModal onClose={() => setShowAdd(false)} onAdd={(t) => { addTransaction(t); setShowAdd(false); }}/>}
    </div>
  );
};

const AddTransactionModal = ({ onClose, onAdd }) => {
  const { state } = useAppState();
  const [type, setType] = React.useState('expense');
  const [amount, setAmount] = React.useState('');
  const [category, setCategory] = React.useState('groceries');
  const [source, setSource] = React.useState('salary');
  const [note, setNote] = React.useState('');
  const [date, setDate] = React.useState(today().toISOString().slice(0, 10));
  const [memberId, setMemberId] = React.useState(state.members[0]?.id);
  const [recurring, setRecurring] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    const n = parseFloat(amount);
    if (!n || n <= 0) return;
    onAdd({
      type,
      amount: n,
      category: type === 'expense' ? category : null,
      source: type === 'income' ? source : null,
      note: note.trim(),
      date: new Date(date).toISOString(),
      memberId,
      recurring: recurring ? 'monthly' : null,
      dayOfMonth: recurring ? new Date(date).getDate() : null,
    });
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row-between" style={{marginBottom:18}}>
          <div className="serif" style={{fontSize:24, letterSpacing:'-0.01em'}}>New transaction</div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><IClose size={16}/></button>
        </div>

        <div className="mode-toggle" style={{marginBottom:18, width:'100%'}}>
          <button className={type === 'expense' ? 'active' : ''} onClick={() => setType('expense')} style={{flex:1, justifyContent:'center'}}>
            <IArrowUp size={12}/> Spending
          </button>
          <button className={type === 'income' ? 'active' : ''} onClick={() => setType('income')} style={{flex:1, justifyContent:'center'}}>
            <IArrowDown size={12}/> Income
          </button>
        </div>

        <form onSubmit={submit} className="grid" style={{gap:14}}>
          <div className="field">
            <label className="label">Amount</label>
            <div style={{position:'relative'}}>
              <span style={{position:'absolute', left:16, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', fontSize:16}}>R</span>
              <input className="input input-lg" style={{paddingLeft:36}} placeholder="0.00" type="number" step="0.01" value={amount} onChange={e => setAmount(e.target.value)} autoFocus required/>
            </div>
          </div>

          <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:12}}>
            <div className="field">
              <label className="label">{type === 'expense' ? 'Category' : 'Source'}</label>
              {type === 'expense' ? (
                <select className="select" value={category} onChange={e => setCategory(e.target.value)}>
                  {CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
                </select>
              ) : (
                <select className="select" value={source} onChange={e => setSource(e.target.value)}>
                  {INCOME_SOURCES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
                </select>
              )}
            </div>
            <div className="field">
              <label className="label">Date</label>
              <input className="input" type="date" value={date} onChange={e => setDate(e.target.value)}/>
            </div>
          </div>

          <div className="field">
            <label className="label">Description</label>
            <input className="input" value={note} onChange={e => setNote(e.target.value)} placeholder="e.g. Checkers groceries"/>
          </div>

          {state.mode === 'household' && (
            <div className="field">
              <label className="label">Who</label>
              <div className="row" style={{gap:8, flexWrap:'wrap'}}>
                {state.members.map(m => (
                  <button type="button" key={m.id}
                    className={`member-chip ${memberId === m.id ? '' : ''}`}
                    style={{
                      cursor:'pointer',
                      borderColor: memberId === m.id ? 'var(--ink)' : 'var(--line)',
                      background: memberId === m.id ? 'var(--surface-2)' : 'var(--card)',
                    }}
                    onClick={() => setMemberId(m.id)}
                  >
                    <span className="avatar" style={{background: m.color}}>{m.initials}</span>
                    {m.name}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div className="row-between" style={{padding:'4px 2px'}}>
            <div>
              <div style={{fontSize:13, fontWeight:500}}>Recurring monthly</div>
              <div style={{fontSize:11.5, color:'var(--ink-3)'}}>Auto-track every month</div>
            </div>
            <button type="button" className={`switch ${recurring ? 'on' : ''}`} onClick={() => setRecurring(!recurring)}/>
          </div>

          <div className="row" style={{gap:8, marginTop:6}}>
            <button type="button" className="btn" style={{flex:1, justifyContent:'center'}} onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" style={{flex:1, justifyContent:'center'}}>Add</button>
          </div>
        </form>
      </div>
    </div>
  );
};

Object.assign(window, { PageTransactions, AddTransactionModal });
