'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { listAuditLog, type AuditLogEntry } from '@/features/audit-log/api.client';
import { listContacts } from '@/features/contacts/api.client';
import { listDeals } from '@/features/deals/api.client';
import {
  getMember,
  getMemberProfile,
  listMembers,
  resendInvite,
  sendMemberPasswordReset,
  setMemberStatus,
  updateMember,
  impersonateMember,
  removeMember,
  SEAT_OPTIONS,
  type Member,
} from '@/features/members/api.client';
import { getBulkOperation, startBulk } from '@/features/bulk/api.client';
import { listSequences } from '@/features/sequences/api.client';
import { getProfile } from '@/features/settings/api.client';
import type { WorkingHourRow } from '@/features/settings/types';
import { bulkTasks, getTaskCounts, listTasks } from '@/features/tasks/api.client';
import { listWorkflows } from '@/features/workflows/api.client';
import { errorText } from '@/lib/api/errors';
import { SetDialog } from './settings-ui';
import { AccessPanel } from './user-details/AccessPanel';
import { ExtIcon } from './user-details/parts';
import {
  isPreferencesSub,
  PreferencesPanel,
  type PreferencesSub,
} from './user-details/PreferencesPanel';
import { isRoutingSub, RoutingPanel, type RoutingSub } from './user-details/RoutingPanel';
import { isSetupSub, SetupPanel, type SetupSub } from './user-details/SetupPanel';

const TABS = [
  ['overview', 'Overview'],
  ['access', 'Access'],
  ['setup', 'Setup'],
  ['routing', 'Routing'],
  ['preferences', 'Preferences'],
] as const;

type TabId = (typeof TABS)[number][0];
type RangeId = 'today' | 'week' | 'month' | 'Last 30 days' | 'Last 90 days';

const RANGES: Array<[RangeId, string]> = [
  ['today', 'Today'],
  ['week', 'This week'],
  ['month', 'This month'],
  ['Last 30 days', 'Last 30 days'],
  ['Last 90 days', 'Last 90 days'],
];

const SEAT_LABEL = Object.fromEntries(SEAT_OPTIONS.map((o) => [o.value, o.label]));

/** Rows the design offers "Bulk assign all" on. Sequences and workflows have no owner job. */
type BulkKind = 'tasks' | 'deals' | 'contacts';

const BULK_LABEL: Record<BulkKind, string> = {
  tasks: 'Tasks',
  deals: 'Open deals',
  contacts: 'Contacts',
};

/** Waits out a queued owner change (HUB-371). A small one often comes back already finished. */
async function finishBulk(id: string, first: Awaited<ReturnType<typeof startBulk>>) {
  let op = first;
  for (let i = 0; i < 20 && op.status !== 'done' && op.status !== 'failed'; i += 1) {
    await new Promise((resolve) => setTimeout(resolve, 400));
    op = await getBulkOperation(id);
  }
  if (op.status === 'failed') throw new Error(op.error ?? 'Bulk assign failed');
  if (op.status !== 'done') {
    throw new Error('Bulk assign is still running. Refresh this page in a moment.');
  }
  return op.succeeded;
}

function initials(name: string): string {
  return name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? '')
    .join('');
}

function formatWhen(iso: string | null): string {
  if (!iso) return '--';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '--';
  return date.toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });
}

function rangeStart(range: RangeId): string {
  const start = new Date();
  if (range === 'today') start.setHours(0, 0, 0, 0);
  else if (range === 'week') {
    start.setDate(start.getDate() - start.getDay());
    start.setHours(0, 0, 0, 0);
  } else if (range === 'month') {
    start.setDate(1);
    start.setHours(0, 0, 0, 0);
  } else if (range === 'Last 30 days') start.setDate(start.getDate() - 30);
  else start.setDate(start.getDate() - 90);
  return start.toISOString();
}

function hoursToday(rows: WorkingHourRow[]): string {
  const index = new Date().getDay();
  const day = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][index]!;
  const weekend = index === 0 || index === 6;
  const match = rows.find((row) => {
    if (row.day === 'everyday' || row.day === day) return true;
    if (row.day === 'mon-fri') return !weekend;
    if (row.day === 'sat-sun') return weekend;
    return false;
  });
  return match ? `${match.start}–${match.end}` : 'Unavailable';
}

async function loadMembers(): Promise<Member[]> {
  const all: Member[] = [];
  let cursor: string | undefined;
  for (let page = 0; page < 20; page += 1) {
    const list = await listMembers({ limit: 100, cursor });
    all.push(...list.data);
    if (!list.nextCursor) break;
    cursor = list.nextCursor;
  }
  return all;
}

