'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  listActivityAssociationRules,
  listActivityObjects,
  setActivityAssociationRule,
  type ActivityLogMode,
  type ActivityObject,
} from '@/features/data-model/api.client';
import { DmIcon } from '@/features/data-model/ui/icons';
import {
  getExtensionAdminSettings,
  updateExtensionAdminSettings,
} from '@/features/extension/api.client';
import { getBusinessSettings, updateBusinessSettings } from '@/features/settings/api.client';
import type { BusinessSettings } from '@/features/settings/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  ACTIVITY_TABS,
  dataModelHref,
  settingsHref,
  type ActivityTab,
  type OsObject,
} from './config';
import { CheckRow, OsDropdown, RadioRow, Soon, Tip } from './primitives';

/** The API's limits (MAX_EMAIL_DAILY_LIMIT / MAX_EMAIL_HOURLY_LIMIT). */
const DAILY_MAX = 100_000;
const HOURLY_MAX = 10_000;

/** Used until GET /activity-objects answers (or when it fails). */
const FALLBACK_TYPES: ActType[] = [
  { key: 'call', label: 'Calls' },
  { key: 'communication', label: 'Communications' },
  { key: 'email', label: 'Emails' },
  { key: 'meeting', label: 'Meetings' },
  { key: 'note', label: 'Notes' },
  { key: 'postal_mail', label: 'Postal Mail' },
  { key: 'task', label: 'Tasks' },
];

interface Draft {
  trackingEnabled: boolean;
  daily: string;
  hourly: string;
  /** Apply the account Log default to every Sales extension user. */
  enforceLog: boolean;
  /** Apply the account Track default to every Sales extension user. */
  enforceTrack: boolean;
}

const draftOf = (
  s: BusinessSettings,
  locks: { enforceLog: boolean; enforceTrack: boolean } = {
    enforceLog: false,
    enforceTrack: false,
  },
): Draft => ({
  trackingEnabled: s.trackingEnabled,
  daily: s.emailDailyLimit.toLocaleString(),
  hourly: s.emailHourlyLimit.toLocaleString(),
  enforceLog: locks.enforceLog,
  enforceTrack: locks.enforceTrack,
});

const parseCount = (text: string) => Number(text.replace(/[,\s]/g, ''));
const countError = (text: string, max: number) => {
  const n = parseCount(text);
  return Number.isInteger(n) && n >= 1 && n <= max
    ? null
    : `Enter a number between 1 and ${max.toLocaleString()}.`;
};

/**
 * Activities settings: Email Log & Track | Email Frequency Controls | Associations. Email
 * tracking and the send limits save to the business settings (PATCH /business/settings). The
 * Sales extension Log and Track locks save on the extension admin settings. The other rows stay
 * marked "Coming soon".
 */
