'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  deactivateSecurityUsers,
  demoteSecurityAdmins,
  getSecuritySettings,
  remindSecurity2fa,
  updateSecuritySettings,
  type LoginMethod,
  type LoginMethods,
  type SecuritySettings,
  type SecuritySso,
  type SecurityUser,
} from '../api.client';
import {
  DialogHead,
  SetDialog,
  SetTabs,
  SettingsForm,
  SettingsFormsProvider,
  TabPanel,
  useHashTab,
} from './settings-ui';

const TABS = [
  { id: 'login', label: 'Login' },
  { id: 'permissions', label: 'Permissions' },
];

const LOGIN_METHOD_FIELDS: Array<{
  key: LoginMethod;
  name: string;
  label: string;
  /** Microsoft / Apple stay static (Coming Soon) — not user-configurable. */
  static?: boolean;
}> = [
  { key: 'apple', name: 'login_apple', label: 'Apple login', static: true },
  { key: 'google', name: 'login_google', label: 'Google login' },
  { key: 'microsoft', name: 'login_microsoft', label: 'Microsoft login', static: true },
  { key: 'chatgpt', name: 'login_chatgpt', label: 'ChatGPT login' },
  { key: 'passkeys', name: 'login_passkeys', label: 'Passkeys' },
  { key: 'password', name: 'login_password', label: 'Password' },
];

const DYNAMIC_METHODS: LoginMethod[] = ['google', 'chatgpt', 'passkeys', 'password'];

const ALL_METHODS_ON: LoginMethods = {
  apple: true,
  google: true,
  microsoft: true,
  chatgpt: true,
  passkeys: true,
  password: true,
};

/** When restrictions turn on: editable methods start off; static providers stay unavailable. */
const RESTRICTED_METHODS_START: LoginMethods = {
  apple: false,
  google: false,
  microsoft: false,
  chatgpt: false,
  passkeys: false,
  password: false,
};

const SEAT_FILTERS = [
  { value: '', label: 'All seats' },
  { value: 'No seat', label: 'No seat' },
  { value: 'View-only seat', label: 'View-only seat' },
  { value: 'Core seat', label: 'Core seat' },
  { value: 'Partner seat', label: 'Partner seat' },
  { value: 'Sales seat', label: 'Sales seat' },
  { value: 'Service seat', label: 'Service seat' },
];

const TYPE_FILTERS = [
  { value: '', label: 'All user types' },
  { value: 'Partner', label: 'Partner users' },
];

type ConfirmKey = '2fa' | 'account-limit' | 'employee-access';
type ManageKind = '2fa' | 'admins' | 'inactive';

const CONFIRM_COPY: Record<ConfirmKey, { title: string; text: string }> = {
  '2fa': {
    title: 'Require 2FA for login?',
    text: "In 24 hours, users on your account will be required to use two-factor authentication when they log in. Until then, encourage your users to set it up so they're ready for the change. Everyone without 2FA set up will be notified and directed to do so.",
  },
  'account-limit': {
    title: 'Limit users to only this account?',
    text: 'Users on this account will not be able to be added to additional accounts in the future. Do you want to enable this restriction?',
  },
  'employee-access': {
    title: 'Disable support access?',
    text: "Disabling support access will block our team from accessing your account for troubleshooting. This doesn't restrict access to all account data. If you disable this setting, you will need to enable it again if you need to allow the support team to access your account.",
  },
};

function markLoginFormDirty() {
  const form = document.getElementById('security-login-form');
  form?.dispatchEvent(new Event('change', { bubbles: true }));
}