async function countOf(
  load: () => Promise<{ total?: number; data: unknown[] }>,
): Promise<number | null> {
  try {
    const page = await load();
    return typeof page.total === 'number' ? page.total : page.data.length;
  } catch {
    return null;
  }
}

/**
 * A user's page (design user-details.php): header, Actions and the Overview, Access, Setup,
 * Routing and Preferences tabs. `userId` is missing on the signed-in user's own page
 * (/settings/user), which every user may open; the page of another user needs Manage users.
 */
export function UserDetailsView({ userId: routeUserId }: { userId?: string }) {
  const toast = useToast();
  const router = useRouter();
  const me = useCurrentUser();
  const searchParams = useSearchParams();
  const userId = routeUserId ?? me.user.id;
  const base = routeUserId ? `/settings/users/${routeUserId}` : '/settings/user';
  const tabParam = searchParams.get('tab');
  const subParam = searchParams.get('sub');
  const tab: TabId = TABS.some(([id]) => id === tabParam) ? (tabParam as TabId) : 'overview';
  const setupSub: SetupSub = isSetupSub(subParam) ? subParam : 'presets';
  const routingSub: RoutingSub = isRoutingSub(subParam) ? subParam : 'capacity';
  const prefsSub: PreferencesSub = isPreferencesSub(subParam) ? subParam : 'profile';
  const [member, setMember] = useState<Member | null>(null);
  const [allMembers, setAllMembers] = useState<Member[]>([]);
  const [limited, setLimited] = useState(false);
  const [missing, setMissing] = useState(false);
  const [actionsOpen, setActionsOpen] = useState(false);
  const [hours, setHours] = useState<string | null>(null);
  const [counts, setCounts] = useState<Record<string, number | null> | null>(null);
  const [countNonce, setCountNonce] = useState(0);
  const [bulk, setBulk] = useState<BulkKind | null>(null);
  const [bulkOwner, setBulkOwner] = useState('');
  const [bulkBusy, setBulkBusy] = useState(false);
  const [activityRange, setActivityRange] = useState<RangeId>('week');
  const [securityRange, setSecurityRange] = useState<RangeId>('week');
  const [activity, setActivity] = useState<AuditLogEntry[] | null>(null);
  const [security, setSecurity] = useState<{ ok: number; fail: number; actions: number } | null>(
    null,
  );

  const mayList = me.permissionSet.rules.app.manage_users === true;
  const self = me.user.id === userId;

  const go = (next: TabId, sub?: string) => {
    const query = new URLSearchParams({ tab: next });
    if (sub) query.set('sub', sub);
    const hash = sub === 'working-hours' ? '#working-hours' : '';
    router.replace(`${base}?${query.toString()}${hash}`, { scroll: false });
  };

  const reload = useCallback(async () => {
    try {
      // The member itself (GET /members/:userId) plus the full list for the bulk and manager pickers.
      const [found, all] = await Promise.all([getMember(userId), loadMembers()]);
      setAllMembers(all);
      setMember(found);
      setMissing(false);
      setLimited(false);
    } catch (err) {
      if (me.user.id === userId && !mayList) {
        // Without Manage users the member list is closed, so show the user's own details.
        setLimited(true);
        setMember({
          userId: me.user.id,
          name: me.user.name,
          email: me.user.email,
          role: me.role,
          status: 'active',
          lastLoginAt: null,
          createdAt: '',
          inviteStatus: 'accepted',
          seat: 'core',
          permissionSet: me.permissionSet.id
            ? { id: me.permissionSet.id, name: me.permissionSet.name, systemKey: null }
            : null,
          defaultTeam: null,
          extraTeams: [],
          accessPresetId: null,
        });
      } else {
        setMissing(true);
        toast(errorText(err), 'danger');
      }
    }
  }, [me, mayList, toast, userId]);

  useEffect(() => {
    void reload();
  }, [reload]);

  // Today's hours: the signed-in user's own, or an admin's view of another member's (both stored on
  // the member's profile). A limited signed-in user without Manage users has no one else to show.
  useEffect(() => {
    if (!self && !mayList) return;
    let alive = true;
    (self ? getProfile() : getMemberProfile(userId)).then(
      (profile) => {
        if (alive) setHours(hoursToday(profile.preferences.generalWorkingHours ?? []));
      },
      () => {
        if (alive) setHours('Unavailable');
      },
    );
    return () => {
      alive = false;
    };
  }, [self, userId, mayList]);

  useEffect(() => {
    let alive = true;
    void (async () => {
      const [tasks, contacts, deals, sequences, workflows] = await Promise.all([
        getTaskCounts(userId)
          .then((counts) => counts.today + counts.overdue + counts.upcoming + counts.noDueDate)
          .catch(() => null),
        countOf(() => listContacts({ ownerId: userId, limit: 1 })),
        countOf(() => listDeals({ ownerId: userId, status: 'open', limit: 1 })),
        countOf(() => listSequences({ ownerId: userId, limit: 1, hideArchived: true })),
        countOf(() => listWorkflows({ ownerId: userId, limit: 1 })),
      ]);
      if (alive) {
        setCounts({ tasks, contacts, deals, sequences, workflows });
      }
    })();
    return () => {
      alive = false;
    };
  }, [countNonce, userId]);

  const loadActivity = useCallback(
    async (range: RangeId) => {
      const page = await listAuditLog({ actor: userId, from: rangeStart(range), limit: 8 });
      setActivity(page.data);
    },
    [userId],
  );

  const loadSecurity = useCallback(
    async (range: RangeId) => {
      const from = rangeStart(range);
      const [login, actions] = await Promise.all([
        listAuditLog({ actor: userId, view: 'login', from, limit: 50 }),
        listAuditLog({ actor: userId, view: 'security', from, limit: 50 }),
      ]);
      const fail = login.data.filter((row) => /fail|denied|unsuccess/i.test(row.action)).length;
      setSecurity({
        ok: Math.max(0, login.data.length - fail),
        fail,
        actions: actions.data.length,
      });
    },
    [userId],
  );

  useEffect(() => {
    if (tab !== 'overview') return;
    loadActivity(activityRange).catch(() => setActivity([]));
  }, [activityRange, loadActivity, tab]);

  useEffect(() => {
    if (tab !== 'overview') return;
    loadSecurity(securityRange).catch(() => setSecurity({ ok: 0, fail: 0, actions: 0 }));
  }, [loadSecurity, securityRange, tab]);

  const run = async (work: () => Promise<void>, done: string) => {
    try {
      await work();
      toast(done, 'success');
      setActionsOpen(false);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  if (!member && !missing) return <p className="crm-text-muted">Loading user…</p>;
  if (!member) return <p className="crm-text-muted">This user is not in the account.</p>;

  const deactivated = member.status === 'deactivated';
  const canManage = mayList && !limited && !deactivated;
  // Transfer stays available after deactivation: that is when the records need a new owner.
  const canAssign = mayList && !limited;
  const targets = allMembers.filter(
    (person) => person.userId !== member.userId && person.status === 'active',
  );
  const rows: Array<{
    name: string;
    type: string;
    href: string;
    count: number | null;
    bulk: BulkKind | null;
  }> = [
    {
      name: 'Tasks',
      type: 'CRM records and assets',
      href: `/tasks?assignee=${member.userId}`,
      count: counts?.tasks ?? null,
      bulk: 'tasks',
    },
    {
      name: 'Open deals',
      type: 'CRM records and assets',
      href: '/deals',
      count: counts?.deals ?? null,
      bulk: 'deals',
    },
    {
      name: 'Contacts',
      type: 'CRM records and assets',
      href: '/contacts',
      count: counts?.contacts ?? null,
      bulk: 'contacts',
    },
    {
      name: 'Sequences',
      type: 'Automations',
      href: '/sequences',
      count: counts?.sequences ?? null,
      bulk: null,
    },
    {
      name: 'Workflows',
      type: 'Automations',
      href: '/workflows',
      count: counts?.workflows ?? null,
      bulk: null,
    },
  ];

  const assignBulk = async () => {
    if (!bulk || !bulkOwner || bulkBusy) return;
    setBulkBusy(true);
    try {
      let moved = 0;
      if (bulk === 'tasks') {
        const ids: string[] = [];
        let cursor: string | undefined;
        for (let page = 0; page < 30; page += 1) {
          const list = await listTasks({
            assignee: member.userId,
            view: 'all',
            limit: 100,
            cursor,
          });
          ids.push(
            ...list.data.filter((task) => task.status !== 'completed').map((task) => task.id),
          );
          if (!list.nextCursor) break;
          cursor = list.nextCursor;
        }
        for (let index = 0; index < ids.length; index += 100) {
          const result = await bulkTasks({
            ids: ids.slice(index, index + 100),
            action: 'reassign',
            assigneeId: bulkOwner,
          });
          moved += result.updated;
        }
      } else {
        const started = await startBulk(bulk === 'deals' ? 'deal' : 'contact', {
          action: 'assign_owner',
          ownerId: bulkOwner,
          selection: {
            query:
              bulk === 'deals'
                ? { ownerId: member.userId, status: 'open' }
                : { ownerId: member.userId },
          },
        });
        moved = await finishBulk(started.id, started);
      }
      const who = targets.find((person) => person.userId === bulkOwner)?.name ?? 'the new owner';
      toast(`${moved} ${BULK_LABEL[bulk].toLowerCase()} assigned to ${who}.`, 'success');
      setBulk(null);
      setCountNonce((nonce) => nonce + 1);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBulkBusy(false);
    }
  };

  return (
    <div className="up-page" id="userProfile">
      <Link className="up-back" href={routeUserId ? '/settings/users' : '/settings/profile'}>
        <svg
          viewBox="0 0 24 24"
          width="16"
          height="16"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.8"
          aria-hidden
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
        Back
      </Link>
      <header className="up-head">
        <div className="up-avatar" aria-hidden>
          {initials(member.name) || '?'}
        </div>
        <div className="up-head__info">
          <h1 className="up-name">{member.name}</h1>
          <div className="up-meta">
            <span className="up-state">
              <span className={deactivated ? 'up-dot up-dot--off' : 'up-dot up-dot--on'} />
              {deactivated ? 'User deactivated' : 'User active'}
            </span>
            <span className="up-meta__sep" />
            <strong>{member.email}</strong>
            <span className="up-meta__sep" />
            <label className="up-status">
              User status:
              <span
                className={
                  member.availability === 'away' ? 'up-dot up-dot--away' : 'up-dot up-dot--on'
                }
              />
              <select
                className="up-inline-select"
                aria-label="User status"
                value={member.availability ?? 'available'}
                disabled={!canManage}
                onChange={(event) => {
                  const availability = event.target.value as 'available' | 'away';
                  void run(async () => {
                    const next = await updateMember(member.userId, { availability });
                    setMember(next);
                  }, 'User status saved.');
                }}
              >
                <option value="available">Available</option>
                <option value="away">Away</option>
              </select>
            </label>
          </div>
          <div className="up-meta">
            <span>Today&apos;s working hours: {hours ?? '…'}</span>
            <button
              type="button"
              className="up-link up-link--btn"
              onClick={() => go('preferences', 'working-hours')}
            >
              Edit working hours
            </button>
          </div>
        </div>
        {limited ? null : (
          <div className="up-head__actions">
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              aria-expanded={actionsOpen}
              onClick={() => setActionsOpen((open) => !open)}
            >
              Actions
            </button>
            {actionsOpen ? (
              <div className="dropdown__menu dropdown__menu--right" role="menu">
                <button
                  type="button"
                  className="dropdown__item"
                  disabled={deactivated}
                  onClick={() =>
                    void run(
                      () => sendMemberPasswordReset(member.userId),
                      'Password reset email sent.',
                    )
                  }
                >
                  Reset password
                </button>
                <button
                  type="button"
                  className="dropdown__item"
                  disabled={self || deactivated}
                  onClick={() =>
                    void run(async () => {
                      await impersonateMember(member.userId);
                      window.location.assign('/home');
                    }, `Now viewing as ${member.name}.`)
                  }
                >
                  Log in as user
                </button>
                <button
                  type="button"
                  className="dropdown__item"
                  disabled={member.inviteStatus !== 'pending'}
                  onClick={() => void run(() => resendInvite(member.userId), 'Invite resent.')}
                >
                  Resend invite
                </button>
                <button
                  type="button"
                  className="dropdown__item"
                  onClick={() =>
                    void run(async () => {
                      await navigator.clipboard.writeText(member.userId);
                    }, 'User ID copied.')
                  }
                >
                  Copy user ID
                </button>
                <div className="dropdown__rule" />
                <button
                  type="button"
                  className="dropdown__item"
                  disabled={self}
                  onClick={() =>
                    void run(
                      async () => {
                        const next = await setMemberStatus(
                          member.userId,
                          deactivated ? 'active' : 'deactivated',
                        );
                        setMember(next);
                      },
                      deactivated ? 'User reactivated.' : 'User deactivated.',
                    )
                  }
                >
                  {deactivated ? 'Reactivate user' : 'Deactivate user'}
                </button>
                <button
                  type="button"
                  className="dropdown__item crm-text-danger"
                  disabled={self}
                  onClick={() => {
                    if (!window.confirm(`Remove ${member.name} from this account?`)) return;
                    void run(async () => {
                      await removeMember(member.userId);
                      router.push('/settings/users');
                    }, 'User removed.');
                  }}
                >
                  Remove from account
                </button>
              </div>
            ) : null}
          </div>
        )}
      </header>

      <nav className="up-tabs" role="tablist" aria-label="User sections">
        {TABS.map(([id, label]) => (
          <button
            key={id}
            type="button"
            role="tab"
            className={tab === id ? 'up-tab is-active' : 'up-tab'}
            aria-selected={tab === id}
            onClick={() => go(id)}
          >
            {label}
          </button>
        ))}
      </nav>

      {tab === 'overview' ? (
        <section className="up-panel">
          {deactivated ? (
            <div className="up-banner">
              <strong>{member.name} can no longer access your account.</strong>
              <span>
                A deactivated user&apos;s historical activities and important data are still
                accessible and can be reactivated in the future.
              </span>
            </div>
          ) : null}
          <div className="up-card">
            <div className="up-card__title-row">
              <span className="up-illus" aria-hidden>
                <svg
                  viewBox="0 0 24 24"
                  width="24"
                  height="24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M21 8 12 3 3 8v8l9 5 9-5z" />
                  <path d="m3 8 9 5 9-5M12 13v8" />
                </svg>
              </span>
              <h2>Next steps: Transfer records and assets</h2>
            </div>
            <p className="up-muted">
              To provide a smooth transition of this user&apos;s work, please review the following
              records and assets associated with this user. This user may own CRM objects, or they
              may be used in assets and tools. You can edit them individually or in bulk from the
              record, asset, or tool. Note: Only open deals are eligible for reassignment. Closed
              deals will remain assigned to this user.
            </p>
            <div className="up-table-wrap">
              <table className="up-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Count</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((row) => (
                    <tr key={row.name}>
                      <td>{row.name}</td>
                      <td>{row.type}</td>
                      <td>
                        <Link className="up-link" href={row.href}>
                          {row.count == null ? '—' : row.count}
                        </Link>
                      </td>
                      <td>
                        <div className="up-row-actions">
                          <Link className="btn-crm btn-crm--outline btn-crm--sm" href={row.href}>
                            View all <ExtIcon />
                          </Link>
                          {row.bulk ? (
                            <button
                              type="button"
                              className="btn-crm btn-crm--outline btn-crm--sm"
                              disabled={!canAssign || !row.count}
                              title={
                                canAssign
                                  ? undefined
                                  : 'You need permission to manage users to reassign these.'
                              }
                              onClick={() => {
                                setBulkOwner(targets[0]?.userId ?? '');
                                setBulk(row.bulk);
                              }}
                            >
                              Bulk assign all
                            </button>
                          ) : null}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
          <div className="up-grid">
            <div className="up-card">
              <h2>Summary</h2>
              <dl className="up-stats">
                <div>
                  <dt>Date created</dt>
                  <dd>{formatWhen(member.createdAt)}</dd>
                </div>
                <div>
                  <dt>Last active</dt>
                  <dd>{formatWhen(member.lastLoginAt)}</dd>
                </div>
                <div>
                  <dt>Invite status</dt>
                  <dd>{member.inviteStatus}</dd>
                </div>
              </dl>
            </div>
            <div className="up-card">
              <div className="up-card__head">
                <h2>User activity</h2>
                <label className="up-range">
                  Time range:
                  <select
                    className="up-select"
                    value={activityRange}
                    aria-label="Activity time range"
                    onChange={(event) => setActivityRange(event.target.value as RangeId)}
                  >
                    {RANGES.map(([value, label]) => (
                      <option key={value} value={value}>
                        {label}
                      </option>
                    ))}
                  </select>
                </label>
              </div>
              {activity == null ? (
                <p className="up-empty-line">Loading activity…</p>
              ) : activity.length === 0 ? (
                <p className="up-empty-line">No activity in this range.</p>
              ) : (
                <ul className="up-activity">
                  {activity.map((row) => (
                    <li key={row.id}>
                      {row.action}
                      <time dateTime={row.createdAt}>{formatWhen(row.createdAt)}</time>
                    </li>
                  ))}
                </ul>
              )}
              <Link className="up-link" href="/settings/audit-log">
                Open audit log <ExtIcon />
              </Link>
            </div>
            <div className="up-card">
              <div className="up-card__head">
                <h2>Security activity</h2>
                <label className="up-range">
                  Time range:
                  <select
                    className="up-select"
                    value={securityRange}
                    aria-label="Security time range"
                    onChange={(event) => setSecurityRange(event.target.value as RangeId)}
                  >
                    {RANGES.map(([value, label]) => (
                      <option key={value} value={value}>
                        {label}
                      </option>
                    ))}
                  </select>
                </label>
              </div>
              <dl className="up-stats up-stats--3">
                <div>
                  <dt>Successful logins</dt>
                  <dd>{security?.ok ?? '—'}</dd>
                </div>
                <div>
                  <dt>Unsuccessful logins</dt>
                  <dd>{security?.fail ?? '—'}</dd>
                </div>
                <div>
                  <dt>Security actions</dt>
                  <dd>{security?.actions ?? '—'}</dd>
                </div>
              </dl>
              <Link className="up-link" href="/settings/security">
                Open security activities <ExtIcon />
              </Link>
            </div>
            <div className="up-card">
              <h2>Teams and access</h2>
              <ul className="up-connected">
                <li>
                  <span>Default team</span>
                  <span className="up-pill">{member.defaultTeam?.name ?? 'None'}</span>
                </li>
                <li>
                  <span>Extra teams</span>
                  <span className="up-pill">
                    {member.extraTeams.length
                      ? member.extraTeams.map((team) => team.name).join(', ')
                      : 'None'}
                  </span>
                </li>
                <li>
                  <span>Seat</span>
                  <span className="up-pill">{SEAT_LABEL[member.seat] ?? member.seat}</span>
                </li>
                <li>
                  <span>Permission set</span>
                  <span className="up-pill">{member.permissionSet?.name ?? 'None'}</span>
                </li>
              </ul>
            </div>
          </div>
        </section>
      ) : null}

      {tab === 'access' ? (
        <AccessPanel
          member={member}
          self={self}
          canManage={canManage}
          allMembers={allMembers}
          onMember={setMember}
        />
      ) : null}

      {tab === 'setup' ? (
        <SetupPanel
          member={member}
          self={self}
          canManage={canManage}
          allMembers={allMembers}
          onMember={setMember}
          onReload={reload}
          sub={setupSub}
          onSub={(sub) => go('setup', sub)}
        />
      ) : null}

      {tab === 'routing' ? (
        <RoutingPanel sub={routingSub} onSub={(sub) => go('routing', sub)} />
      ) : null}

      {tab === 'preferences' ? (
        <PreferencesPanel
          member={member}
          self={self}
          canManage={canManage}
          allMembers={allMembers}
          onMember={setMember}
          sub={prefsSub}
          onSub={(sub) => go('preferences', sub)}
          onHours={(saved) => setHours(hoursToday(saved))}
        />
      ) : null}

      <SetDialog open={bulk != null} onClose={() => setBulk(null)} labelledBy="up-bulk-title">
        <div className="set-modal__head">
          <h2 className="set-modal__title" id="up-bulk-title">
            Bulk assign {bulk ? BULK_LABEL[bulk].toLowerCase() : ''}
          </h2>
        </div>
        <form
          className="set-modal__body"
          onSubmit={(event) => {
            event.preventDefault();
            void assignBulk();
          }}
        >
          <p className="up-muted">
            Every {bulk === 'deals' ? 'open deal' : bulk === 'tasks' ? 'open task' : 'contact'} this
            user owns moves to the person you pick. Closed deals stay with this user.
          </p>
          <div className="up-field">
            <label htmlFor="up-bulk-owner">New owner</label>
            <select
              className="up-select"
              id="up-bulk-owner"
              value={bulkOwner}
              onChange={(event) => setBulkOwner(event.target.value)}
            >
              {targets.length === 0 ? <option value="">No other active users</option> : null}
              {targets.map((person) => (
                <option key={person.userId} value={person.userId}>
                  {person.name}
                </option>
              ))}
            </select>
          </div>
          <div className="set-modal__foot">
            <button
              type="submit"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={bulkBusy || !bulkOwner}
            >
              {bulkBusy ? 'Assigning…' : 'Assign'}
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={() => setBulk(null)}
            >
              Cancel
            </button>
          </div>
        </form>
      </SetDialog>
    </div>
  );
}