export function ActivitiesSettings({
  tab: rawTab,
  subject: rawSubject,
  type: rawType,
  objects,
  canManage,
}: {
  tab: string | null;
  subject: string | null;
  type: string | null;
  objects: OsObject[];
  canManage: boolean;
}) {
  const toast = useToast();
  const tab: ActivityTab = ACTIVITY_TABS.some(([k]) => k === rawTab)
    ? (rawTab as ActivityTab)
    : 'email';

  const [settings, setSettings] = useState<BusinessSettings | null>(null);
  const [savedLocks, setSavedLocks] = useState({ enforceLog: false, enforceTrack: false });
  const [draft, setDraft] = useState<Draft | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    Promise.all([
      getBusinessSettings(),
      canManage ? getExtensionAdminSettings() : Promise.resolve(null),
    ]).then(
      ([s, admin]) => {
        const locks = {
          enforceLog: admin?.enforceLogDefault ?? false,
          enforceTrack: admin?.enforceTrackDefault ?? false,
        };
        setSettings(s);
        setSavedLocks(locks);
        setDraft(draftOf(s, locks));
      },
      (err: unknown) => setLoadError(errorText(err)),
    );
  }, [canManage]);

  const saved = settings ? draftOf(settings, savedLocks) : null;
  const dirty =
    Boolean(draft && saved) &&
    (draft!.trackingEnabled !== saved!.trackingEnabled ||
      draft!.enforceLog !== saved!.enforceLog ||
      draft!.enforceTrack !== saved!.enforceTrack ||
      parseCount(draft!.daily) !== parseCount(saved!.daily) ||
      parseCount(draft!.hourly) !== parseCount(saved!.hourly));
  const dailyError = draft ? countError(draft.daily, DAILY_MAX) : null;
  const hourlyError = draft ? countError(draft.hourly, HOURLY_MAX) : null;

  const save = async () => {
    if (!draft || !settings || dailyError || hourlyError) return;
    setSaving(true);
    try {
      const next = await updateBusinessSettings({
        trackingEnabled: draft.trackingEnabled,
        emailDailyLimit: parseCount(draft.daily),
        emailHourlyLimit: parseCount(draft.hourly),
        updatedAt: settings.updatedAt,
      });
      const admin = canManage
        ? await updateExtensionAdminSettings({
            enforceLogDefault: draft.enforceLog,
            enforceTrackDefault: draft.enforceTrack,
          })
        : null;
      const locks = {
        enforceLog: admin?.enforceLogDefault ?? draft.enforceLog,
        enforceTrack: admin?.enforceTrackDefault ?? draft.enforceTrack,
      };
      setSettings(next);
      setSavedLocks(locks);
      setDraft(draftOf(next, locks));
      toast('Settings saved.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <div className="os-tabbar">
        <nav className="os-tabs" aria-label="Activities settings">
          {ACTIVITY_TABS.map(([key, label]) => (
            <Link
              key={key}
              className={cn('os-tab', key === tab && 'is-active')}
              href={settingsHref('activities', key === 'email' ? undefined : key)}
              aria-current={key === tab ? 'page' : undefined}
            >
              {label}
            </Link>
          ))}
        </nav>
        <Link
          className="os-viewlink"
          href={dataModelHref()}
          title="View activities in the data model"
        >
          <span>View activities in the data model</span>
          <DmIcon name="external" size={14} />
        </Link>
      </div>

      {loadError && tab !== 'associations' ? (
        <p className="os-num-field__err os-gap-sm">{loadError}</p>
      ) : null}

      {tab === 'email' ? (
        <EmailTab
          draft={draft}
          canManage={canManage}
          onChange={(d) => setDraft((cur) => (cur ? { ...cur, ...d } : cur))}
        />
      ) : tab === 'frequency' ? (
        <section className="os-panel os-act" aria-label="Email Frequency Controls">
          <p className="os-intro os-intro--rule">
            These settings apply to all users sending one-to-one and sequences emails through their{' '}
            <Link className="os-link" href="/settings/email-provider">
              connected email accounts <DmIcon name="external" size={14} />
            </Link>
          </p>
          <h2 className="os-h2">Send limits</h2>
          <p className="os-sub">
            Configure limits on how many emails are sent through each connected account
          </p>
          <NumField
            label="Maximum sends per 24 hours*"
            tip={`Between 1 and ${DAILY_MAX.toLocaleString()} emails in a rolling 24 hours.`}
            help="Reduce the number of emails sent within 24 hours"
            value={draft?.daily ?? ''}
            error={dailyError}
            disabled={!draft || !canManage}
            onChange={(daily) => setDraft((cur) => (cur ? { ...cur, daily } : cur))}
          />
          <NumField
            label="Maximum sends per hour*"
            tip={`Between 1 and ${HOURLY_MAX.toLocaleString()} emails per hour.`}
            help="Limit the number of emails that can be sent per hour"
            value={draft?.hourly ?? ''}
            error={hourlyError}
            disabled={!draft || !canManage}
            onChange={(hourly) => setDraft((cur) => (cur ? { ...cur, hourly } : cur))}
          />
        </section>
      ) : (
        <AssociationsTab
          subject={rawSubject}
          type={rawType}
          objects={objects}
          canManage={canManage}
        />
      )}

      {dirty && tab !== 'associations' ? (
        <div className="os-savebar" role="region" aria-label="Unsaved changes">
          <span className="os-savebar__text">You have unsaved changes</span>
          <span className="os-savebar__btns">
            <button
              type="button"
              className={cn('btn-crm btn-crm--primary btn-crm--sm', saving && 'is-loading')}
              disabled={saving || Boolean(dailyError || hourlyError)}
              onClick={() => void save()}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              disabled={saving}
              onClick={() => saved && setDraft(saved)}
            >
              Cancel
            </button>
          </span>
        </div>
      ) : null}
    </>
  );
}

function EmailTab({
  draft,
  canManage,
  onChange,
}: {
  draft: Draft | null;
  canManage: boolean;
  onChange: (d: Partial<Draft>) => void;
}) {
  const [alertOpen, setAlertOpen] = useState(true);
  const [accOpen, setAccOpen] = useState(false);
  const tracking = draft?.trackingEnabled ?? false;

  return (
    <section className="os-panel os-act" aria-label="Email Log & Track">
      <p className="os-intro os-intro--rule">
        These settings are for everyone logging data in your account&apos;s CRM. To connect your
        email, go to your{' '}
        <Link className="os-link" href="/settings/email-provider">
          email preferences.
        </Link>
      </p>

      <h2 className="os-h2">Email log and track settings</h2>
      <p className="os-sub">Configure how emails are recorded in CRM</p>
      <CheckRow
        label={
          <>
            Allow all users to log email attachments <Soon />
          </>
        }
        help="When this setting is off it will prevent all incoming attachments from being logged in the CRM, conversations inbox, and sidebar."
        checked
        disabled
      />
      <CheckRow
        label="Apply Default Log setting for all users - Sales Extension Only"
        help="Turn this setting on to select a default log setting for all CRM Sales Extension users in the portal. This will override the individual's default log setting."
        checked={draft?.enforceLog ?? false}
        disabled={!draft || !canManage}
        onChange={(enforceLog) => onChange({ enforceLog })}
      />

      {tracking && alertOpen ? (
        <div className="os-alert" role="note">
          <button
            type="button"
            className="os-alert__x"
            aria-label="Dismiss"
            onClick={() => setAlertOpen(false)}
          >
            <DmIcon name="x" size={16} />
          </button>
          <p className="os-alert__title">Confirm consent before tracking emails</p>
          <p>
            Email open and click tracking may require prior recipient consent in some jurisdictions,
            including parts of the EU. Tracking is currently turned on. By leaving tracking on, you
            confirm that you are responsible for determining whether these requirements apply and
            that you have obtained any necessary recipient consent.
          </p>
        </div>
      ) : null}

      <CheckRow
        label="Allow all users to track emails and see recipients open and click on their emails"
        help="When this setting is off it will prevent all users from tracking emails sent from the CRM, conversations inbox, email extensions, and sequences. Tracking needs a tracking domain (Email provider settings)."
        checked={tracking}
        disabled={!draft || !canManage}
        onChange={(trackingEnabled) => onChange({ trackingEnabled })}
      />
      <CheckRow
        indent
        label="Apply Default Track setting for all users - Sales Extension Only"
        help="Turn this setting on to select default track setting for all CRM Sales Extension users in the portal. This will override the individual's default track setting."
        checked={draft?.enforceTrack ?? false}
        disabled={!draft || !canManage}
        onChange={(enforceTrack) => onChange({ enforceTrack })}
      />

      <h2 className="os-h2 os-h2--gap">
        Contact email logging rules <Soon />
      </h2>
      <p className="os-sub">
        Configure which incoming contact emails are logged to the CRM. This setting only applies to
        new emails.
      </p>
      <RadioRow name="os-logrule" checked={false} disabled>
        <span>
          <b>Log replies only</b>
          <small>
            Only logs emails from contacts that are part of an existing thread already logged to the
            CRM by a user.
          </small>
        </span>
      </RadioRow>
      <RadioRow name="os-logrule" checked disabled>
        <span>
          <b>
            Log all emails <span className="os-new">NEW</span>
          </b>
          <small>
            Logs all emails between known contacts in the CRM and users with connected emails.
          </small>
        </span>
      </RadioRow>

      <div className="os-acc">
        <button
          type="button"
          className={cn('os-acc__btn', accOpen && 'is-open')}
          aria-expanded={accOpen}
          onClick={() => setAccOpen((v) => !v)}
        >
          <DmIcon name="chevron-right" size={14} />
          Exchange &amp; IMAP settings
        </button>
        {accOpen ? (
          <div className="os-acc__body">
            <button type="button" className="os-link os-link--strong" disabled>
              Add IMAP settings
            </button>
            <p className="os-block__text">
              If your email server requires an IMAP connection, add your IMAP settings here to make
              it easy for other users to connect their inboxes.
            </p>
            <button type="button" className="os-link os-link--strong" disabled>
              Add Exchange settings
            </button>
            <p className="os-block__text">
              If your Exchange email or calendar server is on-premise, add your Exchange settings
              here to make it easy for other users to connect their accounts. <Soon />
            </p>
          </div>
        ) : null}
      </div>

      <h2 className="os-h2 os-h2--gap">
        Unsubscribe links <Soon />
      </h2>
      <p className="os-sub">
        Configure how unsubscribe links are used in emails sent from the CRM.
      </p>
      <CheckRow
        label="Apply the same unsubscribe link settings for all users"
        help="When this setting is off it will allow each user to set their own unsubscribe settings."
        checked={false}
        disabled
      />

      <h2 className="os-h2 os-h2--gap">
        Never Log <Soon />
      </h2>
      <p className="os-sub">
        The Never Log list ensures emails and meetings with specified domains or email addresses are
        not automatically logged to your CRM.
      </p>
      <div className="os-nl-bar">
        <label className="os-search">
          <input
            type="search"
            placeholder="Search emails or domains"
            aria-label="Search emails or domains"
            disabled
          />
          <DmIcon name="search" size={16} />
        </label>
        <span className="os-nl-view">
          View:{' '}
          <button type="button" className="os-nl-view__btn" disabled>
            Blocked for all users
            <DmIcon name="caret" size={14} />
          </button>
        </span>
      </div>
      <button type="button" className="btn-crm btn-crm--outline btn-crm--sm os-nl-add" disabled>
        Add emails or domains
      </button>
      <div className="os-table-wrap">
        <table className="os-table os-nl-table">
          <thead>
            <tr>
              <th>Domains and Email Addresses</th>
              <th className="os-nl-table__by">Blocked for</th>
            </tr>
          </thead>
        </table>
        <p className="os-noresults">No emails or domains on the Never Log list.</p>
      </div>

      <h2 className="os-h2 os-h2--gap">
        Manual logging <Soon />
      </h2>
      <p className="os-sub">
        Log outgoing and incoming emails manually by including these email addresses.
      </p>
      <div className="os-copy-field">
        <span className="os-copy-field__label">BCC Address (Outgoing)</span>
        <p className="os-copy-field__help">
          BCC this email address when you send an email to log outgoing emails in your CRM.
        </p>
      </div>
      <div className="os-copy-field">
        <span className="os-copy-field__label">Forwarding Address (Incoming)</span>
        <p className="os-copy-field__help">
          Forward emails to this address to log incoming emails in your CRM.
        </p>
      </div>
    </section>
  );
}

function NumField({
  label,
  tip,
  help,
  value,
  error,
  disabled,
  onChange,
}: {
  label: string;
  tip: string;
  help: string;
  value: string;
  error: string | null;
  disabled: boolean;
  onChange: (value: string) => void;
}) {
  return (
    <label className="os-num-field">
      <span className="os-num-field__label">
        {label} <Tip text={tip} />
      </span>
      <span className="os-num-field__help">{help}</span>
      <input
        className={cn('input', error && 'is-invalid')}
        type="text"
        inputMode="numeric"
        value={value}
        disabled={disabled}
        aria-invalid={Boolean(error)}
        onChange={(e) => onChange(e.target.value)}
      />
      {error ? <span className="os-num-field__err">{error}</span> : null}
    </label>
  );
}

/** An activity type in the Associations tab's picker: its key and plural label. */
interface ActType {
  key: string;
  label: string;
}

/** The log options, as in the design: label and help (HUB-226 D4). */
const LOG_OPTIONS: ReadonlyArray<readonly [ActivityLogMode, string, string]> = [
  ['none', 'None', ''],
  ['all', 'Log to all', 'Logging to all is limited to the 500 most recently associated records.'],
  ['one', 'Log to 1 most recently associated', ''],
  ['five', 'Log to 5 most recently associated', ''],
];

/** The API's defaults: deals get the 5 most recent open ones, the other objects none. */
const defaultMode = (target: string): ActivityLogMode => (target === 'deal' ? 'five' : 'none');

/**
 * Associations (HUB-226 D4): which associated records an activity logged on a record is also
 * logged on, per object and activity type (GET/PUT /activity-association-rules).
 */
function AssociationsTab({
  subject: rawSubject,
  type: rawType,
  objects,
  canManage,
}: {
  subject: string | null;
  type: string | null;
  objects: OsObject[];
  canManage: boolean;
}) {
  const [types, setTypes] = useState<ActType[]>(FALLBACK_TYPES);
  useEffect(() => {
    listActivityObjects().then(
      (list: ActivityObject[]) => {
        if (list.length) setTypes(list.map((t) => ({ key: t.key, label: t.pluralLabel })));
      },
      () => undefined,
    );
  }, []);

  const subjects = useMemo(
    () => objects.filter((o) => o.kind === 'builtIn' || o.kind === 'custom'),
    [objects],
  );
  const subject =
    subjects.find((o) => o.key === rawSubject) ??
    subjects.find((o) => o.key === 'company') ??
    subjects[0];
  // `type` is the activity's key; links made before it was keyed name its plural label.
  const type =
    types.find((t) => t.key === rawType || t.label.toLowerCase() === rawType) ?? types[0]!;
  const href = (s: string, t: ActType) =>
    settingsHref('activities', 'associations', { subject: s, type: t.key });
  if (!subject) return null;

  return (
    <section className="os-panel os-act" aria-label="Associations">
      <p className="os-intro">
        Configure the default experience when auto-associating activities to the relevant records.
        When an activity is associated based on the starting object type and the ending object type,
        the activity will appear in that record&apos;s activity timeline.
      </p>

      <div className="os-assoc-pick">
        <div className="os-assoc-pick__col">
          <span className="os-assoc-pick__label">
            Select an object{' '}
            <Tip text="The record the activity is logged on. Choose which associated records it is also logged to." />
          </span>
          <OsDropdown
            className="os-select os-select--sm"
            menuClassName="os-pop os-pop--objects"
            width={260}
            ariaLabel="Select an object"
            label={
              <>
                <span className="os-select__value">{subject.plural}</span>
                <DmIcon name="caret" size={18} />
              </>
            }
          >
            {(close) => (
              <div className="os-pop__list" role="listbox">
                {subjects.map((o) => (
                  <Link
                    key={o.key}
                    role="option"
                    aria-selected={o.key === subject.key}
                    className={cn('os-opt', o.key === subject.key && 'is-selected')}
                    href={href(o.key, type)}
                    onClick={close}
                  >
                    {o.plural}
                  </Link>
                ))}
              </div>
            )}
          </OsDropdown>
        </div>
        <div className="os-assoc-pick__col">
          <span className="os-assoc-pick__label">Select activity type</span>
          <OsDropdown
            className="os-select os-select--sm"
            width={220}
            ariaLabel="Select activity type"
            label={
              <>
                <span className="os-select__value">{type.label}</span>
                <DmIcon name="caret" size={18} />
              </>
            }
          >
            {(close) =>
              types.map((t) => (
                <Link
                  key={t.key}
                  role="option"
                  aria-selected={t.key === type.key}
                  className={cn('os-menu__item', t.key === type.key && 'is-selected')}
                  href={href(subject.key, t)}
                  onClick={close}
                >
                  {t.label}
                </Link>
              ))
            }
          </OsDropdown>
        </div>
      </div>

      <LogRules
        key={`${subject.key}:${type.key}`}
        subjectType={subject.key}
        type={type}
        targets={subjects}
        canManage={canManage}
      />
    </section>
  );
}

/** "Log activity": one object and activity type's settings, saved through the unsaved bar. */
function LogRules({
  subjectType,
  type,
  targets,
  canManage,
}: {
  subjectType: string;
  type: ActType;
  targets: OsObject[];
  canManage: boolean;
}) {
  const toast = useToast();
  const [saved, setSaved] = useState<Record<string, ActivityLogMode> | null>(null);
  const [draft, setDraft] = useState<Record<string, ActivityLogMode>>({});
  const [loadError, setLoadError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    let live = true;
    listActivityAssociationRules(subjectType, type.key).then(
      (rules) => {
        if (!live) return;
        const modes = Object.fromEntries(rules.map((r) => [r.targetType, r.mode]));
        setSaved(modes);
        setDraft(modes);
      },
      (err: unknown) => {
        if (live) setLoadError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [subjectType, type.key]);

  const savedMode = (target: string) => saved?.[target] ?? defaultMode(target);
  const modeOf = (target: string) => draft[target] ?? savedMode(target);
  const changed = targets.filter((o) => modeOf(o.key) !== savedMode(o.key));
  const editable = canManage && saved !== null && !saving;

  const save = async () => {
    setSaving(true);
    try {
      const next = { ...saved };
      for (const o of changed) {
        const rule = await setActivityAssociationRule({
          subjectType,
          activityType: type.key,
          targetType: o.key,
          mode: modeOf(o.key),
        });
        next[o.key] = rule.mode;
      }
      setSaved(next);
      setDraft(next);
      toast('Settings saved.', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const plural = type.label.toLowerCase();
  return (
    <>
      <div className="os-log-head">
        <div>
          <h2 className="os-h2">Log activity</h2>
          <p className="os-sub">
            Changing the settings for activities won&apos;t affect older data. For example, if you
            change a setting to log all {plural}, it won&apos;t copy over all {plural} that have
            already been logged.
          </p>
        </div>
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm os-reset"
          disabled={!editable}
          onClick={() =>
            setDraft(Object.fromEntries(targets.map((o) => [o.key, defaultMode(o.key)])))
          }
        >
          Reset all changes{' '}
          <Tip text="Sets every associated object back to its default for this object and activity type." />
        </button>
      </div>
      {loadError ? <p className="os-num-field__err os-gap-sm">{loadError}</p> : null}

      {targets.map((o) => {
        const mode = modeOf(o.key);
        const def = defaultMode(o.key);
        return (
          <div className="os-log-row" key={o.key}>
            <p className="os-log-row__label">Associated {o.plural}</p>
            {o.key === 'deal' ? (
              <p className="os-log-row__help">Activities are logged only to open deals.</p>
            ) : null}
            <OsDropdown
              className="os-select os-log-row__btn"
              menuClassName="os-pop os-pop--menu os-pop--log"
              ariaLabel={`Associated ${o.plural}`}
              disabled={!editable}
              label={
                <>
                  <span className="os-select__value">
                    {LOG_OPTIONS.find(([v]) => v === mode)?.[1]}
                    {mode === def ? (
                      <>
                        {' '}
                        <span className="os-default">Default</span>
                      </>
                    ) : null}
                  </span>
                  <DmIcon name="caret" size={18} />
                </>
              }
            >
              {(close) => (
                <div role="listbox">
                  {LOG_OPTIONS.map(([v, label, help]) => (
                    <button
                      key={v}
                      type="button"
                      role="option"
                      aria-selected={v === mode}
                      className={cn('os-menu__item os-log-opt', v === mode && 'is-selected')}
                      onClick={() => {
                        setDraft((cur) => ({ ...cur, [o.key]: v }));
                        close();
                      }}
                    >
                      <span className="os-log-opt__l">
                        {label}
                        {v === def ? <span className="os-default">Default</span> : null}
                      </span>
                      {help ? <small>{help}</small> : null}
                    </button>
                  ))}
                </div>
              )}
            </OsDropdown>
          </div>
        );
      })}

      {changed.length ? (
        <div className="os-savebar" role="region" aria-label="Unsaved changes">
          <span className="os-savebar__text">You have unsaved changes</span>
          <span className="os-savebar__btns">
            <button
              type="button"
              className={cn('btn-crm btn-crm--primary btn-crm--sm', saving && 'is-loading')}
              disabled={saving}
              onClick={() => void save()}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              disabled={saving}
              onClick={() => setDraft(saved ?? {})}
            >
              Cancel
            </button>
          </span>
        </div>
      ) : null}
    </>
  );
}