function csvEscape(value: string) {
  if (/[",\n]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
  return value;
}

function downloadCsv(name: string, rows: string[][]) {
  const csv = rows.map((row) => row.map(csvEscape).join(',')).join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = name;
  link.click();
  URL.revokeObjectURL(link.href);
}

function people(n: number, one: string, many: string) {
  return n === 1 ? one : many;
}

function CardSwitch({
  checked,
  onChange,
  label,
  name,
}: {
  checked: boolean;
  onChange: (next: boolean, event: React.ChangeEvent<HTMLInputElement>) => void;
  label: string;
  name: string;
}) {
  return (
    <label className="switch security-card-switch" aria-label={label}>
      <input
        type="checkbox"
        name={name}
        checked={checked}
        onChange={(event) => onChange(event.target.checked, event)}
      />
      <span className="switch__track" />
    </label>
  );
}

function FilterMenu({
  kind,
  value,
  options,
  onChange,
}: {
  kind: 'seat' | 'type';
  value: string;
  options: Array<{ value: string; label: string }>;
  onChange: (value: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const selected = options.find((row) => row.value === value) ?? options[0]!;
  useEffect(() => {
    if (!open) return;
    const close = (event: MouseEvent) => {
      if (!(event.target as HTMLElement).closest(`[data-security-filter="${kind}"]`)) {
        setOpen(false);
      }
    };
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setOpen(false);
    };
    document.addEventListener('click', close);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', close);
      document.removeEventListener('keydown', onKey);
    };
  }, [kind, open]);
  return (
    <div className={cn('security-filter-dropdown', open && 'is-open')} data-security-filter={kind}>
      <button
        type="button"
        className="security-filter-trigger"
        aria-expanded={open}
        onClick={(event) => {
          event.stopPropagation();
          setOpen((current) => !current);
        }}
      >
        {selected.label}{' '}
        <svg viewBox="0 0 12 12" aria-hidden="true">
          <path d="m3 4.5 3 3 3-3" fill="currentColor" />
        </svg>
      </button>
      <div
        className={cn('security-filter-menu', kind === 'type' && 'security-filter-menu--compact')}
        hidden={!open}
      >
        {options.map((row) => (
          <button
            key={row.label}
            type="button"
            data-filter-value={row.value}
            className={cn(row.value === value && 'is-selected')}
            onClick={(event) => {
              event.stopPropagation();
              onChange(row.value);
              setOpen(false);
            }}
          >
            {row.label}
          </button>
        ))}
      </div>
    </div>
  );
}

export function SecuritySettingsView() {
  const toast = useToast();
  const copySsoValue = async (value: string) => {
    try {
      await navigator.clipboard.writeText(value);
      toast('Copied', 'success');
    } catch {
      toast('Select the value and copy it', 'info');
    }
  };
  const me = useCurrentUser();
  const [tab, setTab] = useHashTab(TABS, 'login');
  const [settings, setSettings] = useState<SecuritySettings | null>(null);
  const [restrict, setRestrict] = useState(false);
  const [methods, setMethods] = useState<LoginMethods>(ALL_METHODS_ON);
  const [enforce2fa, setEnforce2fa] = useState(false);
  const [limitToAccount, setLimitToAccount] = useState(false);
  const [employeeAccess, setEmployeeAccess] = useState(true);
  const [sso, setSso] = useState<SecuritySso>({
    loginUrl: null,
    issuer: null,
    certificate: null,
    acsUrl: '',
    entityId: '',
  });
  const [loginOpen, setLoginOpen] = useState(true);
  const [employeeOpen, setEmployeeOpen] = useState(true);
  const [confirm, setConfirm] = useState<{ key: ConfirmKey; next: boolean } | null>(null);
  const [ssoOpen, setSsoOpen] = useState(false);
  const [ssoDraft, setSsoDraft] = useState({ loginUrl: '', issuer: '', certificate: '' });
  const [ssoErrors, setSsoErrors] = useState({
    loginUrl: false,
    issuer: false,
    certificate: false,
  });
  const [manage, setManage] = useState<ManageKind | null>(null);
  const [manageStep, setManageStep] = useState(1);
  const [search, setSearch] = useState('');
  const [seatFilter, setSeatFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [selected, setSelected] = useState<string[]>([]);

  const applySettings = useCallback((next: SecuritySettings) => {
    setSettings(next);
    setRestrict(next.restrictLoginMethods);
    // Checked boxes are the login-page source of truth — always show stored flags.
    setMethods(next.loginMethods);
    setEnforce2fa(next.enforce2fa);
    setLimitToAccount(next.limitToAccount);
    setEmployeeAccess(next.employeeAccess);
    setSso(next.sso);
  }, []);

  useEffect(() => {
    let cancelled = false;
    getSecuritySettings()
      .then((row) => {
        if (!cancelled) applySettings(row);
      })
      .catch((error) => {
        if (!cancelled) toast(errorText(error), 'danger');
      });
    return () => {
      cancelled = true;
    };
  }, [applySettings, toast]);

  const saveLogin = useCallback(async () => {
    if (!DYNAMIC_METHODS.some((key) => methods[key])) {
      toast('Keep at least one login method enabled', 'info');
      return false;
    }
    // Restrict is on whenever anything is unchecked; off only when every method is allowed.
    const allOn = DYNAMIC_METHODS.every((key) => methods[key]);
    const nextRestrict = restrict || !allOn;
    try {
      const saved = await updateSecuritySettings({
        restrictLoginMethods: nextRestrict,
        loginMethods: {
          ...methods,
          apple: false,
          microsoft: false,
        },
        sso: {
          loginUrl: sso.loginUrl,
          issuer: sso.issuer,
          certificate: sso.certificate,
        },
        enforce2fa,
        limitToAccount,
        employeeAccess,
      });
      applySettings(saved);
    } catch (error) {
      toast(errorText(error), 'danger');
      return false;
    }
  }, [applySettings, employeeAccess, enforce2fa, limitToAccount, methods, restrict, sso, toast]);

  const openConfirm = (
    key: ConfirmKey,
    next: boolean,
    event: React.ChangeEvent<HTMLInputElement>,
  ) => {
    event.stopPropagation();
    setConfirm({ key, next });
  };

  const applyConfirm = () => {
    if (!confirm) return;
    if (confirm.key === '2fa') setEnforce2fa(confirm.next);
    if (confirm.key === 'account-limit') setLimitToAccount(confirm.next);
    if (confirm.key === 'employee-access') setEmployeeAccess(confirm.next);
    setConfirm(null);
    markLoginFormDirty();
    toast('Change ready — click Save to apply', 'info');
  };

  const toggleMaster = (next: boolean, event: React.ChangeEvent<HTMLInputElement>) => {
    event.stopPropagation();
    setRestrict(next);
    // Off = every method allowed on login; on = start fresh so only what you check stays.
    setMethods(next ? RESTRICTED_METHODS_START : ALL_METHODS_ON);
    if (next) setLoginOpen(true);
    markLoginFormDirty();
  };

  const toggleMethod = (key: LoginMethod, next: boolean) => {
    if (key === 'apple' || key === 'microsoft') return;
    const upcoming = { ...methods, [key]: next };
    if (!DYNAMIC_METHODS.some((method) => upcoming[method])) {
      toast('Keep at least one login method enabled', 'info');
      return;
    }
    setMethods(upcoming);
    // Unchecking anything turns restrictions on so the login page matches the boxes.
    if (!next) setRestrict(true);
    markLoginFormDirty();
  };

  const users = settings?.users ?? [];
  const eligible = useMemo(() => {
    if (!manage) return [];
    return users.filter((row) => {
      if (manage === '2fa') return !row.twoFactorEnabled;
      if (manage === 'admins') return row.isAdmin;
      return row.inactive;
    });
  }, [manage, users]);

  const visibleUsers = useMemo(() => {
    const q = search.trim().toLowerCase();
    return eligible.filter((row) => {
      const match =
        (!q || `${row.name} ${row.email}`.toLowerCase().includes(q)) &&
        (!seatFilter || row.seatLabel === seatFilter) &&
        (!typeFilter || row.userType === typeFilter);
      return match;
    });
  }, [eligible, search, seatFilter, typeFilter]);

  const adminCount = users.filter((row) => row.isAdmin).length;
  const selectedUsers = visibleUsers.filter((row) => selected.includes(row.id));
  const canSelect = (row: SecurityUser) => {
    if (manage === 'admins') {
      if (row.id === me.user.id) return false;
      if (adminCount <= 1) return false;
    }
    if (manage === 'inactive' && row.id === me.user.id) return false;
    return true;
  };

  const openManage = (kind: ManageKind) => {
    setManage(kind);
    setManageStep(1);
    setSearch('');
    setSeatFilter('');
    setTypeFilter('');
    setSelected([]);
  };

  const manageConfig = {
    '2fa': {
      title: 'Manage users without 2FA',
      heading: 'Remind users to set up two-factor authentication (2FA)',
      description: `There are ${settings?.risks.with2fa ?? 0} users out of ${settings?.risks.totalUsers ?? 0} that log in using 2FA on your account. To reduce risk, we recommend sending email reminders to at least 1 user to request they set up 2FA.`,
      reviewTitle: 'Review and send email',
      reviewCopy: 'Send a reminder to selected users to set up 2FA.',
      action: 'Send',
    },
    admins: {
      title: 'Manage Super Admin access',
      heading: 'Remove super admins',
      description: `Choose users to remove their Super Admin access. There ${people(settings?.risks.superAdmins ?? 0, 'is', 'are')} ${settings?.risks.superAdmins ?? 0} Super Admin${(settings?.risks.superAdmins ?? 0) === 1 ? '' : 's'} out of ${settings?.risks.totalUsers ?? 0} users in your account.`,
      reviewTitle: 'Review Super Admin changes',
      reviewCopy: 'Review the selected users whose Super Admin access will be changed.',
      action: 'Save',
    },
    inactive: {
      title: 'Manage inactive users',
      heading: 'Review inactive users',
      description: 'Choose inactive users to review or remove from account access.',
      reviewTitle: 'Review inactive users',
      reviewCopy: 'Review the selected inactive users before continuing.',
      action: 'Save',
    },
  } as const;

  const finishManage = async () => {
    if (!manage) return;
    const ids = selectedUsers.map((row) => row.id);
    try {
      if (manage === '2fa') await remindSecurity2fa(ids);
      if (manage === 'admins') await demoteSecurityAdmins(ids);
      if (manage === 'inactive') await deactivateSecurityUsers(ids);
      const next = await getSecuritySettings();
      applySettings(next);
      toast(
        `${manageConfig[manage].action} completed for ${ids.length} user${ids.length === 1 ? '' : 's'}`,
      );
      setManage(null);
    } catch (error) {
      toast(errorText(error), 'danger');
    }
  };

  const saveSso = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const loginUrl = ssoDraft.loginUrl.trim();
    const issuer = ssoDraft.issuer.trim();
    const certificate = ssoDraft.certificate.trim();
    const urlValid = /^https:\/\/.+/i.test(loginUrl);
    const errors = {
      loginUrl: !urlValid,
      issuer: !issuer,
      certificate: !certificate,
    };
    setSsoErrors(errors);
    if (errors.loginUrl || errors.issuer || errors.certificate) return;
    try {
      const saved = await updateSecuritySettings({
        sso: { loginUrl, issuer, certificate },
      });
      applySettings(saved);
      setSsoOpen(false);
      toast('SSO configuration saved', 'success');
    } catch (error) {
      toast(errorText(error), 'danger');
    }
  };

  const risks = settings?.risks;
  const confirmCopy = confirm
    ? confirm.key === 'employee-access' && confirm.next
      ? {
          title: 'Allow HubSpot employees to access this account?',
          text: 'HubSpot employees can access your account to help with technical support and usage questions. This doesn’t limit access to all account data.',
        }
      : confirm.key === '2fa' && !confirm.next
        ? {
            title: 'Stop requiring 2FA for login?',
            text: 'Users will no longer be required to use two-factor authentication when they log in.',
          }
        : confirm.key === 'account-limit' && !confirm.next
          ? {
              title: 'Allow users to join other accounts?',
              text: 'Users on this account will be able to be added to additional accounts in the future.',
            }
          : CONFIRM_COPY[confirm.key]
    : null;
  const confirmDanger = confirm?.key === 'employee-access' && !confirm.next;

  return (
    <div className="security-page">
      <SettingsFormsProvider>
        <header className="set-head">
          <div>
            <h1 className="set-head__title">Security</h1>
          </div>
        </header>
        <SetTabs label="Security settings" tabs={TABS} active={tab} onSelect={setTab} boxed />

        <TabPanel id="login" active={tab}>
          <SettingsForm
            id="security-login-form"
            onSave={saveLogin}
            onReset={() => settings && applySettings(settings)}
          >
            <p className="security-intro">Manage how users access your account.</p>
            <section className="security-group">
              <h2 className="security-group__title">Account login preferences</h2>
              <article
                className={cn(
                  'security-setting-card security-setting-card--accordion',
                  loginOpen && 'is-expanded',
                )}
              >
                <div className="security-setting-card__body">
                  <button
                    type="button"
                    className="security-accordion-trigger"
                    aria-expanded={loginOpen}
                    onClick={() => setLoginOpen((open) => !open)}
                  >
                    <svg
                      className="security-accordion-chevron"
                      viewBox="0 0 24 24"
                      fill="none"
                      aria-hidden="true"
                    >
                      <path
                        d="m9 18 6-6-6-6"
                        stroke="currentColor"
                        strokeWidth="1.8"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                    <span>Allowed login methods</span>
                  </button>
                  <div className="security-accordion-panel" hidden={!loginOpen}>
                    <p>
                      Checked methods are shown to every visitor on the login page (same options for
                      all users). Uncheck anything you do not want them to see, then Save. If you
                      set up SAML Single Sign-On, users will need to use SAML to log in.
                    </p>
                    <div className="security-login-methods">
                      {LOGIN_METHOD_FIELDS.map((row) => {
                        const locked = !!row.static;
                        const checked = locked ? false : methods[row.key];
                        return (
                          <label key={row.key} title={locked ? 'Coming soon' : undefined}>
                            <input
                              type="checkbox"
                              name={row.name}
                              checked={checked}
                              disabled={locked}
                              onChange={(event) => toggleMethod(row.key, event.target.checked)}
                            />{' '}
                            {row.label}
                            {locked ? (
                              <span className="security-method-soon"> Coming soon</span>
                            ) : null}
                          </label>
                        );
                      })}
                    </div>
                  </div>
                </div>
                <CardSwitch
                  name="restrict_login_methods"
                  checked={restrict}
                  label="Enable allowed login method restrictions"
                  onChange={toggleMaster}
                />
              </article>
              {/* SSO is hidden (product decision, Settings audit): no Configure card. The saved
                  configuration and its drawer stay for when it comes back. */}
            </section>

            <section className="security-group">
              <h2 className="security-group__title">Account 2FA preferences</h2>
              <article className="security-setting-card">
                <div className="security-setting-card__body">
                  <h3>Enforce 2FA to log in</h3>
                  <p>Enforce Two-factor authentication to all users when they log in.</p>
                </div>
                <CardSwitch
                  name="enforce_2fa"
                  checked={enforce2fa}
                  label="Enforce two-factor authentication"
                  onChange={(next, event) => openConfirm('2fa', next, event)}
                />
              </article>
            </section>

            <section className="security-group">
              <h2 className="security-group__title">Account restrictions</h2>
              <article className="security-setting-card">
                <div className="security-setting-card__body">
                  <h3>Limit users to only this account</h3>
                  <p>
                    Users on this account will not be able to be added to additional accounts in the
                    future.
                  </p>
                </div>
                <CardSwitch
                  name="limit_to_account"
                  checked={limitToAccount}
                  label="Limit users to this account"
                  onChange={(next, event) => openConfirm('account-limit', next, event)}
                />
              </article>
              <article
                className={cn(
                  'security-setting-card security-setting-card--accordion',
                  employeeOpen && 'is-expanded',
                )}
              >
                <div className="security-setting-card__body">
                  <button
                    type="button"
                    className="security-accordion-trigger"
                    aria-expanded={employeeOpen}
                    onClick={() => setEmployeeOpen((open) => !open)}
                  >
                    <svg
                      className="security-accordion-chevron"
                      viewBox="0 0 24 24"
                      fill="none"
                      aria-hidden="true"
                    >
                      <path
                        d="m9 18 6-6-6-6"
                        stroke="currentColor"
                        strokeWidth="1.8"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                    <span>Allow access to HubSpot employees</span>
                  </button>
                  <div className="security-accordion-panel" hidden={!employeeOpen}>
                    <p>
                      HubSpot employees can access your account to help with technical support and
                      usage questions. This doesn’t limit access to all account data.
                    </p>
                    <a
                      href="#"
                      className="security-history-link"
                      onClick={(event) => {
                        event.preventDefault();
                        const rows = [
                          ['User', 'Accessed at', 'Reason'],
                          ...(settings?.employeeAccessHistory ?? []).map((row) => [
                            row.user,
                            row.accessedAt,
                            row.reason,
                          ]),
                        ];
                        downloadCsv('employee-access-history.csv', rows);
                      }}
                    >
                      Download employee access history
                    </a>
                  </div>
                </div>
                <CardSwitch
                  name="employee_access"
                  checked={employeeAccess}
                  label="Allow employee access"
                  onChange={(next, event) => openConfirm('employee-access', next, event)}
                />
              </article>
            </section>
          </SettingsForm>
        </TabPanel>

        <TabPanel id="permissions" active={tab}>
          <p className="security-intro">Monitor and manage user permissions to reduce risk.</p>
          <div className="security-risk-list">
            <article className="security-risk-card">
              <span
                className={cn(
                  'security-risk-icon',
                  (risks?.without2fa ?? 0) > 0
                    ? 'security-risk-icon--danger'
                    : 'security-risk-icon--success',
                )}
                aria-hidden="true"
              >
                {(risks?.without2fa ?? 0) > 0 ? (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                    <circle cx="12" cy="12" r="9" />
                    <path d="M12 7v6m0 4h.01" />
                  </svg>
                ) : (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                    <path d="m5 12 4 4L19 6" />
                  </svg>
                )}
              </span>
              <div className="security-risk-copy">
                <h2>
                  {(risks?.without2fa ?? 0) === 0
                    ? 'All users are enrolled in two-factor authentication (2FA)'
                    : (risks?.without2fa ?? 0) === 1
                      ? '1 user is not enrolled in two-factor authentication (2FA)'
                      : `${risks?.without2fa} users are not enrolled in two-factor authentication (2FA)`}
                </h2>
                <p>
                  Remind users to set up 2FA. At least 1 user should sign in with 2FA to reduce
                  unauthorized access to your account.
                </p>
              </div>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => openManage('2fa')}
              >
                Manage
              </button>
            </article>
            <article className="security-risk-card">
              <span className="security-risk-icon security-risk-icon--info" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <circle cx="12" cy="12" r="9" />
                  <path d="M12 11v5M12 8h.01" />
                </svg>
              </span>
              <div className="security-risk-copy">
                <h2>
                  {(risks?.criticalPermissions ?? 0) === 0
                    ? 'No users with critical permissions'
                    : (risks?.criticalPermissions ?? 0) === 1
                      ? '1 user with critical permissions'
                      : `${risks?.criticalPermissions} users with critical permissions`}
                </h2>
                <p>
                  Reducing the number of users with powerful, high-risk permissions helps keep your
                  account safe.
                </p>
              </div>
            </article>
            <article className="security-risk-card">
              <span className="security-risk-icon security-risk-icon--success" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <path d="m5 12 4 4L19 6" />
                </svg>
              </span>
              <div className="security-risk-copy">
                <h2>
                  {(risks?.superAdmins ?? 0) === 0
                    ? 'No Super Admins in your account'
                    : (risks?.superAdmins ?? 0) === 1
                      ? '1 Super Admin in your account'
                      : `${risks?.superAdmins} Super Admins in your account`}
                </h2>
                <p>
                  Limiting admins to fewer than 1 helps prevent unnecessary distribution of access
                  and reduces risk.
                </p>
              </div>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => openManage('admins')}
              >
                Manage
              </button>
            </article>
            <article className="security-risk-card">
              <span className="security-risk-icon security-risk-icon--success" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <path d="m5 12 4 4L19 6" />
                </svg>
              </span>
              <div className="security-risk-copy">
                <h2>
                  {(risks?.partnerSuperAdmins ?? 0) === 0
                    ? 'No partner users with Super Admin access'
                    : `${risks?.partnerSuperAdmins} partner users with Super Admin access`}
                </h2>
                <p>
                  Minimizing the number of partners with Super Admin access boosts your
                  account&apos;s security and reduces access risk.
                </p>
              </div>
            </article>
            <article className="security-risk-card">
              <span
                className={cn(
                  'security-risk-icon',
                  (risks?.inactive ?? 0) > 0
                    ? 'security-risk-icon--danger'
                    : 'security-risk-icon--success',
                )}
                aria-hidden="true"
              >
                {(risks?.inactive ?? 0) > 0 ? (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                    <circle cx="12" cy="12" r="9" />
                    <path d="M12 7v6m0 4h.01" />
                  </svg>
                ) : (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
                    <path d="m5 12 4 4L19 6" />
                  </svg>
                )}
              </span>
              <div className="security-risk-copy">
                <h2>
                  {(risks?.inactive ?? 0) === 0
                    ? 'No inactive users in your account'
                    : (risks?.inactive ?? 0) === 1
                      ? '1 inactive user in your account'
                      : `${risks?.inactive} inactive users in your account`}
                </h2>
                <p>
                  Keeping inactive users to a minimum ensures that your account is only accessed by
                  current users.
                </p>
              </div>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => openManage('inactive')}
              >
                Manage <span aria-hidden="true">↗</span>
              </button>
            </article>
          </div>
        </TabPanel>
      </SettingsFormsProvider>

      <SetDialog
        open={!!confirm}
        onClose={() => setConfirm(null)}
        labelledBy="security-confirm-title"
        className="security-confirm-modal"
      >
        <DialogHead
          id="security-confirm-title"
          title={confirmCopy?.title ?? 'Confirm security setting'}
          onClose={() => setConfirm(null)}
        />
        <div className="set-modal__body">
          <p>{confirmCopy?.text}</p>
        </div>
        <div className="set-modal__foot">
          <button
            type="button"
            className={cn('btn-crm btn-crm--primary', confirmDanger && 'security-confirm-danger')}
            onClick={applyConfirm}
          >
            Yes
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            data-security-confirm-no
            onClick={() => setConfirm(null)}
          >
            No
          </button>
        </div>
      </SetDialog>

      <SetDialog
        open={ssoOpen}
        onClose={() => setSsoOpen(false)}
        drawer
        labelledBy="security-sso-title"
        className="security-sso-drawer"
      >
        <form className="set-drawer__form" onSubmit={saveSso} noValidate>
          <div className="set-drawer__head">
            <h2 className="set-modal__title" id="security-sso-title">
              Configure single sign-on (SSO)
            </h2>
            <button
              type="button"
              className="icon-btn icon-btn--ghost"
              aria-label="Close"
              onClick={() => setSsoOpen(false)}
            >
              <svg
                viewBox="0 0 24 24"
                className="icon iconSize-20"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
              >
                <path d="m6 6 12 12M18 6 6 18" />
              </svg>
            </button>
          </div>
          <div className="set-drawer__body">
            <p className="field__help crm-mb-4">
              Connect your identity provider so users can sign in with your organization&apos;s
              credentials. Copy these CRM values into Okta, Google, or Azure first.
            </p>
            <div className="field">
              <label className="field__label" htmlFor="security-sso-acs">
                Sign-on URL (ACS)
              </label>
              <div className="security-sso-copy">
                <input
                  className="input"
                  id="security-sso-acs"
                  readOnly
                  value={sso.acsUrl}
                  onFocus={(event) => event.currentTarget.select()}
                />
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => void copySsoValue(sso.acsUrl)}
                >
                  Copy
                </button>
              </div>
            </div>
            <div className="field crm-mt-4">
              <label className="field__label" htmlFor="security-sso-entity">
                Audience URI (Service Provider Entity ID)
              </label>
              <div className="security-sso-copy">
                <input
                  className="input"
                  id="security-sso-entity"
                  readOnly
                  value={sso.entityId}
                  onFocus={(event) => event.currentTarget.select()}
                />
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => void copySsoValue(sso.entityId)}
                >
                  Copy
                </button>
              </div>
            </div>
            <div className={cn('field crm-mt-4', ssoErrors.loginUrl && 'is-invalid')}>
              <label className="field__label" htmlFor="security-sso-url">
                Identity provider login URL
              </label>
              <input
                className="input"
                id="security-sso-url"
                type="url"
                placeholder="https://login.yourcompany.com/saml"
                value={ssoDraft.loginUrl}
                onChange={(event) => {
                  setSsoDraft((row) => ({ ...row, loginUrl: event.target.value }));
                  setSsoErrors((row) => ({ ...row, loginUrl: false }));
                }}
                required
              />
              <p className="field__error">Enter a valid HTTPS login URL.</p>
            </div>
            <div className={cn('field crm-mt-4', ssoErrors.issuer && 'is-invalid')}>
              <label className="field__label" htmlFor="security-sso-issuer">
                Identity provider identifier (issuer)
              </label>
              <input
                className="input"
                id="security-sso-issuer"
                placeholder="urn:yourcompany:crm"
                value={ssoDraft.issuer}
                onChange={(event) => {
                  setSsoDraft((row) => ({ ...row, issuer: event.target.value }));
                  setSsoErrors((row) => ({ ...row, issuer: false }));
                }}
                required
              />
              <p className="field__error">Enter the issuer identifier.</p>
            </div>
            <div className={cn('field crm-mt-4', ssoErrors.certificate && 'is-invalid')}>
              <label className="field__label" htmlFor="security-sso-cert">
                X.509 certificate
              </label>
              <textarea
                className="input"
                id="security-sso-cert"
                rows={5}
                placeholder="-----BEGIN CERTIFICATE-----"
                value={ssoDraft.certificate}
                onChange={(event) => {
                  setSsoDraft((row) => ({ ...row, certificate: event.target.value }));
                  setSsoErrors((row) => ({ ...row, certificate: false }));
                }}
                required
              />
              <p className="field__error">Paste the identity provider certificate.</p>
            </div>
          </div>
          <div className="set-drawer__foot">
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setSsoOpen(false)}
            >
              Cancel
            </button>
            <button type="submit" className="btn-crm btn-crm--primary">
              Save configuration
            </button>
          </div>
        </form>
      </SetDialog>

      <SetDialog
        open={!!manage}
        onClose={() => setManage(null)}
        drawer
        labelledBy="security-manage-title"
        className="security-manage-drawer"
      >
        {manage ? (
          <form className="set-drawer__form" onSubmit={(event) => event.preventDefault()}>
            <div className="set-drawer__head">
              <h2 className="set-modal__title" id="security-manage-title">
                {manageConfig[manage].title}
              </h2>
              <button
                type="button"
                className="icon-btn icon-btn--ghost"
                aria-label="Close"
                onClick={() => setManage(null)}
              >
                <svg
                  viewBox="0 0 24 24"
                  className="icon iconSize-20"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                >
                  <path d="m6 6 12 12M18 6 6 18" />
                </svg>
              </button>
            </div>
            <div className="set-drawer__body">
              <ol className="security-stepper" aria-label="Progress">
                <li className={cn(manageStep === 1 && 'is-active', manageStep > 1 && 'is-done')}>
                  <span />
                  <small>CHOOSE USERS</small>
                </li>
                <li className={cn(manageStep === 2 && 'is-active')}>
                  <span />
                  <small>REVIEW</small>
                </li>
              </ol>
              {manageStep === 1 ? (
                <section>
                  <h3>{manageConfig[manage].heading}</h3>
                  <p className="field__help">{manageConfig[manage].description}</p>
                  <div className="security-user-toolbar">
                    <input
                      className="input"
                      type="search"
                      placeholder="Search for a user"
                      aria-label="Search users"
                      value={search}
                      onChange={(event) => setSearch(event.target.value)}
                    />
                    <FilterMenu
                      kind="seat"
                      value={seatFilter}
                      options={SEAT_FILTERS}
                      onChange={setSeatFilter}
                    />
                    <FilterMenu
                      kind="type"
                      value={typeFilter}
                      options={TYPE_FILTERS}
                      onChange={setTypeFilter}
                    />
                  </div>
                  <div className="security-user-table">
                    <div className="security-user-table__head">
                      <label className="security-user-select-all">
                        <input
                          type="checkbox"
                          aria-label="Select all users"
                          checked={
                            visibleUsers.filter(canSelect).length > 0 &&
                            visibleUsers.filter(canSelect).every((row) => selected.includes(row.id))
                          }
                          onChange={(event) => {
                            const ids = visibleUsers.filter(canSelect).map((row) => row.id);
                            setSelected(event.target.checked ? ids : []);
                          }}
                        />
                      </label>
                      <span className="security-user-table__user-heading">
                        User <span aria-hidden="true">↑</span>
                      </span>
                      <span>
                        Seat <span aria-hidden="true">↕</span>
                      </span>
                      <span>
                        User type <span aria-hidden="true">↕</span>
                      </span>
                    </div>
                    {visibleUsers.map((row) => (
                      <label key={row.id} className="security-user-row">
                        <input
                          type="checkbox"
                          checked={selected.includes(row.id)}
                          disabled={!canSelect(row)}
                          onChange={(event) => {
                            setSelected((current) =>
                              event.target.checked
                                ? [...current, row.id]
                                : current.filter((id) => id !== row.id),
                            );
                          }}
                        />
                        <span className="security-user-avatar">
                          {row.name.slice(0, 1).toUpperCase()}
                        </span>
                        <span className="security-user-name">
                          <strong>{row.name}</strong>
                          <small>{row.email}</small>
                        </span>
                        <span className="security-user-seat">{row.seatLabel}</span>
                        <span className="security-user-type">{row.userType}</span>
                      </label>
                    ))}
                  </div>
                  {visibleUsers.length === 0 ? (
                    <p className="security-no-users">No users match these filters.</p>
                  ) : null}
                </section>
              ) : (
                <section>
                  <h3>{manageConfig[manage].reviewTitle}</h3>
                  <p className="field__help">
                    {manageConfig[manage].reviewCopy} {selectedUsers.length} user
                    {selectedUsers.length === 1 ? '' : 's'} selected.
                  </p>
                  <div className="security-review-list">
                    {selectedUsers.map((row) => (
                      <div key={row.id} className="security-review-user">
                        <span className="security-user-avatar">
                          {row.name.slice(0, 1).toUpperCase()}
                        </span>
                        <div className="security-review-user__details">
                          <strong>{row.name}</strong>
                          <span>{row.email}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </section>
              )}
            </div>
            <div className="set-drawer__foot">
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                hidden={manageStep === 1}
                onClick={() => setManageStep(1)}
              >
                Back
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline"
                hidden={manageStep === 2}
                onClick={() => setManage(null)}
              >
                Cancel
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                disabled={manageStep === 1 && selectedUsers.filter(canSelect).length === 0}
                onClick={() => {
                  if (manageStep === 1) {
                    if (selectedUsers.length === 0) return;
                    setManageStep(2);
                    return;
                  }
                  void finishManage();
                }}
              >
                {manageStep === 1 ? 'Next' : manageConfig[manage].action}
              </button>
            </div>
          </form>
        ) : null}
      </SetDialog>
    </div>
  );
}
