const PAGE_SIZE = 20;
function fmtDateTime(v) { if (!v) return 'N/A'; return new Date(v).toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' }); }

function RefundPromptDialog({ open, order, onClose, onConfirm }) {
  const { Button, Radio } = window.TheUpperDeckDesignSystem_4d3294;
  const [mode, setMode] = React.useState('full');
  const [amount, setAmount] = React.useState('');
  const [pct, setPct] = React.useState('100');
  React.useEffect(() => { if (open) { setMode('full'); setAmount(''); setPct('100'); } }, [open]);
  if (!open || !order) return null;
  const cents = mode === 'full' ? order.originalAmountCents : mode === 'amount' ? Math.round(Number(amount) || 0) : Math.round(order.originalAmountCents * (Number(pct) || 0) / 100);
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1100, padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 380, background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <h3 style={{ fontFamily: 'var(--font-display)', margin: 0 }}>Refund order</h3>
        <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>Total paid: {window.fmtUSD(order.originalAmount)}</div>
        <Radio label={'Full refund (' + window.fmtUSD(order.originalAmount) + ')'} checked={mode === 'full'} onChange={() => setMode('full')} />
        <Radio label="Specific amount" checked={mode === 'amount'} onChange={() => setMode('amount')} />
        {mode === 'amount' && <input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="e.g. 500" style={{ padding: '8px 10px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)' }} />}
        <Radio label="Percentage of amount" checked={mode === 'percent'} onChange={() => setMode('percent')} />
        {mode === 'percent' && <input type="number" value={pct} onChange={(e) => setPct(e.target.value)} placeholder="e.g. 50" style={{ padding: '8px 10px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)' }} />}
        <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600 }}>Refund amount: {window.fmtUSD(cents)}</div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 8 }}>
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="danger" disabled={cents <= 0} onClick={() => onConfirm(cents)}>Confirm refund</Button>
        </div>
      </div>
    </div>, document.body
  );
}

