// src/features/admin/ui/admin-instructors-card-payments.jsx
//
// Per-instructor earnings history table + past-lessons (paid/unpaid)
// review table. Both are rendered inside the expanded AICard but
// were extracted to keep admin-instructors-card.jsx under the
// 400 LOC budget.
//
// Public: window.{AIEarningsHistory, AIUnsettledBookings}.

// ── Per-instructor earnings history ───────────────────────────────────────────
// Groups all completed (and uncancelled-past) bookings by YYYY-MM and shows
// a tidy table: month · lesson count · gross earned · cash · payout · paid pct.
// Joe wanted this so he can verify monthly payouts at a glance.
// NB: per BACKLOG #1, cancelled bookings keep their `paid` flag (we don't
// drop money state on cancel) but must NOT count toward earnings. The
// `b.status !== 'cancelled'` filter below is what keeps Earned/Paid/Cash/
// Settled accurate. Don't remove it.
const AIEarningsHistory = ({ bookings }) => {
  const rows = (bookings || []).filter(b => b.status !== 'cancelled' && new Date(b.scheduledAt) < new Date());
  if (rows.length === 0) return null;
  const byMonth = {};
  for (const b of rows) {
    const ym = (b.scheduledAt || '').slice(0, 7); // YYYY-MM
    if (!ym) continue;
    if (!byMonth[ym]) byMonth[ym] = { lessons: 0, earned: 0, paid: 0, cash: 0, settled: 0 };
    const t = Number(b.teacherRate) || 0;
    byMonth[ym].lessons += 1;
    byMonth[ym].earned  += t;
    if (b.paid)                              byMonth[ym].paid    += t;
    if (b.paid && b.paymentMethod === 'cash') byMonth[ym].cash   += t;
    if (b.paid && b.settled)                 byMonth[ym].settled += t;
  }
  const months = Object.keys(byMonth).sort().reverse();
  const monthLabel = (ym) => {
    const [y, m] = ym.split('-').map(Number);
    return new Date(y, m-1, 1).toLocaleDateString(undefined, { month:'short', year:'numeric' });
  };
  const f$ = (n) => '$' + (Number(n) || 0).toLocaleString();
  return (
    <div style={{ paddingTop:14, borderTop:'1px solid oklch(94% 0.005 60)', marginBottom:14 }}>
      <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(55% 0.03 265)', marginBottom:10 }}>Earnings history ({months.length} month{months.length===1?'':'s'})</div>
      <div style={{ overflowX:'auto' }}>
        <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
          <thead>
            <tr style={{ borderBottom:'1.5px solid oklch(90% 0.01 265)', color:'oklch(56% 0.03 265)', fontWeight:700 }}>
              <th style={{ textAlign:'left',  padding:'7px 8px' }}>Month</th>
              <th style={{ textAlign:'right', padding:'7px 8px' }}>Lessons</th>
              <th style={{ textAlign:'right', padding:'7px 8px' }}>Earned</th>
              <th style={{ textAlign:'right', padding:'7px 8px' }}>Paid</th>
              <th style={{ textAlign:'right', padding:'7px 8px' }}>Cash</th>
              <th style={{ textAlign:'right', padding:'7px 8px' }}>Settled</th>
            </tr>
          </thead>
          <tbody>
            {months.map(ym => {
              const r = byMonth[ym];
              const pct = r.earned > 0 ? Math.round((r.paid / r.earned) * 100) : 0;
              return (
                <tr key={ym} style={{ borderBottom:'1px solid oklch(95% 0.005 60)', color:'oklch(28% 0.05 265)' }}>
                  <td style={{ padding:'7px 8px', fontWeight:600 }}>{monthLabel(ym)}</td>
                  <td style={{ padding:'7px 8px', textAlign:'right' }}>{r.lessons}</td>
                  <td style={{ padding:'7px 8px', textAlign:'right', fontWeight:700 }}>{f$(r.earned)}</td>
                  <td style={{ padding:'7px 8px', textAlign:'right', color: pct < 100 ? 'oklch(38% 0.16 25)' : 'oklch(30% 0.13 150)' }}>{f$(r.paid)} <span style={{ fontSize:10, color:'oklch(60% 0.03 265)' }}>({pct}%)</span></td>
                  <td style={{ padding:'7px 8px', textAlign:'right' }}>{f$(r.cash)}</td>
                  <td style={{ padding:'7px 8px', textAlign:'right' }}>{f$(r.settled)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// ── Payments table inside the expanded card ───────────────────────────────────
// Shows ALL non-cancelled past bookings (paid + unpaid) so the admin can
// see the breakdown at a glance and toggle paid status in either direction.
// Previously this only showed unsettled rows, which made paid rows disappear
// once you clicked "Mark paid" — confusing if it was a mis-tap.
const AIUnsettledBookings = ({ bookings }) => {
  const data = window.useAdminData();
  const [busyId, setBusyId] = React.useState(null);

  const now = new Date();
  const rows = bookings
    .filter(b => b.status !== 'cancelled' && new Date(b.scheduledAt) < now)
    .sort((a,b) => (b.scheduledAt || '').localeCompare(a.scheduledAt || ''));
  const paidCount   = rows.filter(b => b.paid).length;
  const unpaidCount = rows.filter(b => !b.paid).length;

  const act = async (id, patch) => {
    setBusyId(id);
    try { await data.setBookingFlags(id, patch); }
    catch (e) { console.error(e); alert(e.message || 'Update failed'); }
    finally { setBusyId(null); }
  };

  if (rows.length === 0) return (
    <div style={{ paddingTop:14, borderTop:'1px solid oklch(94% 0.005 60)', fontSize:12, color:'oklch(60% 0.03 265)', fontStyle:'italic' }}>
      No past lessons yet.
    </div>
  );

  return (
    <div style={{ paddingTop:14, borderTop:'1px solid oklch(94% 0.005 60)' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10, flexWrap:'wrap', gap:8 }}>
        <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(55% 0.03 265)' }}>Past lessons ({rows.length})</div>
        <div style={{ display:'flex', gap:6, fontSize:11, fontWeight:700 }}>
          <span style={{ padding:'3px 9px', borderRadius:20, background: paidCount > 0 ? 'oklch(91% 0.1 150)' : 'oklch(95% 0.005 60)', color: paidCount > 0 ? 'oklch(28% 0.13 150)' : 'oklch(60% 0.03 265)' }}>{paidCount} paid</span>
          <span style={{ padding:'3px 9px', borderRadius:20, background: unpaidCount > 0 ? 'oklch(95% 0.07 25)' : 'oklch(95% 0.005 60)', color: unpaidCount > 0 ? 'oklch(38% 0.16 25)' : 'oklch(60% 0.03 265)' }}>{unpaidCount} unpaid</span>
        </div>
      </div>
      {rows.map(b => {
        const d = new Date(b.scheduledAt);
        const teacher = Number(b.teacherRate) || 0;
        const isCash = b.paymentMethod === 'cash';
        const busy = busyId === b.id;
        return (
          <div key={b.id} style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', padding:'8px 0', borderBottom:'1px solid oklch(95% 0.005 60)', fontSize:12, gap:12, flexWrap:'wrap' }}>
            <div style={{ flex:1, minWidth:180 }}>
              <div style={{ fontWeight:600, color:'oklch(26% 0.05 265)' }}>{b.student?.name || '—'} {isCash && <span style={{ fontSize:10, marginLeft:4 }}>💵</span>}</div>
              <div style={{ color:'oklch(58% 0.03 265)' }}>{d.toLocaleDateString(undefined, { month:'short', day:'numeric' })} · {aiFmtH(d.getHours())} {window.adminSchTzAbbrev?.(d) || ''} · ${teacher} owed</div>
              {b.rescheduleRequestedAt && (() => {
                const rd = new Date(b.rescheduleRequestedAt);
                return (
                  <div style={{ marginTop:6, background:'oklch(96.5% 0.07 80)', borderRadius:7, padding:'7px 10px', fontSize:11, color:'oklch(34% 0.13 75)', display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                    <span style={{ fontWeight:700 }}>🔄 Reschedule pending</span>
                    <span>→ {rd.toLocaleDateString(undefined, { month:'short', day:'numeric' })} · {aiFmtH(rd.getHours())} {window.adminSchTzAbbrev?.(rd) || ''}</span>
                    <button disabled={busy} onClick={async () => { setBusyId(b.id); try { await data.approveReschedule(b.id); } catch(e){ alert(e.message); } finally { setBusyId(null); } }}
                      style={{ background:'oklch(32% 0.14 150)', color:'#fff', border:'none', borderRadius:5, padding:'3px 8px', fontSize:10, fontWeight:700, cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Approve</button>
                    <button disabled={busy} onClick={async () => { setBusyId(b.id); try { await data.declineReschedule(b.id); } catch(e){ alert(e.message); } finally { setBusyId(null); } }}
                      style={{ background:'#fff', color:'oklch(40% 0.1 25)', border:'1px solid oklch(88% 0.08 25)', borderRadius:5, padding:'3px 8px', fontSize:10, fontWeight:700, cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Decline</button>
                  </div>
                );
              })()}
            </div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap', justifyContent:'flex-end' }}>
              {/* Always-visible toggle — flips paid <-> unpaid in either
                  direction so a mis-tap is recoverable. */}
              <button disabled={busy} onClick={()=>act(b.id, { paid: !b.paid })} style={{
                background: b.paid ? 'oklch(91% 0.1 150)' : 'oklch(96% 0.01 265)',
                border: b.paid ? '1px solid oklch(82% 0.08 150)' : '1px solid oklch(86% 0.02 265)',
                borderRadius:6, padding:'5px 9px', fontSize:11, fontWeight:600,
                color: b.paid ? 'oklch(28% 0.13 150)' : 'oklch(28% 0.05 265)',
                cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif",
              }}>
                {b.paid ? '✓ Paid · click to undo' : 'Mark paid'}
              </button>
              {b.paid && !b.settled && isCash && (
                <button disabled={busy} onClick={()=>act(b.id, { settled:true })} style={{ background:'oklch(44% 0.12 150)', border:'none', borderRadius:6, padding:'5px 9px', fontSize:11, fontWeight:700, color:'#fff', cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Cash received</button>
              )}
              {b.paid && !b.settled && !isCash && (
                <button disabled={busy} onClick={()=>act(b.id, { settled:true })} style={{ background:'oklch(22% 0.06 265)', border:'none', borderRadius:6, padding:'5px 9px', fontSize:11, fontWeight:700, color:'#fff', cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Payout sent</button>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
};

Object.assign(window, { AIEarningsHistory, AIUnsettledBookings });
