// AdminPanel.jsx — AegisComply Master Control Panel (Supabase-powered)
// Only visible to users with tier = 'full_forever'

const adminStyles = {
  overlay: { position: 'fixed', inset: 0, background: 'rgba(7,15,30,0.7)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 },
  panel: { background: 'white', borderRadius: 14, width: '100%', maxWidth: 920, maxHeight: '92vh', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,0.3)', overflow: 'hidden' },
  header: { background: '#0B1F3A', padding: '16px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 },
  headerTitle: { fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 16, fontWeight: 700, color: 'white' },
  headerSub: { fontSize: 11, color: 'rgba(255,255,255,0.45)', marginTop: 2 },
  closeBtn: { width: 30, height: 30, borderRadius: 6, border: 'none', background: 'rgba(255,255,255,0.1)', color: 'white', cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  body: { flex: 1, overflowY: 'auto', padding: 20 },
  tabs: { display: 'flex', gap: 4, marginBottom: 16 },
  tab: { padding: '7px 16px', borderRadius: 6, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: 'none', background: '#F1F5F9', color: '#475569', fontFamily: "'DM Sans',sans-serif" },
  tabActive: { background: '#0B1F3A', color: 'white' },
  userTable: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden' },
  thead: { display: 'grid', gridTemplateColumns: '1.6fr 1.4fr 0.9fr 1.1fr 1.3fr 120px', gap: 8, padding: '9px 14px', background: '#F8FAFC', borderBottom: '1px solid #E2E8F0' },
  trow: { display: 'grid', gridTemplateColumns: '1.6fr 1.4fr 0.9fr 1.1fr 1.3fr 120px', gap: 8, padding: '10px 14px', borderBottom: '1px solid #F1F5F9', alignItems: 'center' },
  thc: { fontSize: 10, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', color: '#94A3B8' },
  tier: { display: 'inline-flex', padding: '2px 8px', borderRadius: 4, fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' },
  tierColors: {
    pilot:        { bg: '#F0FDFA', color: '#0D9488' },
    monthly:      { bg: '#F0FDF4', color: '#16A34A' },
    yearly:       { bg: '#EFF6FF', color: '#2563EB' },
    frozen:       { bg: '#FFF5F5', color: '#DC2626' },
    full_forever: { bg: '#0B1F3A', color: '#14B8A6' },
  },
  actionBtn: { height: 26, padding: '0 10px', borderRadius: 4, border: 'none', fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  modal: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 3000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 },
  modalCard: { background: 'white', borderRadius: 12, width: '100%', maxWidth: 480, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 16px 48px rgba(0,0,0,0.2)' },
  modalHeader: { padding: '16px 20px', borderBottom: '1px solid #F1F5F9', fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A' },
  modalBody: { padding: '18px 20px' },
  modalFooter: { padding: '14px 20px', borderTop: '1px solid #F1F5F9', display: 'flex', justifyContent: 'flex-end', gap: 8 },
  fieldGroup: { marginBottom: 12 },
  fieldLabel: { fontSize: 12, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 4 },
  fieldInput: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 12px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white', boxSizing: 'border-box' },
  infoRow: { display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0', borderBottom: '1px solid #F8FAFC', color: '#475569' },
  infoLabel: { color: '#94A3B8', fontWeight: 500 },
  successMsg: { background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: 6, padding: '10px 12px', fontSize: 12, color: '#16A34A', marginBottom: 12 },
  warningMsg: { background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 6, padding: '10px 12px', fontSize: 12, color: '#92400E', marginBottom: 12 },
  errorMsg:   { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '10px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 },
  empty: { padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 13 },
  logRow: { padding: '10px 14px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'flex-start', gap: 12 },
  logIcon: { width: 28, height: 28, borderRadius: 6, background: '#F0FDFA', color: '#0D9488', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
  logTitle: { fontSize: 12, fontWeight: 600, color: '#0F172A' },
  logMeta: { fontSize: 11, color: '#94A3B8', marginTop: 2 },
  logDetails: { fontSize: 11, color: '#64748B', marginTop: 2, fontFamily: "'JetBrains Mono', monospace", background: '#F8FAFC', padding: '4px 6px', borderRadius: 3 },
  btn: { height: 32, padding: '0 14px', border: '1px solid #CBD5E1', borderRadius: 5, background: 'white', fontSize: 12, color: '#334155', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  btnPrimary: { height: 32, padding: '0 16px', border: 'none', borderRadius: 5, background: '#0D9488', fontSize: 12, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  btnPrimaryDisabled: { background: '#CBD5E1', cursor: 'not-allowed' },
};

function TierBadge({ tier }) {
  const c = adminStyles.tierColors[tier] || adminStyles.tierColors.pilot;
  return <span style={{ ...adminStyles.tier, background: c.bg, color: c.color }}>{(tier || 'pilot').replace('_', ' ')}</span>;
}

function adminFmt(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-MY', { day: 'numeric', month: 'short', year: 'numeric' }); }
  catch { return d; }
}

// ── Helper: log an admin action to activity_log ─────────────────────────────
async function logAdminAction(adminUserId, action, details) {
  const sb = window.supabaseClient;
  if (!sb) return;
  try {
    await sb.from('activity_log').insert({
      user_id: adminUserId,
      action,
      details,
    });
  } catch (err) {
    console.warn('[Admin] activity log insert failed:', err.message);
  }
}

// ── Subscription Modal ──────────────────────────────────────────────────────
function SubscriptionModal({ targetUser, adminUser, onClose, onSaved }) {
  const [months, setMonths] = React.useState(1);
  const [action, setAction] = React.useState('activate'); // activate | freeze | full_forever | pilot
  const [note, setNote]     = React.useState('');
  const [saving, setSaving] = React.useState(false);
  const [error, setError]   = React.useState('');
  const [saved, setSaved]   = React.useState(false);

  const handleSave = async () => {
    setSaving(true); setError('');
    try {
      const sb = window.supabaseClient;
      const now = new Date();
      const end = new Date(now);
      end.setMonth(end.getMonth() + months);

      let newTier = 'monthly';
      let subEnd  = null;
      if (action === 'activate')      { newTier = months >= 12 ? 'yearly' : 'monthly'; subEnd = end.toISOString(); }
      if (action === 'freeze')        { newTier = 'frozen';       subEnd = now.toISOString(); }
      if (action === 'full_forever')  { newTier = 'full_forever'; subEnd = null; }
      if (action === 'pilot')         { newTier = 'pilot';        subEnd = null; }

      const notePrefix = `[${now.toLocaleDateString('en-MY')}] ${action}${action === 'activate' ? ` ${months}mo` : ''}`;
      const newNote = note ? `${notePrefix} — ${note}` : notePrefix;
      const combinedNotes = targetUser.admin_notes
        ? `${targetUser.admin_notes}\n${newNote}`
        : newNote;

      const { error: upErr } = await sb.from('users').update({
        tier:               newTier,
        subscription_start: action === 'activate' ? now.toISOString() : (action === 'freeze' ? targetUser.subscription_start : null),
        subscription_end:   subEnd,
        manual_override:    true,
        admin_notes:        combinedNotes,
        override_months:    action === 'activate' ? months : 0,
      }).eq('id', targetUser.id);
      if (upErr) throw upErr;

      // Log admin action
      await logAdminAction(adminUser.id, 'subscription_change', {
        target_user_id: targetUser.id,
        target_email:   targetUser.email,
        action,
        months,
        new_tier:       newTier,
        note,
      });

      setSaved(true);
      setTimeout(() => onSaved(), 1200);
    } catch (err) {
      console.error('[Admin] subscription change error:', err);
      setError(err.message || 'Update failed.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={adminStyles.modal} onClick={saving ? undefined : onClose}>
      <div style={adminStyles.modalCard} onClick={e => e.stopPropagation()}>
        <div style={adminStyles.modalHeader}>Manage Subscription — {targetUser.name}</div>
        <div style={adminStyles.modalBody}>
          {saved ? (
            <div style={adminStyles.successMsg}>
              ✓ Subscription updated for <strong>{targetUser.email}</strong>.<br/>
              <span style={{ fontSize: 11, color: '#16A34A', opacity: 0.7 }}>In production: user would receive email + WhatsApp notification automatically (Resend / Twilio integration to be added).</span>
            </div>
          ) : (
            <>
              {error && <div style={adminStyles.errorMsg}>{error}</div>}

              <div style={{ ...adminStyles.infoRow, marginBottom: 10 }}>
                <span style={adminStyles.infoLabel}>Current tier</span>
                <TierBadge tier={targetUser.tier}/>
              </div>
              <div style={adminStyles.infoRow}>
                <span style={adminStyles.infoLabel}>Subscription ends</span>
                <span>{adminFmt(targetUser.subscription_end)}</span>
              </div>
              <div style={{ ...adminStyles.infoRow, marginBottom: 14 }}>
                <span style={adminStyles.infoLabel}>Pilot used</span>
                <span>{targetUser.pilot_used ? 'Yes' : 'No'}</span>
              </div>

              <div style={adminStyles.fieldGroup}>
                <label style={adminStyles.fieldLabel}>Action</label>
                <select style={adminStyles.fieldInput} value={action} onChange={e => setAction(e.target.value)}>
                  <option value="activate">Activate Subscription (manual payment received)</option>
                  <option value="freeze">Freeze Account (payment lapsed)</option>
                  <option value="full_forever">Grant Full Access Forever</option>
                  <option value="pilot">Reset to 14-Day Pilot</option>
                </select>
              </div>

              {action === 'activate' && (
                <div style={adminStyles.fieldGroup}>
                  <label style={adminStyles.fieldLabel}>Duration (months)</label>
                  <select style={adminStyles.fieldInput} value={months} onChange={e => setMonths(parseInt(e.target.value))}>
                    {[1, 2, 3, 6, 12].map(m => (
                      <option key={m} value={m}>
                        {m} month{m > 1 ? 's' : ''} — expires {new Date(new Date().setMonth(new Date().getMonth() + m)).toLocaleDateString('en-MY', { day: 'numeric', month: 'short', year: 'numeric' })}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {action === 'freeze' && (
                <div style={adminStyles.warningMsg}>
                  Account will be locked. User can still log in and VIEW data but cannot add, edit, or approve anything.
                </div>
              )}

              {action === 'full_forever' && (
                <div style={adminStyles.warningMsg}>
                  ⚠️ Grants permanent unrestricted access including admin panel rights. Use sparingly.
                </div>
              )}

              <div style={adminStyles.fieldGroup}>
                <label style={adminStyles.fieldLabel}>Admin Note (optional)</label>
                <input style={adminStyles.fieldInput} placeholder="e.g. Paid RM289 on 3 May 2026 via Maybank" value={note} onChange={e => setNote(e.target.value)}/>
              </div>

              <div style={{ fontSize: 11, color: '#94A3B8', lineHeight: 1.6 }}>
                📧 Will eventually notify: <strong>{targetUser.email}</strong><br/>
                📱 WhatsApp: <strong>{targetUser.whatsapp || 'not set'}</strong>
              </div>
            </>
          )}
        </div>
        <div style={adminStyles.modalFooter}>
          <button onClick={onClose} style={adminStyles.btn} disabled={saving}>
            {saved ? 'Close' : 'Cancel'}
          </button>
          {!saved && (
            <button
              onClick={handleSave}
              style={{ ...adminStyles.btnPrimary, ...(saving ? adminStyles.btnPrimaryDisabled : {}) }}
              disabled={saving}
            >
              {saving ? 'Saving…' : 'Apply Changes'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Main Admin Panel ────────────────────────────────────────────────────────
function AdminPanel({ onClose, user }) {
  const [tab, setTab]       = React.useState('users');
  const [users, setUsers]   = React.useState([]);
  const [logs, setLogs]     = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError]   = React.useState('');
  const [search, setSearch] = React.useState('');
  const [manageUser, setManageUser] = React.useState(null);

  const fetchAll = React.useCallback(async () => {
    setLoading(true); setError('');
    try {
      const sb = window.supabaseClient;
      const [{ data: u, error: ue }, { data: l, error: le }] = await Promise.all([
        sb.from('users').select('*').order('created_at', { ascending: false }),
        sb.from('activity_log').select('*').order('created_at', { ascending: false }).limit(100),
      ]);
      if (ue) throw ue;
      if (le) console.warn('[Admin] activity log fetch failed:', le.message);
      setUsers(u || []);
      setLogs(l || []);
    } catch (err) {
      console.error('[Admin] load error:', err);
      setError(err.message || 'Failed to load admin data. Make sure you have run the master RLS policy SQL.');
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { fetchAll(); }, [fetchAll]);

  // Realtime — refresh when users or activity_log change
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`admin-watcher-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'users' }, () => fetchAll())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'activity_log' }, () => fetchAll())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchAll]);

  const filtered = users.filter(u => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (u.email || '').toLowerCase().includes(q)
        || (u.name || '').toLowerCase().includes(q)
        || (u.company || '').toLowerCase().includes(q);
  });

  const stats = {
    total:  users.length,
    pilot:  users.filter(u => u.tier === 'pilot').length,
    active: users.filter(u => ['monthly', 'yearly', 'full_forever'].includes(u.tier)).length,
    frozen: users.filter(u => u.tier === 'frozen').length,
  };

  return (
    <div style={adminStyles.overlay}>
      <div style={adminStyles.panel}>
        <div style={adminStyles.header}>
          <div>
            <div style={adminStyles.headerTitle}>⚡ Admin Control Panel</div>
            <div style={adminStyles.headerSub}>AegisComply Master Dashboard — {user?.email || ''}</div>
          </div>
          <button style={adminStyles.closeBtn} onClick={onClose}>✕</button>
        </div>

        <div style={adminStyles.body}>
          {error && <div style={adminStyles.errorMsg}>{error}</div>}

          {/* KPI Stats */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10, marginBottom: 16 }}>
            {[
              { label: 'Total Users', val: stats.total,  color: '#0B1F3A' },
              { label: 'On Pilot',    val: stats.pilot,  color: '#0D9488' },
              { label: 'Active Paid', val: stats.active, color: '#16A34A' },
              { label: 'Frozen',      val: stats.frozen, color: '#DC2626' },
            ].map((s, i) => (
              <div key={i} style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 7, padding: '10px 14px', textAlign: 'center' }}>
                <div style={{ fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 24, fontWeight: 700, color: s.color }}>{s.val}</div>
                <div style={{ fontSize: 11, color: '#64748B' }}>{s.label}</div>
              </div>
            ))}
          </div>

          {/* Tabs */}
          <div style={adminStyles.tabs}>
            {[['users', 'Users'], ['create', 'New Client'], ['logs', `Activity Log (${logs.length})`]].map(([id, label]) => (
              <button key={id} style={{ ...adminStyles.tab, ...(tab === id ? adminStyles.tabActive : {}) }} onClick={() => setTab(id)}>{label}</button>
            ))}
          </div>

          {tab === 'users' && (
            <>
              <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
                <input
                  style={{ flex: 1, height: 32, border: '1px solid #E2E8F0', borderRadius: 6, padding: '0 10px', fontSize: 12, fontFamily: "'DM Sans',sans-serif", outline: 'none', boxSizing: 'border-box' }}
                  placeholder="Search by name, email, company…"
                  value={search} onChange={e => setSearch(e.target.value)}
                />
              </div>
              <div style={adminStyles.userTable}>
                <div style={adminStyles.thead}>
                  {['User / Company', 'Email', 'Tier', 'Sub. Ends', 'Notes', 'Action'].map(h => <div key={h} style={adminStyles.thc}>{h}</div>)}
                </div>
                {loading ? (
                  <div style={adminStyles.empty}>Loading…</div>
                ) : filtered.length === 0 ? (
                  <div style={adminStyles.empty}>No users found.</div>
                ) : filtered.map((u, i) => (
                  <div key={u.id} style={{ ...adminStyles.trow, background: u.tier === 'frozen' ? '#FFF8F8' : i % 2 === 0 ? 'white' : '#FAFCFF' }}>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: '#0F172A' }}>{u.name || '—'}</div>
                      <div style={{ fontSize: 10, color: '#94A3B8' }}>{u.company || '—'}</div>
                    </div>
                    <div style={{ fontSize: 11, color: '#475569', wordBreak: 'break-all' }}>{u.email}</div>
                    <TierBadge tier={u.tier}/>
                    <div style={{ fontSize: 11, color: u.subscription_end ? '#475569' : '#94A3B8' }}>
                      {adminFmt(u.subscription_end)}
                    </div>
                    <div style={{ fontSize: 10, color: '#94A3B8', lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={u.admin_notes || ''}>
                      {u.admin_notes ? (u.admin_notes.length > 40 ? u.admin_notes.slice(0, 40) + '…' : u.admin_notes) : '—'}
                    </div>
                    <div style={{ display: 'flex', gap: 4 }}>
                      {u.id !== user?.id && (
                        <button
                          style={{ ...adminStyles.actionBtn, background: '#0D9488', color: 'white' }}
                          onClick={() => setManageUser(u)}
                        >Manage</button>
                      )}
                      {u.id === user?.id && (
                        <span style={{ fontSize: 10, color: '#94A3B8', fontStyle: 'italic' }}>You</span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}

          {tab === 'create' && (
            <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8, padding: 24 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#0F172A', marginBottom: 8 }}>Create Account for a Client</div>
              <div style={{ fontSize: 12, color: '#475569', lineHeight: 1.7, marginBottom: 16 }}>
                Creating user accounts requires the Supabase Auth API (which is locked down for security).
                The cleanest way to onboard a client is:
              </div>
              <ol style={{ fontSize: 12, color: '#334155', lineHeight: 1.9, paddingLeft: 22, marginBottom: 16 }}>
                <li>Open <strong>Supabase Dashboard → Authentication → Users → Add user</strong></li>
                <li>Enter the client's email and a temporary password</li>
                <li>Tick <strong>"Auto Confirm User"</strong></li>
                <li>The new user appears in the <strong>Users</strong> tab here automatically</li>
                <li>Click <strong>Manage</strong> on their row to set tier + subscription length</li>
                <li>Share the temporary password with the client via WhatsApp / email — they can change it on first login</li>
              </ol>
              <div style={{ fontSize: 11, color: '#94A3B8', lineHeight: 1.6 }}>
                💡 In a future update, this can be automated via a Supabase Edge Function that creates the Auth user and emails them a welcome message. For now, the 2-minute manual flow above is what production SaaS apps use too.
              </div>
            </div>
          )}

          {tab === 'logs' && (
            <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden' }}>
              {loading ? (
                <div style={adminStyles.empty}>Loading…</div>
              ) : logs.length === 0 ? (
                <div style={adminStyles.empty}>
                  No activity logged yet. Admin actions (subscription changes, etc.) will appear here as they happen.
                </div>
              ) : logs.map((log) => {
                const details = log.details && typeof log.details === 'object' ? log.details : null;
                return (
                  <div key={log.id} style={adminStyles.logRow}>
                    <div style={adminStyles.logIcon}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={adminStyles.logTitle}>{log.action}</div>
                      <div style={adminStyles.logMeta}>
                        {new Date(log.created_at).toLocaleString('en-MY', { dateStyle: 'medium', timeStyle: 'short' })}
                        {details?.target_email && ` · ${details.target_email}`}
                      </div>
                      {details && (
                        <div style={adminStyles.logDetails}>
                          {Object.entries(details).map(([k, v]) => `${k}=${typeof v === 'object' ? JSON.stringify(v) : v}`).join(' · ')}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {manageUser && (
        <SubscriptionModal
          targetUser={manageUser}
          adminUser={user}
          onClose={() => setManageUser(null)}
          onSaved={() => { setManageUser(null); fetchAll(); }}
        />
      )}
    </div>
  );
}

Object.assign(window, { AdminPanel });