function OrderDetailDialog({ order, onClose, onRefund, onToggleCheckin, onVerify, onDeny }) {
  const { Badge, Switch } = window.TheUpperDeckDesignSystem_4d3294;
  const { Btn } = window.UdUI;
  const [denying, setDenying] = React.useState(false);
  const [remarks, setRemarks] = React.useState('');
  React.useEffect(() => { setDenying(false); setRemarks(''); }, [order && order.ref]);
  if (!order) return null;
  const toneFor = (s) => s === 'paid' ? 'success' : s === 'refunded' || s === 'denied' ? 'error' : 'warning';
  const methodLabel = order.method === 'bank' ? 'Bank transfer' : order.method === 'ewallet' ? 'GCash' : (order.method || '—');
  const Section = ({ title, children }) => (
    <div style={{ background: 'var(--bg-sunken)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: 18 }}>
      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)', fontWeight: 700, marginBottom: 12 }}>{title}</div>
      {children}
    </div>
  );
  const Row = ({ label, children }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '8px 0', borderBottom: '1px solid var(--border-default)', fontSize: 'var(--text-sm)' }}>
      <span style={{ color: 'var(--text-muted)', flexShrink: 0 }}>{label}</span>
      <span style={{ textAlign: 'right', fontWeight: 500 }}>{children}</span>
    </div>
  );
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 24 }}>
      <div className="ud-modal" onClick={(e) => e.stopPropagation()} style={{ width: 640, maxHeight: '90vh', overflowY: 'auto', position: 'relative', background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', animation: 'udScaleIn 200ms var(--ease-standard) both' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 20, right: 24, width: 32, height: 32, borderRadius: '50%', border: 'none', background: 'var(--bg-sunken)', color: 'var(--text-primary)', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 2 }}>×</button>
        <div style={{ padding: '28px 64px 20px 32px', borderBottom: '1px solid var(--border-default)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 20, background: 'var(--gradient-navy)', color: 'white' }}>
          <div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', margin: '0 0 4px', color: 'white' }}>Order {order.ref}</h2>
            <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-on-dark-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>Order details</div>
          </div>
          <Badge tone={toneFor(order.status)}>{order.status}</Badge>
        </div>

        <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <Section title="Session">
              <Row label="Event">{order.eventTitle}</Row>
              <Row label="Main event">{order.mainTitle}</Row>
              <Row label="Package">{order.package}</Row>
              <Row label="Amount">{window.fmtUSD(order.originalAmount)}</Row>
              <Row label="Purchased on">{fmtDateTime(order.purchasedOn)}</Row>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '8px 0', fontSize: 'var(--text-sm)' }}>
                <span style={{ color: 'var(--text-muted)' }}>Payment method</span>
                <span style={{ fontWeight: 500 }}>{methodLabel}</span>
              </div>
            </Section>
            <Section title="Buyer">
              <Row label="Name">{order.buyer}</Row>
              <Row label="Email">{order.email}</Row>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '8px 0', fontSize: 'var(--text-sm)' }}>
                <span style={{ color: 'var(--text-muted)' }}>Phone</span>
                <span style={{ fontWeight: 500 }}>{order.phone}</span>
              </div>
              <div style={{ marginTop: 10 }}>
                <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)', marginBottom: 6 }}>Checked in</div>
                <Switch checked={order.checkedIn} onChange={(v) => onToggleCheckin(order.ref, v)} disabled={order.status !== 'paid'} label={order.checkedIn ? 'Checked in' : 'Not checked in'} />
              </div>
            </Section>
          </div>

          {order.attendees && order.attendees.length > 1 && (
            <Section title={'All attendees (' + order.attendees.length + ')'}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {order.attendees.map((a, i) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 'var(--text-sm)', padding: '8px 12px', background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)' }}>
                    <span>{a.name}{a.email ? ' · ' + a.email : ''}</span>
                    {a.checkedIn && <Badge tone="success">Checked in</Badge>}
                  </div>
                ))}
              </div>
            </Section>
          )}

          {order.proofImage && (
            <Section title="Proof of payment">
              <img src={order.proofImage} alt="Proof of payment" style={{ width: '100%', maxWidth: 320, borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', display: 'block' }} />
            </Section>
          )}

          {order.status === 'denied' && order.remarks && (
            <div style={{ padding: '12px 14px', borderRadius: 'var(--radius-md)', background: 'var(--status-error-bg)', color: 'var(--status-error)', fontSize: 'var(--text-sm)' }}>
              <strong>Denial remarks:</strong> {order.remarks}
            </div>
          )}
        </div>

        {order.status === 'pending' && !denying && (
          <div style={{ padding: '16px 32px 28px', display: 'flex', justifyContent: 'flex-end', gap: 10, borderTop: '1px solid var(--border-default)' }}>
            <Btn variant="danger" onClick={() => setDenying(true)}>Deny</Btn>
            <Btn onClick={() => { onVerify(order.ref); onClose(); }}>Verify payment</Btn>
          </div>
        )}
        {order.status === 'pending' && denying && (
          <div style={{ padding: '16px 32px 28px', display: 'flex', flexDirection: 'column', gap: 10, borderTop: '1px solid var(--border-default)' }}>
            <label style={{ fontSize: 'var(--text-sm)', fontWeight: 600 }}>Remarks (required)</label>
            <textarea value={remarks} onChange={(e) => setRemarks(e.target.value)} placeholder="Explain why this payment is being denied…" rows={3} style={{ width: '100%', padding: '10px 12px', fontSize: 'var(--text-sm)', fontFamily: 'var(--font-body)', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', resize: 'vertical', boxSizing: 'border-box' }} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
              <Btn variant="secondary" onClick={() => setDenying(false)}>Cancel</Btn>
              <Btn variant="danger" disabled={!remarks.trim()} onClick={() => { onDeny(order.ref, remarks.trim()); onClose(); }}>Confirm denial</Btn>
            </div>
          </div>
        )}
        {order.status === 'paid' && (
          <div style={{ padding: '16px 32px 28px', display: 'flex', justifyContent: 'flex-end', borderTop: '1px solid var(--border-default)' }}>
            <Btn variant="danger" onClick={() => onRefund(order)}>Refund this order</Btn>
          </div>
        )}
      </div>
    </div>, document.body
  );
}

function OrdersScreen({ adminId }) {
  const { Badge, Switch, Toast } = window.TheUpperDeckDesignSystem_4d3294;
  const { CustomSelect, CustomDatePicker, SearchInput, Btn, ColumnPicker, useColumnPrefs } = window.UdUI;
  const ALL_COLUMNS = [
    { key: 'ref', label: 'Ref', locked: true }, { key: 'buyer', label: 'Buyer' }, { key: 'event', label: 'Event' },
    { key: 'amount', label: 'Amount' }, { key: 'status', label: 'Status' },
  ];
  const [cols, setCols] = useColumnPrefs('orders', ALL_COLUMNS.map((c) => c.key));
  const [orders, setOrders] = React.useState([]);
  const [mainEvents, setMainEvents] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [query, setQuery] = React.useState('');
  const [status, setStatus] = React.useState('');
  const [eventFilter, setEventFilter] = React.useState('');
  const [subEventFilter, setSubEventFilter] = React.useState('');
  const [startDate, setStartDate] = React.useState('');
  const [endDate, setEndDate] = React.useState('');
  const [page, setPage] = React.useState(1);
  const [viewing, setViewing] = React.useState(null);
  const [toast, setToast] = React.useState(null);

  function notify(msg) { setToast(msg); setTimeout(() => setToast(null), 2200); }
  const [refunding, setRefunding] = React.useState(null);
  const [actionError, setActionError] = React.useState('');

  function reload() {
    setLoading(true);
    Promise.all([window.fetchOrdersLive(), window.fetchEventFilterOptions()]).then(([o, m]) => {
      setOrders(o); setMainEvents(m); setLoading(false);
    });
  }
  React.useEffect(() => { reload(); }, []);
  const d = { mainEvents };

  const filtered = orders.filter((o) => {
    const q = query.toLowerCase();
    const matchQ = !q || o.buyer.toLowerCase().includes(q) || o.ref.toLowerCase().includes(q) || o.eventTitle.toLowerCase().includes(q);
    const matchS = !status || o.status === status;
    const matchEv = !eventFilter || o.mainId === eventFilter;
    const matchSub = !subEventFilter || o.eventId === subEventFilter;
    const purchased = new Date(o.purchasedOn);
    const matchStart = !startDate || purchased >= new Date(startDate);
    const matchEnd = !endDate || purchased <= new Date(endDate);
    return matchQ && matchS && matchEv && matchSub && matchStart && matchEnd;
  });
  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const effectivePage = Math.min(page, totalPages);
  React.useEffect(() => { if (page !== effectivePage) setPage(effectivePage); }, [effectivePage]);
  const pageItems = filtered.slice((effectivePage - 1) * PAGE_SIZE, effectivePage * PAGE_SIZE);

  async function refund(cents) {
    try {
      await window.refundOrderLive(refunding.orderId, cents);
      setRefunding(null); setViewing(null);
      reload();
      notify('Order ' + refunding.ref + ' refunded');
    } catch (e) { setActionError('Refund failed: ' + e.message); }
  }
  async function verify(ref) {
    const o = orders.find((x) => x.ref === ref);
    try {
      await window.verifyOrderLive(o.orderId, adminId);
      reload();
      notify('Order ' + ref + ' verified');
    } catch (e) { setActionError('Verify failed: ' + e.message); }
  }
  async function deny(ref, remarks) {
    const o = orders.find((x) => x.ref === ref);
    try {
      await window.denyOrderLive(o.orderId, remarks, adminId);
      reload();
      notify('Order ' + ref + ' denied');
    } catch (e) { setActionError('Deny failed: ' + e.message); }
  }
  async function toggleCheckin(ref, val) {
    const o = orders.find((x) => x.ref === ref);
    try {
      await window.toggleCheckinLive(o.orderId, val, adminId);
      reload();
    } catch (e) { setActionError('Check-in update failed: ' + e.message); }
  }
  function exportCsv() {
    const rows = ['ref,buyer,email,event,amount,status'].concat(filtered.map((o) => [o.ref, o.buyer, o.email, o.eventTitle, o.amount, o.status].join(',')));
    const blob = new Blob([rows.join('\n')], { type: 'text/csv' });
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'orders.csv'; a.click();
    notify('Exported ' + filtered.length + ' orders to CSV');
  }

  return (
    <div>
      <div className="ud-tablewrap" style={{ display: 'flex', gap: 12, marginBottom: 20, flexWrap: 'wrap', alignItems: 'center' }}>
        <SearchInput placeholder="Search buyer, ref, or event…" value={query} onChange={(v) => { setQuery(v); setPage(1); }} width={240} />
        <CustomSelect value={status} onChange={(v) => { setStatus(v); setPage(1); }} placeholder="All statuses" width={150} options={[{ value: 'paid', label: 'Paid' }, { value: 'refunded', label: 'Refunded' }, { value: 'pending', label: 'Pending' }, { value: 'denied', label: 'Denied' }]} />
        <CustomSelect value={eventFilter} onChange={(v) => { setEventFilter(v); setSubEventFilter(''); setPage(1); }} placeholder="All events" width={190} options={d.mainEvents.map((m) => ({ value: m.id, label: m.title }))} />
        <CustomSelect value={subEventFilter} onChange={(v) => { setSubEventFilter(v); setPage(1); }} placeholder="All sub-events" width={190} options={(eventFilter ? (d.mainEvents.find((m) => m.id === eventFilter) || { subEvents: [] }).subEvents : d.mainEvents.flatMap((m) => m.subEvents)).map((s) => ({ value: s.id, label: s.title }))} />
        <CustomDatePicker value={startDate} onChange={(v) => { setStartDate(v); setPage(1); }} placeholder="Purchased from" />
        <CustomDatePicker value={endDate} onChange={(v) => { setEndDate(v); setPage(1); }} placeholder="to" />
        <Btn onClick={exportCsv}>Export CSV</Btn>
        <ColumnPicker columns={ALL_COLUMNS} visible={cols} onChange={setCols} />
      </div>

      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflowX: 'auto' }}>
        {loading && <div style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)' }}>Loading orders…</div>}
        {!loading && <table style={{ width: '100%', minWidth: 720, borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
          <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
            {cols.includes('ref') && <th style={{ padding: '12px 16px' }}>Ref</th>}
            {cols.includes('buyer') && <th>Buyer</th>}
            {cols.includes('event') && <th>Event</th>}
            {cols.includes('amount') && <th>Amount</th>}
            {cols.includes('status') && <th>Status</th>}
            <th></th>
          </tr></thead>
          <tbody>
            {pageItems.map((o) => (
              <tr key={o.ref} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
                {cols.includes('ref') && <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)' }}>{o.ref}</td>}
                {cols.includes('buyer') && <td>{o.buyer}</td>}
                {cols.includes('event') && <td style={{ color: 'var(--text-secondary)' }}>{o.eventTitle}</td>}
                {cols.includes('amount') && <td>
                  {o.status === 'refunded' || o.status === 'denied' ? (
                    <div>
                      <div style={{ textDecoration: 'line-through', color: 'var(--text-muted)' }}>{window.fmtUSD(o.originalAmount)}</div>
                      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{o.status === 'refunded' ? window.fmtUSD(o.originalAmount) + ' refunded' : 'payment denied'}</div>
                    </div>
                  ) : window.fmtUSD(o.amount)}
                </td>}
                {cols.includes('status') && <td><Badge tone={o.status === 'paid' ? 'success' : o.status === 'refunded' || o.status === 'denied' ? 'error' : 'warning'}>{o.status}</Badge></td>}
                <td style={{ padding: '10px 16px', textAlign: 'right' }}>
                  <Btn size="sm" variant="secondary" onClick={() => setViewing(o)}>View</Btn>
                </td>
              </tr>
            ))}
          </tbody>
        </table>}
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16, fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>
        <span>{filtered.length} orders</span>
        <div style={{ display: 'flex', gap: 8 }}>
          <Btn size="sm" variant="ghost" disabled={effectivePage === 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>Prev</Btn>
          <span style={{ padding: '6px 4px' }}>Page {effectivePage} of {totalPages}</span>
          <Btn size="sm" variant="ghost" disabled={effectivePage === totalPages} onClick={() => setPage((p) => Math.min(totalPages, p + 1))}>Next</Btn>
        </div>
      </div>

      <OrderDetailDialog order={viewing ? orders.find((o) => o.ref === viewing.ref) || viewing : null} onClose={() => setViewing(null)} onRefund={(o) => setRefunding(o)} onToggleCheckin={toggleCheckin} onVerify={verify} onDeny={deny} />
      <RefundPromptDialog open={!!refunding} order={refunding} onClose={() => setRefunding(null)} onConfirm={refund} />
      {actionError && <div style={{ position: 'fixed', bottom: 24, left: 24, zIndex: 1200, background: 'var(--status-error-bg)', color: 'var(--status-error)', padding: '10px 16px', borderRadius: 'var(--radius-md)', fontSize: 'var(--text-sm)' }} onClick={() => setActionError('')}>{actionError} (click to dismiss)</div>}
      {toast && <div style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 1200 }}><Toast message={toast} tone="success" onDismiss={() => setToast(null)} /></div>}
    </div>
  );
}

window.OrdersScreen = OrdersScreen;
