/* AIWine CRM — Winery signups: the approval queue for portal self-registrations.
   Wineries create their own login in the portal and submit their details; those
   land here as `winery_signup_requests`. Approving one creates/links the winery
   (via the approve_winery_request RPC) and grants portal access. Live only. */

function Approvals() {
  const store = window.UI.useStore();
  const { Ic, Badge, toast, rel } = window.UI;
  const [tab, setTab] = React.useState('pending');
  const [busy, setBusy] = React.useState(null);

  const reqs = store.t('winery_signup_requests');
  const pendingCount = reqs.filter((r) => r.status === 'pending').length;
  const rows = reqs
    .filter((r) => (tab === 'pending' ? r.status === 'pending' : r.status !== 'pending'))
    .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));

  const PORTAL_URL = 'https://portal.aiwine.co.nz';
  const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

  // Approval email — the portal promises "we'll email you the moment you're
  // approved", so actually send it. Best-effort: a mail failure must NOT block
  // the approval itself (the winery already has access once the RPC succeeds).
  const sendApprovalEmail = async (r, wineryId) => {
    if (!r.email) return { skipped: 'no email on file' };
    const html =
      '<p>Hi ' + esc(r.contact || r.wineryName) + ',</p>' +
      '<p>Good news — <b>' + esc(r.wineryName) + '</b> has been approved on AIWine. Your winery portal is ready.</p>' +
      '<p>You can now sign in and start adding your range:</p>' +
      '<p><a href="' + PORTAL_URL + '" style="display:inline-block;background:#7a1f2b;color:#fff;padding:11px 20px;border-radius:8px;text-decoration:none;font-weight:600">Open your winery portal</a></p>' +
      '<p style="color:#666;font-size:13px">Sign in with the email and password you created when you registered. Once your wines are published they become discoverable to AIWine members.</p>' +
      '<p>Welcome aboard,<br>The AIWine team</p>';
    const body =
      'Hi ' + (r.contact || r.wineryName) + ',\n\n' +
      r.wineryName + ' has been approved on AIWine. Your winery portal is ready.\n\n' +
      'Sign in and start adding your range: ' + PORTAL_URL + '\n\n' +
      'Use the email and password you created when you registered. Once your wines are published they become discoverable to AIWine members.\n\n' +
      'Welcome aboard,\nThe AIWine team';
    return store.sendEmail(
      { email: r.email, name: r.wineryName, audience: 'winery', wineryId: wineryId || r.wineryId || null },
      { subject: 'You’re approved — welcome to AIWine', html, body, mode: 'send' }
    );
  };

  const approve = async (r) => {
    if (!confirm('Approve ' + r.wineryName + '?\n\nThis creates or links their winery record, gives them portal access, and emails them a welcome/approval notice.')) return;
    setBusy(r.userId);
    try {
      const wid = await store.rpc('approve_winery_request', { p_user: r.userId, p_name: r.wineryName });
      await store.reloadLive();
      if (store.audit) store.audit('Approved winery signup: ' + r.wineryName, 'winery');
      // Approval is DONE at this point — the winery has portal access regardless
      // of the welcome email. Report the email outcome separately and calmly so a
      // mail hiccup never reads as a failed approval.
      let mailNote = ' · welcome email sent';
      try {
        const out = await sendApprovalEmail(r, wid);
        if (out && out.skipped) mailNote = ' · no email on file — tell them directly';
        else if (store.audit) store.audit('Emailed approval to ' + r.wineryName + ' <' + r.email + '>', 'email');
      } catch (mailErr) {
        mailNote = ' · welcome email did NOT send — approval is fine, just email them the portal link. (' + mailErr.message + ')';
      }
      toast('Approved ✓ · ' + r.wineryName + mailNote);
    } catch (e) { toast(e.message); } finally { setBusy(null); }
  };
  const reject = async (r) => {
    const reason = prompt('Decline ' + r.wineryName + '? Optional note (emailed to them; they can update and re-apply):', '');
    if (reason === null) return;
    setBusy(r.userId);
    try {
      await store.rpc('reject_winery_request', { p_user: r.userId, p_reason: reason || null, p_name: r.wineryName });
      await store.reloadLive();
      let mailNote = '';
      if (r.email) {
        const html =
          '<p>Hi ' + esc(r.contact || r.wineryName) + ',</p>' +
          '<p>Thanks for applying to AIWine. We weren’t able to approve <b>' + esc(r.wineryName) + '</b> just yet' +
          (reason ? ': ' + esc(reason) : '.') + '</p>' +
          '<p>You’re welcome to update your details and re-apply any time by signing in to the portal:</p>' +
          '<p><a href="' + PORTAL_URL + '" style="color:#7a1f2b;font-weight:600">' + PORTAL_URL + '</a></p>' +
          '<p>Kind regards,<br>The AIWine team</p>';
        const body =
          'Hi ' + (r.contact || r.wineryName) + ',\n\n' +
          'Thanks for applying to AIWine. We weren’t able to approve ' + r.wineryName + ' just yet' +
          (reason ? ': ' + reason : '.') + '\n\n' +
          'You can update your details and re-apply any time at ' + PORTAL_URL + '\n\n' +
          'Kind regards,\nThe AIWine team';
        try {
          await store.sendEmail(
            { email: r.email, name: r.wineryName, audience: 'winery' },
            { subject: 'About your AIWine application', html, body, mode: 'send' }
          );
          if (store.audit) store.audit('Emailed decline to ' + r.wineryName + ' <' + r.email + '>', 'email');
        } catch (mailErr) { mailNote = ' — decline email FAILED: ' + mailErr.message; }
      }
      toast('Declined · ' + r.wineryName + mailNote);
    } catch (e) { toast(e.message); } finally { setBusy(null); }
  };

  if (store.mode !== 'live') {
    return (
      <div>
        <div className="page-head"><div>
          <div className="label" style={{ marginBottom: 6 }}>Portal self-registration</div>
          <h1 className="page-title">Winery signups</h1>
        </div></div>
        <window.UI.Empty msg="Available on the live site" hint="Winery self-signups from the portal appear here once the CRM is connected to Supabase." />
      </div>
    );
  }

  return (
    <div>
      <div className="page-head"><div>
        <div className="label" style={{ marginBottom: 6 }}>{pendingCount} awaiting review</div>
        <h1 className="page-title">Winery signups</h1>
      </div></div>
      <window.UI.Tabs value={tab} onChange={setTab} items={[
        { id: 'pending', label: 'Pending', count: pendingCount },
        { id: 'reviewed', label: 'Reviewed' },
      ]} />
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Winery</th><th>Region</th><th>Contact</th><th>Applied</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.userId + '·' + r.wineryName}>
                <td className="main-cell">
                  {r.wineryName}
                  <div className="sub">{r.email}{r.website ? ' · ' + r.website : ''}</div>
                  {r.message ? <div className="sub" style={{ marginTop: 2, fontStyle: 'italic' }}>“{r.message}”</div> : null}
                </td>
                <td style={{ fontSize: 12.5 }}>{r.region || '—'}</td>
                <td style={{ fontSize: 12.5 }}>{r.contact || '—'}</td>
                <td className="num">{rel(r.createdAt)}</td>
                <td><Badge v={r.status === 'approved' ? 'active' : r.status === 'rejected' ? 'churned' : 'onboarding'}>{r.status}</Badge></td>
                <td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
                  {r.status === 'pending' ? (
                    <span style={{ display: 'inline-flex', gap: 8 }}>
                      <button className="btn btn-ghost btn-sm" disabled={busy === r.userId} onClick={() => reject(r)}>Decline</button>
                      <button className="btn btn-primary btn-sm" disabled={busy === r.userId} onClick={() => approve(r)}>{busy === r.userId ? '…' : 'Approve'}</button>
                    </span>
                  ) : (r.wineryId ? <button className="btn btn-ghost btn-sm" onClick={() => window.go('wineries', r.wineryId)}>View winery</button> : null)}
                </td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan="6"><window.UI.Empty msg={tab === 'pending' ? 'No signups awaiting review' : 'No reviewed signups yet'} hint={tab === 'pending' ? 'New portal registrations land here for approval.' : null} /></td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { Approvals });
