'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from 'react';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { cn } from '@/lib/utils/cn';
import type { CallHourRow, Preferences, Profile, RegisteredNumber, WorkDay } from '../types';
import { timezoneOptions } from './accountDefaultsZones';
import {
  AUDIO_LANGUAGES,
  AUDIO_MESSAGE_TYPES,
  AUDIO_VOICES,
  CALL_DAYS,
  COUNTRY_DIALS,
  RING_PREFERENCES,
  TRACKED_TERM_GROUPS,
  TRANSCRIPTION_LANGUAGES,
} from './callingData';
import {
  DialogHead,
  SetDialog,
  SettingsForm,
  useSettingsSaveBar,
  type SettingsSaveHandler,
} from './settings-ui';

type AudioSource = 'Text-To-Speech' | 'Upload Audio';
type AudioTab = 'add' | 'existing';
type AudioItem = {
  id: string;
  name: string;
  type: string;
  creator: string;
  date: string;
  source: AudioSource;
};

/**
 * Phone-modal country picker (design #call-phone-dialog): trigger shows only the
 * ISO code (`US`); the open list shows `US  United States` + dial (`+1`).
 */
const COUNTRY_SELECT_OPTIONS = COUNTRY_DIALS.map(([code, name, dial]) => ({
  value: code,
  label: `${code}\u00A0\u00A0${name}`,
  sub: dial,
  triggerLabel: code,
}));

const TRANSCRIPTION_LANGUAGE_OPTIONS = TRANSCRIPTION_LANGUAGES.map(([value, label]) => ({
  value,
  label,
}));

const TRACKED_TERM_OPTIONS = TRACKED_TERM_GROUPS.map(([value, label]) => ({
  value,
  label,
}));

/** Writes a hidden field the way the browser would, so the settings save bar notices. */
function writeHidden(input: HTMLInputElement, value: string) {
  const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
  setter?.call(input, value);
  input.dispatchEvent(new Event('input', { bubbles: true }));
}

type Props = {
  profile: Profile;
  /** PATCH /me/profile preferences; resolves false when the save failed (already toasted). */
  onSavePrefs: (prefs: Partial<Preferences>) => Promise<false | void>;
  /** Kept for callers; language settings now link to `/settings/account-defaults`. */
  onOpenProfileTab?: () => void;
};

type Row = CallHourRow & { key: number };

const TIMES = Array.from({ length: 48 }, (_, i) => {
  const hour = Math.floor(i / 2);
  const minute = i % 2 ? 30 : 0;
  const value = `${String(hour).padStart(2, '0')}:${minute ? '30' : '00'}`;
  const label = new Date(2000, 0, 1, hour, minute).toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: '2-digit',
  });
  return [value, label] as const;
});

let rowKey = 0;
const withKeys = (rows: CallHourRow[]): Row[] => rows.map((r) => ({ ...r, key: ++rowKey }));

function browserZone() {
  try {
    return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
  } catch {
    return 'UTC';
  }
}

function formatNumber(n: RegisteredNumber) {
  const dial = COUNTRY_DIALS.find(([code]) => code === n.country)?.[2] ?? '';
  const national = dial && n.number.startsWith(dial) ? n.number.slice(dial.length) : n.number;
  const shown = dial ? `${dial} ${national}` : n.number;
  return n.extension ? `${shown} ext. ${n.extension}` : shown;
}

/**
 * Settings › General › Calling (design: settings-profile.php #tab-calling). Personal calling
 * preferences and registered numbers are saved on the profile. CRM numbers, minute usage and Twilio
 * wait for the telephony provider (HUB-410, HUB-416).
 *
 * Edit audio messages opens the design modal for UI parity. There is no audio-messages API yet, so
 * create/list are session-only and are not persisted (HUB-416).
 */
export function GeneralCallingTab({ profile, onSavePrefs }: Props) {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const saveBar = useSettingsSaveBar();
  const prefs = profile.preferences;
  const defaultZone = profile.timezone || browserZone();

  const savedRowsKey = JSON.stringify(prefs.callWorkingHours ?? []);
  const savedRows = useCallback((): Row[] => {
    const saved = JSON.parse(savedRowsKey) as CallHourRow[];
    return withKeys(
      saved.length
        ? saved
        : [{ day: 'mon-fri', start: '09:00', end: '17:00', timezone: defaultZone }],
    );
  }, [savedRowsKey, defaultZone]);
  const [rows, setRows] = useState<Row[]>(savedRows);
  useEffect(() => setRows(savedRows()), [savedRows]);

  const [termsMode, setTermsMode] = useState(prefs.trackedTermsMode ?? 'selected');
  useEffect(() => setTermsMode(prefs.trackedTermsMode ?? 'selected'), [prefs.trackedTermsMode]);

  const [transcriptionLanguage, setTranscriptionLanguage] = useState(
    prefs.transcriptionLanguage ?? '',
  );
  const [trackedTerm, setTrackedTerm] = useState(prefs.trackedTerms?.[0] ?? '');
  const transcriptionRef = useRef<HTMLInputElement>(null);
  const trackedTermRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setTranscriptionLanguage(prefs.transcriptionLanguage ?? '');
    setTrackedTerm(prefs.trackedTerms?.[0] ?? '');
  }, [prefs.transcriptionLanguage, prefs.trackedTerms]);

  const zones = useMemo(() => timezoneOptions(new Date(), defaultZone), [defaultZone]);

  /** Adding or removing a row changes no input, so mark the form unsaved by hand. */
  const touch = (el: HTMLElement) => {
    const form = el.closest('form');
    if (form) saveBar?.markDirty(form);
  };

  const addRow = (e: React.MouseEvent<HTMLButtonElement>) => {
    const last = rows[rows.length - 1];
    setRows([
      ...rows,
      {
        key: ++rowKey,
        day: 'sat-sun',
        start: last?.start ?? '09:00',
        end: last?.end ?? '17:00',
        timezone: last?.timezone ?? defaultZone,
      },
    ]);
    touch(e.currentTarget);
  };

  const removeRow = (e: React.MouseEvent<HTMLButtonElement>, key: number) => {
    if (rows.length <= 1) {
      toast('At least one working-hours row is required', 'info');
      return;
    }
    touch(e.currentTarget);
    setRows(rows.filter((r) => r.key !== key));
  };

  const save = useCallback<SettingsSaveHandler>(
    async (form) => {
      const value = (name: string) =>
        (form.elements.namedItem(name) as HTMLSelectElement | null)?.value ?? '';
      const hours: CallHourRow[] = Array.from(
        form.querySelectorAll<HTMLElement>('[data-call-hours-row]'),
      ).map((row) => {
        const pick = (name: string) =>
          row.querySelector<HTMLSelectElement>(`select[name="${name}"]`)?.value ?? '';
        return {
          day: pick('call_day') as WorkDay,
          start: pick('call_start'),
          end: pick('call_end'),
          timezone: pick('call_timezone'),
        };
      });
      if (hours.some((h) => h.start >= h.end)) {
        toast('Each call working-hours range must end after it starts', 'danger');
        return false;
      }
      const mode = value('tracked_terms_mode') === 'all' ? 'all' : 'selected';
      const term = value('tracked_terms');
      return onSavePrefs({
        callWorkingHours: hours,
        callRingPreference: value('call_ring_preference') as Preferences['callRingPreference'],
        transcriptionLanguage: value('transcription_language') || null,
        trackedTermsMode: mode,
        trackedTerms: mode === 'selected' && term ? [term] : [],
      });
    },
    [onSavePrefs, toast],
  );

  const onReset = useCallback(
    (form: HTMLFormElement) => {
      setRows(savedRows());
      const checked = form.querySelector<HTMLInputElement>(
        'input[name="tracked_terms_mode"]:checked',
      );
      setTermsMode(checked?.value === 'all' ? 'all' : 'selected');
      setTranscriptionLanguage(prefs.transcriptionLanguage ?? '');
      setTrackedTerm(prefs.trackedTerms?.[0] ?? '');
    },
    [savedRows, prefs.transcriptionLanguage, prefs.trackedTerms],
  );

  const numbers = prefs.registeredNumbers ?? [];
  const [phoneOpen, setPhoneOpen] = useState(false);
  const [audioOpen, setAudioOpen] = useState(false);

  const removeNumber = async (n: RegisteredNumber) => {
    const ok = await confirm({
      title: 'Remove phone number?',
      message: `${formatNumber(n)} will no longer be available for outbound calls.`,
      confirmLabel: 'Remove',
      danger: true,
    });
    if (!ok) return;
    const result = await onSavePrefs({
      registeredNumbers: numbers.filter((x) => x !== n),
    });
    if (result !== false) toast('Phone number removed', 'info');
  };

  const month = new Date().toLocaleDateString('en-US', { month: 'long' });

  return (
    <>
      <p className="set-preferences-note">
        These preferences only apply to you. For account level calling defaults go to{' '}
        <Link href="/settings/account-defaults" className="link">
          account call settings <CrmIcon name="external" className="iconSize-14" />
        </Link>
        .
      </p>

      <SettingsForm className="set-calling-form" onSave={save} onReset={onReset}>
        <h2 className="set-calling-card__title">CRM numbers</h2>
        <p className="set-calling-card__desc crm-mb-4">
          These are phone numbers that were acquired through CRM and have either been assigned to
          you, or have assignments that include you. These numbers can be used for both inbound and
          outbound calling.
        </p>
        <div className="set-calling-top-actions">
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setAudioOpen(true)}
          >
            Edit audio messages
          </button>
        </div>

        <div className="card set-card set-calling-card">
          <div className="set-calling-hero">
            <div className="set-calling-card__body">
              <h2 className="set-calling-card__title">
                Use CRM Calling to streamline your communication and keep all your conversations in
                one place
              </h2>
              <p className="set-calling-card__desc">
                Use a{' '}
                <button
                  type="button"
                  className="link"
                  onClick={() => toast('CRM number is coming soon', 'info')}
                >
                  CRM number
                </button>
                , port an existing number or connect a third-party integration ↗ to start making and
                receiving calls with automatic call logging.
              </p>
            </div>
            <div className="set-calling-card__art" aria-hidden="true">
              {/* Design: assets/img/crm-calling.svg */}
              <img src="/crm/assets/img/crm-calling.svg" width={190} alt="" />
            </div>
          </div>
        </div>

        <div className="set-calling-section">
          <h2 className="set-calling-section__title">Registered numbers</h2>
          <p className="set-calling-section__desc">
            These are phone numbers you have added that were not acquired through CRM. These lines
            can only be used to place outbound calls from the CRM and face increased risk of blocked
            calls and spam labeling from local carriers.
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setPhoneOpen(true)}
          >
            Add phone number
          </button>
          {numbers.length ? (
            <div className="card set-calling-number-list">
              {numbers.map((n) => (
                <div key={`${n.number}#${n.extension ?? ''}`} className="connect-row">
                  <span className="connect-row__icon">
                    <CrmIcon name="phone" className="iconSize-16" />
                  </span>
                  <div className="connect-row__body">
                    <p className="crm-fw-semibold">{formatNumber(n)}</p>
                    <p className="field__help">Registered for outbound calling</p>
                  </div>
                  <span className="badge">Registered</span>
                  {/* <button
                    type="button"
                    className="icon-btn crm-rounded-circle h-32 w-32"
                    aria-label={`Remove ${formatNumber(n)}`}
                    onClick={() => void removeNumber(n)}
                  >
                    <CrmIcon name="trash" className="iconSize-16" />
                  </button> */}
                </div>
              ))}
            </div>
          ) : (
            <div className="card set-calling-empty">
              <svg width="74" height="62" viewBox="0 0 74 62" fill="none" aria-hidden="true">
                <path d="M10 49 36 36l28 13-28 13L10 49Z" fill="var(--surface-3)" />
                <circle cx="36" cy="20" r="12" stroke="var(--border-strong)" strokeWidth="2" />
                <path
                  d="m28 20 5 5 11-12"
                  stroke="var(--border-strong)"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="m48 7 3-5m4 10 6-1"
                  stroke="var(--border-strong)"
                  strokeWidth="2"
                  strokeLinecap="round"
                />
              </svg>
              <p>You do not have any registered phone numbers.</p>
            </div>
          )}
        </div>

        <div className="set-calling-section">
          <h2 className="set-calling-section__title crm-mt-3">
            Call working hours{' '}
            <span
              className="set-info"
              tabIndex={0}
              data-tip-text="Set the hours when you want calls to be routed to you."
              aria-label="Call working hours info"
            >
              <CrmIcon name="info" className="iconSize-14" />
            </span>
          </h2>
          <p className="set-calling-section__desc">
            Set the time when you want calls to be routed to you. You can use this to define routing
            in your phone number setup. This is separate from your general working hours found in{' '}
            <Link href="/settings/users" className="link">
              Users and Teams <CrmIcon name="external" className="iconSize-14" />
            </Link>
            .
          </p>
          <div className="set-calling-hours">
            <div className="set-calling-hours__head">
              <span>Day</span>
              <span />
              <span>Starting time</span>
              <span />
              <span>End time</span>
              <span>Timezone</span>
              <span />
            </div>
            <div className="set-calling-hours__rows">
              {rows.map((row) => (
                <div key={row.key} className="set-calling-hours__row" data-call-hours-row>
                  <select className="input" aria-label="Day" name="call_day" defaultValue={row.day}>
                    {CALL_DAYS.map(([value, label]) => (
                      <option key={value} value={value}>
                        {label}
                      </option>
                    ))}
                  </select>
                  <span className="set-calling-from">from</span>
                  <select
                    className="input"
                    aria-label="Starting time"
                    name="call_start"
                    defaultValue={row.start}
                  >
                    {TIMES.map(([value, label]) => (
                      <option key={value} value={value}>
                        {label}
                      </option>
                    ))}
                  </select>
                  <span className="set-calling-to">to</span>
                  <select
                    className="input"
                    aria-label="End time"
                    name="call_end"
                    defaultValue={row.end}
                  >
                    {TIMES.map(([value, label]) => (
                      <option key={value} value={value}>
                        {label}
                      </option>
                    ))}
                  </select>
                  <select
                    className="input"
                    aria-label="Timezone"
                    name="call_timezone"
                    defaultValue={row.timezone}
                  >
                    {zones.map((z) => (
                      <option key={z.value} value={z.value}>
                        {z.label}
                      </option>
                    ))}
                  </select>
                  <button
                    type="button"
                    className="icon-btn crm-rounded-circle h-32 w-32"
                    aria-label="Remove working hours"
                    onClick={(e) => removeRow(e, row.key)}
                  >
                    <CrmIcon name="trash" className="iconSize-16" />
                  </button>
                </div>
              ))}
            </div>
            <button type="button" className="link set-calling-add-hours" onClick={addRow}>
              + Add hours
            </button>
          </div>
        </div>

        <div className="set-calling-section">
          <h2 className="set-calling-section__title crm-mt-3">Inbound calling preferences</h2>
          <p className="set-calling-section__desc">
            Set how you want to receive inbound calls to your CRM phone numbers.
          </p>
          <div className="field set-calling-narrow-field">
            <label className="field__label" htmlFor="call-ring-preference">
              Ring preference
            </label>
            <select
              className="input"
              id="call-ring-preference"
              name="call_ring_preference"
              defaultValue={prefs.callRingPreference ?? 'browser'}
            >
              {RING_PREFERENCES.map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div className="set-calling-section">
          <h2 className="set-calling-section__title crm-mt-3">Usage this month</h2>
          <p className="set-calling-section__desc">
            This is the accumulative overview for all users of calling in your account. You can also
            view historical minute usage on the{' '}
            <Link href="/calls/analytics" className="link">
              call analytics dashboard <CrmIcon name="external" className="iconSize-14" />
            </Link>
            .
          </p>
          <div className="card set-calling-usage">
            <div className="set-calling-usage__head">
              <strong>
                {month} minute usage&nbsp; <span>0</span> / 12,000
              </strong>
              <Link href="/settings/billing" className="link">
                Manage minute subscription
              </Link>
            </div>
            <div className="set-calling-progress">
              <span style={{ width: '0%' }} />
            </div>
            <p>
              Usage resets at the start of each month. The available minutes are based on your CRM
              plan and any minute subscriptions in your account.
            </p>
          </div>
        </div>

        <div className="set-calling-section">
          <h2 className="set-calling-section__title crm-mt-3">Connect an integration</h2>
          <div className="set-calling-integration">
            <div className="set-calling-integration__logo">
              <svg width="28" height="28" viewBox="0 0 32 32" fill="none" aria-hidden="true">
                <circle cx="16" cy="16" r="16" fill="#F22F46" />
                <circle cx="11.5" cy="11.5" r="2.5" fill="#fff" />
                <circle cx="20.5" cy="11.5" r="2.5" fill="#fff" />
                <circle cx="11.5" cy="20.5" r="2.5" fill="#fff" />
                <circle cx="20.5" cy="20.5" r="2.5" fill="#fff" />
              </svg>
            </div>
            <div className="set-calling-integration__info">
              <h3 className="set-calling-integration__name">
                <button
                  type="button"
                  className="link"
                  onClick={() => toast('Twilio connect is coming soon', 'info')}
                >
                  Sign up or connect your Twilio account
                </button>
              </h3>
              <p className="set-calling-integration__desc">
                Get more calling minutes and access additional supported countries
              </p>
            </div>
          </div>
        </div>

        <div className="set-calling-section">
          <h2 className="set-calling-section__title set-calling-section__title--lg crm-mt-3">
            Transcription and Analysis
          </h2>
          <p className="set-calling-section__desc">
            Conversation Intelligence gives real-time insights into customer conversations and
            coaching opportunities through call transcription, call analysis and reporting on
            tracked terms.
          </p>
          <div className="set-calling-group set-calling-transcription">
            <h3 className="set-calling-group__title">Transcription language</h3>
            <p className="set-calling-group__desc">
              Choose a preferred language for call transcriptions. Once selected, all calls will be
              in your preferred language. This choice is separate from your{' '}
              <Link href="/settings/account-defaults" className="link">
                language settings
              </Link>
              .
            </p>
            <div className="set-calling-language">
              <input
                ref={transcriptionRef}
                type="hidden"
                name="transcription_language"
                value={transcriptionLanguage}
                readOnly
              />
              <CustomSelect
                className="crm-w-100"
                placeholder="Select transcription language"
                searchPlaceholder="Search"
                emptyText="No languages match"
                value={transcriptionLanguage}
                options={TRANSCRIPTION_LANGUAGE_OPTIONS}
                onChange={(next) => {
                  if (transcriptionRef.current) writeHidden(transcriptionRef.current, next);
                  setTranscriptionLanguage(next);
                }}
                searchable
                showPlaceholderOption
                menuActions={false}
                menuMinWidth={330}
              />
            </div>
          </div>
          <div className="set-calling-group crm-mt-2">
            <h3 className="set-calling-group__title">Tracked Terms Notifications</h3>
            <p className="set-calling-group__desc">
              Customize which tracked terms are included in your notifications.
            </p>
            <div className="set-calling-radios">
              {(
                [
                  ['all', 'All terms'],
                  ['selected', 'Selected Terms'],
                ] as const
              ).map(([value, label]) => (
                <label key={value} className="set-calling-radio">
                  <input
                    type="radio"
                    name="tracked_terms_mode"
                    value={value}
                    defaultChecked={(prefs.trackedTermsMode ?? 'selected') === value}
                    onChange={() => setTermsMode(value)}
                  />
                  <span>{label}</span>
                </label>
              ))}
            </div>
            <div className="set-calling-terms-box" hidden={termsMode === 'all'}>
              <input
                ref={trackedTermRef}
                type="hidden"
                name="tracked_terms"
                value={trackedTerm}
                readOnly
              />
              <CustomSelect
                className="crm-w-100"
                placeholder="Select tracked terms"
                searchPlaceholder="Search"
                emptyText="No terms match"
                value={trackedTerm}
                options={TRACKED_TERM_OPTIONS}
                onChange={(next) => {
                  if (trackedTermRef.current) writeHidden(trackedTermRef.current, next);
                  setTrackedTerm(next);
                }}
                searchable
                showPlaceholderOption
                menuActions={false}
                menuMinWidth={280}
              />
            </div>
          </div>
        </div>
      </SettingsForm>

      <AddPhoneDialog
        open={phoneOpen}
        onClose={() => setPhoneOpen(false)}
        existing={numbers}
        onAdd={(n) => onSavePrefs({ registeredNumbers: [...numbers, n] })}
      />
      <EditAudioMessagesDialog open={audioOpen} onClose={() => setAudioOpen(false)} />
      {confirmDialog}
    </>
  );
}

/** "Add your phone number": number, then a verification code, then done (design 1/3 … 3/3). */
function AddPhoneDialog({
  open,
  onClose,
  existing,
  onAdd,
}: {
  open: boolean;
  onClose: () => void;
  existing: RegisteredNumber[];
  onAdd: (n: RegisteredNumber) => Promise<false | void>;
}) {
  const [step, setStep] = useState(1);
  const [country, setCountry] = useState('US');
  const [number, setNumber] = useState('');
  const [extension, setExtension] = useState('');
  const [method, setMethod] = useState<'sms' | 'call'>('sms');
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (open) return;
    setStep(1);
    setNumber('');
    setExtension('');
    setMethod('sms');
    setCode('');
    setError('');
  }, [open]);

  const dial = COUNTRY_DIALS.find(([c]) => c === country)?.[2] ?? '+1';
  const national = number.replace(/\D/g, '').replace(/^0+/, '');
  const full = `${dial}${national}`;
  const validNumber = /^\+[1-9]\d{6,14}$/.test(full) && national.length >= 4;
  const ext = extension.replace(/\D/g, '');

  const next = async () => {
    setError('');
    if (step === 1) {
      if (!validNumber) return setError('Please enter a valid phone number.');
      if (existing.some((n) => n.number === full && (n.extension ?? '') === ext)) {
        return setError('That phone number is already registered.');
      }
      setStep(2);
      return;
    }
    if (step === 2) {
      if (!/^\d{4,6}$/.test(code)) return setError('Enter a valid 4–6 digit verification code.');
      setBusy(true);
      const result = await onAdd({
        country,
        number: full,
        extension: ext || null,
        verification: method,
        addedAt: new Date().toISOString(),
      });
      setBusy(false);
      if (result === false) return;
      setStep(3);
      return;
    }
    onClose();
  };

  const nextLabel =
    step === 1 ? (method === 'sms' ? 'Text me' : 'Call me') : step === 2 ? 'Verify' : 'Done';
  const nextDisabled = busy || (step === 1 && !national) || (step === 2 && !code);

  return (
    <SetDialog
      open={open}
      onClose={onClose}
      labelledBy="call-phone-title"
      className="set-modal set-calling-phone-modal"
    >
      <DialogHead id="call-phone-title" title="Add your phone number" onClose={onClose} />
      <div className="set-modal__body">
        {step === 1 && (
          <div>
            <h3 className="set-calling-step-title">Enter your phone number</h3>
            <p className="set-calling-modal-intro">
              To verify your phone number, you&apos;ll receive a code via SMS message or phone call.
            </p>
            <div className="set-calling-phone-fields">
              <CustomSelect
                className="set-calling-country-select"
                placeholder="US"
                value={country}
                options={COUNTRY_SELECT_OPTIONS}
                onChange={setCountry}
                searchable
                menuActions={false}
                menuMinWidth={330}
                searchPlaceholder="Search"
                emptyText="No countries match"
              />
              <input
                className="input"
                name="phone_number"
                type="tel"
                placeholder={dial}
                aria-label="Phone number"
                value={number}
                onChange={(e) => setNumber(e.target.value)}
                autoFocus
              />
              <input
                className="input"
                name="phone_extension"
                placeholder="Extension"
                aria-label="Extension"
                inputMode="numeric"
                value={extension}
                onChange={(e) => setExtension(e.target.value)}
              />
            </div>
            {error && <p className="set-calling-phone-error">{error}</p>}
            <fieldset className="set-calling-radio-field">
              <legend>Receive the code by (data rates apply):</legend>
              {(
                [
                  ['sms', 'SMS message'],
                  ['call', 'Phone call'],
                ] as const
              ).map(([value, label]) => (
                <label key={value} className="set-calling-radio">
                  <input
                    type="radio"
                    name="verification_method"
                    value={value}
                    checked={method === value}
                    onChange={() => setMethod(value)}
                  />
                  <span>{label}</span>
                </label>
              ))}
            </fieldset>
          </div>
        )}
        {step === 2 && (
          <div>
            <h3 className="set-calling-step-title">Verify your phone number</h3>
            <p className="set-calling-modal-intro">
              Enter the verification code sent to {dial} {national}.
            </p>
            <label className="field__label" htmlFor="phone-verification-code">
              Verification code
            </label>
            <input
              className="input"
              id="phone-verification-code"
              inputMode="numeric"
              maxLength={6}
              placeholder="Enter code"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
              autoFocus
            />
            <p className="field__help">
              Codes are not sent yet: enter any 4–6 digit code to continue.
            </p>
            {error && <p className="set-calling-phone-error">{error}</p>}
          </div>
        )}
        {step === 3 && (
          <div>
            <h3 className="set-calling-step-title">Phone number added</h3>
            <p className="set-calling-modal-intro">
              Your phone number has been verified and added for outbound calling.
            </p>
          </div>
        )}
        <div className="set-calling-phone-footer">
          {step < 3 && (
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              data-phone-cancel
              onClick={onClose}
            >
              Cancel
            </button>
          )}
          <span className="set-calling-step-count">{step}/3</span>
          <button
            type="button"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            data-phone-next
            disabled={nextDisabled}
            onClick={() => void next()}
          >
            <span className="btn-crm__spinner" aria-hidden />
            {nextLabel}
          </button>
        </div>
      </div>
    </SetDialog>
  );
}

/**
 * Edit audio messages (design: #call-audio-dialog).
 * TODO(HUB-416): wire create/list/delete to the calling audio-messages API when available.
 * Until then items stay in this session only and are not saved to the server.
 */
function EditAudioMessagesDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
  const toast = useToast();
  const [tab, setTab] = useState<AudioTab>('existing');
  const [items, setItems] = useState<AudioItem[]>([]);
  const [search, setSearch] = useState('');
  const [sortKey, setSortKey] = useState<'name' | 'type' | 'creator' | 'date'>('name');
  const [sortDir, setSortDir] = useState<1 | -1>(1);
  const [typeFilter, setTypeFilter] = useState('');
  const [creatorFilter, setCreatorFilter] = useState('');
  const [typePopOpen, setTypePopOpen] = useState(false);
  const [createdPopOpen, setCreatedPopOpen] = useState(false);
  const [typeSearch, setTypeSearch] = useState('');
  const [createdSearch, setCreatedSearch] = useState('');
  const typeFilterRef = useRef<HTMLDivElement>(null);
  const createdFilterRef = useRef<HTMLDivElement>(null);
  const typeSearchRef = useRef<HTMLInputElement>(null);
  const createdSearchRef = useRef<HTMLInputElement>(null);

  const [name, setName] = useState('');
  const [messageType, setMessageType] = useState('');
  const [source, setSource] = useState<AudioSource>('Text-To-Speech');
  const [messageText, setMessageText] = useState('');
  const [language, setLanguage] = useState<string>(AUDIO_LANGUAGES[0]);
  const [voice, setVoice] = useState<string>(AUDIO_VOICES[0]);
  const [file, setFile] = useState<File | null>(null);

  useEffect(() => {
    // Match tickets settings.js: lock page scroll while the right-side audio drawer is open.
    const root = document.documentElement;
    const body = document.body;
    if (open) {
      root.classList.add('calling-audio-dialog-open');
      body.classList.add('calling-audio-dialog-open');
    } else {
      root.classList.remove('calling-audio-dialog-open');
      body.classList.remove('calling-audio-dialog-open');
      setTab('existing');
      setSearch('');
      setTypeFilter('');
      setCreatorFilter('');
      setTypePopOpen(false);
      setCreatedPopOpen(false);
      setTypeSearch('');
      setCreatedSearch('');
      setName('');
      setMessageType('');
      setSource('Text-To-Speech');
      setMessageText('');
      setLanguage(AUDIO_LANGUAGES[0]);
      setVoice(AUDIO_VOICES[0]);
      setFile(null);
    }
    return () => {
      root.classList.remove('calling-audio-dialog-open');
      body.classList.remove('calling-audio-dialog-open');
    };
  }, [open]);

  useEffect(() => {
    if (!typePopOpen && !createdPopOpen) return;
    const onDoc = (e: MouseEvent) => {
      const target = e.target as Node;
      if (typePopOpen && !typeFilterRef.current?.contains(target)) setTypePopOpen(false);
      if (createdPopOpen && !createdFilterRef.current?.contains(target)) setCreatedPopOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [typePopOpen, createdPopOpen]);

  useEffect(() => {
    if (typePopOpen) {
      setTypeSearch('');
      queueMicrotask(() => typeSearchRef.current?.focus());
    }
  }, [typePopOpen]);

  useEffect(() => {
    if (createdPopOpen) {
      setCreatedSearch('');
      queueMicrotask(() => createdSearchRef.current?.focus());
    }
  }, [createdPopOpen]);

  const creators = useMemo(
    () => Array.from(new Set(items.map((i) => i.creator))).sort((a, b) => a.localeCompare(b)),
    [items],
  );

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    const rows = items.filter((item) => {
      if (typeFilter && item.type !== typeFilter) return false;
      if (creatorFilter && item.creator !== creatorFilter) return false;
      if (!q) return true;
      return (
        item.name.toLowerCase().includes(q) ||
        item.type.toLowerCase().includes(q) ||
        item.creator.toLowerCase().includes(q)
      );
    });
    rows.sort((a, b) => {
      const left = a[sortKey].toLowerCase();
      const right = b[sortKey].toLowerCase();
      if (left < right) return -1 * sortDir;
      if (left > right) return 1 * sortDir;
      return 0;
    });
    return rows;
  }, [items, search, typeFilter, creatorFilter, sortKey, sortDir]);

  const toggleSort = (key: typeof sortKey) => {
    if (sortKey === key) setSortDir((d) => (d === 1 ? -1 : 1));
    else {
      setSortKey(key);
      setSortDir(1);
    }
  };

  const resetAddForm = () => {
    setName('');
    setMessageType('');
    setSource('Text-To-Speech');
    setMessageText('');
    setLanguage(AUDIO_LANGUAGES[0]);
    setVoice(AUDIO_VOICES[0]);
    setFile(null);
  };

  const onSave = (e: FormEvent) => {
    e.preventDefault();
    if (!name.trim()) {
      toast('Enter a message name', 'danger');
      return;
    }
    if (!messageType) {
      toast('Choose a message type', 'danger');
      return;
    }
    if (source === 'Upload Audio' && !file) {
      toast('Upload an .mp3 or .wav file', 'danger');
      return;
    }
    // Session-only until HUB-416 audio API lands — do not PATCH profile or call settings.
    setItems((prev) => [
      {
        id: `audio-${Date.now()}`,
        name: name.trim(),
        type: messageType,
        creator: 'You',
        date: new Date().toLocaleDateString(undefined, {
          year: 'numeric',
          month: 'short',
          day: 'numeric',
        }),
        source,
      },
      ...prev,
    ]);
    resetAddForm();
    setTab('existing');
    toast('Audio message saved for this session only (not stored on the server yet)', 'info');
  };

  const typeOptions = AUDIO_MESSAGE_TYPES.filter((t) =>
    t.label.toLowerCase().includes(typeSearch.trim().toLowerCase()),
  );
  const creatorOptions = creators.filter((c) =>
    c.toLowerCase().includes(createdSearch.trim().toLowerCase()),
  );

  return (
    <SetDialog
      open={open}
      onClose={onClose}
      labelledBy="call-audio-title"
      className="set-calling-modal"
    >
      <DialogHead id="call-audio-title" title="Edit audio messages" onClose={onClose} />
      <div className="set-modal__body">
        <div className="set-calling-modal-tabs" role="tablist">
          <button
            type="button"
            role="tab"
            aria-selected={tab === 'add'}
            className={cn(tab === 'add' && 'is-active')}
            onClick={() => setTab('add')}
          >
            Add an audio message
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={tab === 'existing'}
            className={cn(tab === 'existing' && 'is-active')}
            onClick={() => setTab('existing')}
          >
            Edit existing audio messages
          </button>
        </div>

        {tab === 'add' && (
          <div data-audio-panel="add">
            <p className="set-calling-modal-intro">
              Create an audio message or file that can be used across CRM.
            </p>
            <form data-audio-form onSubmit={onSave} noValidate>
              <div className="field">
                <label className="field__label" htmlFor="audio-message-name">
                  Message name <span className="crm-text-danger">*</span>
                </label>
                <input
                  className="input"
                  id="audio-message-name"
                  name="message_name"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
              </div>
              <div className="field">
                <label className="field__label" htmlFor="audio-message-type">
                  Message type <span className="crm-text-danger">*</span>
                </label>
                <CustomSelect
                  id="audio-message-type"
                  className="crm-w-100 set-calling-audio-select"
                  placeholder="Choose a message type"
                  value={messageType}
                  options={AUDIO_MESSAGE_TYPES.map((t) => ({
                    value: t.value,
                    label: t.label,
                    inactive: t.disabled,
                  }))}
                  onChange={setMessageType}
                  searchable
                  searchPlaceholder="Search"
                  emptyText="No message types match"
                  menuActions={false}
                  menuMinWidth={280}
                />
              </div>
              <div className="field">
                <label className="field__label" htmlFor="audio-source">
                  Audio source
                </label>
                <CustomSelect
                  id="audio-source"
                  className="crm-w-100 set-calling-audio-select"
                  placeholder="Audio source"
                  value={source}
                  options={[
                    { value: 'Text-To-Speech', label: 'Text-To-Speech' },
                    { value: 'Upload Audio', label: 'Upload Audio' },
                  ]}
                  onChange={(next) => setSource(next as AudioSource)}
                  searchable={false}
                  menuActions={false}
                  menuMinWidth={280}
                />
              </div>

              {source === 'Text-To-Speech' ? (
                <div className="field" data-audio-text-wrap>
                  <label className="field__label" htmlFor="audio-message-text">
                    Enter your message
                  </label>
                  <p className="field__help">
                    Enter text to create an audio version of your message. The written language must
                    match the selected audio language.
                  </p>
                  <textarea
                    className="input"
                    id="audio-message-text"
                    name="message_text"
                    rows={5}
                    maxLength={1000}
                    placeholder="Type your audio message..."
                    value={messageText}
                    onChange={(e) => setMessageText(e.target.value)}
                  />
                  <div className="set-calling-char-count">{messageText.length}/1000</div>
                </div>
              ) : (
                <div className="field set-calling-upload-field" data-audio-file-wrap>
                  <label className="field__label" htmlFor="audio-file">
                    Upload audio message
                  </label>
                  <p className="field__help set-calling-upload-help">
                    Upload an audio file to use as the message.
                  </p>
                  <input
                    className="set-calling-file-input"
                    type="file"
                    id="audio-file"
                    name="audio_file"
                    accept=".mp3,.wav,audio/mpeg,audio/wav"
                    onChange={(e) => setFile(e.target.files?.[0] ?? null)}
                  />
                  <label
                    className="set-calling-upload-drop"
                    htmlFor="audio-file"
                    tabIndex={0}
                    role="button"
                  >
                    <svg
                      className="set-calling-upload-icon"
                      viewBox="0 0 40 44"
                      fill="none"
                      aria-hidden="true"
                    >
                      <path
                        d="M10 5.5H23L31 13.5V37.5C31 39.2 29.7 40.5 28 40.5H10C8.3 40.5 7 39.2 7 37.5V8.5C7 6.8 8.3 5.5 10 5.5Z"
                        stroke="currentColor"
                        strokeWidth="2.5"
                        strokeLinejoin="round"
                      />
                      <path
                        d="M23 5.5V13.5H31M13 22H25M13 28H25M13 34H22"
                        stroke="currentColor"
                        strokeWidth="2.5"
                        strokeLinecap="round"
                      />
                      <path
                        d="M30 2V13M25 7L30 2L35 7"
                        stroke="currentColor"
                        strokeWidth="2.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      />
                    </svg>
                    <span className="set-calling-upload-copy">
                      <strong>Upload a file that is:</strong>
                      <span>• An .mp3 or .wav</span>
                      <span>• Less than 5MB</span>
                    </span>
                  </label>
                  {file && <p className="set-calling-upload-filename">{file.name}</p>}
                </div>
              )}

              {source === 'Text-To-Speech' && (
                <div className="set-calling-audio-voice" data-audio-voice-wrap>
                  <div className="field">
                    <label className="field__label" htmlFor="audio-language">
                      Language
                    </label>
                    <CustomSelect
                      id="audio-language"
                      className="crm-w-100 set-calling-audio-select"
                      placeholder="Language"
                      value={language}
                      options={AUDIO_LANGUAGES.map((lang) => ({ value: lang, label: lang }))}
                      onChange={setLanguage}
                      searchable
                      searchPlaceholder="Search"
                      emptyText="No languages match"
                      menuActions={false}
                      menuMinWidth={240}
                    />
                  </div>
                  <div className="field">
                    <label className="field__label" htmlFor="audio-voice">
                      Voice
                    </label>
                    <div className="set-calling-voice-line">
                      <CustomSelect
                        id="audio-voice"
                        className="crm-w-100 set-calling-audio-select"
                        placeholder="Voice"
                        value={voice}
                        options={AUDIO_VOICES.map((v) => ({ value: v, label: v }))}
                        onChange={setVoice}
                        searchable
                        searchPlaceholder="Search"
                        emptyText="No voices match"
                        menuActions={false}
                        menuMinWidth={200}
                      />
                      <button
                        type="button"
                        className="icon-btn"
                        aria-label="Preview voice"
                        onClick={() => toast('Voice preview is not available yet', 'info')}
                      >
                        <svg
                          className="icon iconSize-16"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="1.8"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          aria-hidden
                        >
                          <path d="m8 5 12 7-12 7V5z" />
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {source === 'Text-To-Speech' ? (
                <div className="set-calling-audio-legal" data-audio-tts-legal>
                  <p className="field__help">
                    You are responsible for ensuring that the audio message does not infringe on
                    intellectual property rights of third parties. If the audio message is for call
                    recording consent, you are responsible for compliance with call recording laws.{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={() => toast('Call recording laws help is coming soon', 'info')}
                    >
                      Learn more about call recording laws.
                    </button>
                  </p>
                </div>
              ) : (
                <div className="set-calling-audio-legal" data-audio-upload-legal>
                  <p>
                    You are responsible for ensuring that the audio message does not infringe on the
                    intellectual property rights of third parties. If the audio message is for call
                    recording, you are responsible for compliance with call recording laws.{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={() => toast('Call recording laws help is coming soon', 'info')}
                    >
                      Learn more about call recording laws
                    </button>
                    .
                  </p>
                  <p>
                    CRM reserves the right to review and remove any audio message that violates its{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={() => toast('Acceptable Use Policy is coming soon', 'info')}
                    >
                      Acceptable Use Policy
                    </button>
                    .
                  </p>
                </div>
              )}

              <div className="set-modal__foot">
                <button type="button" className="btn-crm btn-crm--ghost" onClick={onClose}>
                  Cancel
                </button>
                <button type="submit" className="btn-crm btn-crm--primary">
                  Save
                </button>
              </div>
            </form>
          </div>
        )}

        {tab === 'existing' && (
          <div data-audio-panel="existing">
            <div className="set-calling-existing-search">
              <label className="set-calling-searchbox">
                <input
                  className="input"
                  type="search"
                  placeholder="Search messages"
                  aria-label="Search messages"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                />
                <span aria-hidden="true">
                  <svg viewBox="0 0 20 20" width="17" height="17" fill="none">
                    <circle cx="8.5" cy="8.5" r="5.5" stroke="currentColor" strokeWidth="1.4" />
                    <path
                      d="m12.5 12.5 4 4"
                      stroke="currentColor"
                      strokeWidth="1.4"
                      strokeLinecap="round"
                    />
                  </svg>
                </span>
              </label>
            </div>
            <div className="set-calling-filterbar" role="group" aria-label="Filter audio messages">
              <div
                ref={typeFilterRef}
                className={cn('set-calling-filter-wrap', typePopOpen && 'is-open')}
              >
                <button
                  type="button"
                  className="set-calling-filter-trigger"
                  aria-expanded={typePopOpen}
                  aria-haspopup="listbox"
                  onClick={() => {
                    setTypePopOpen((v) => !v);
                    setCreatedPopOpen(false);
                  }}
                >
                  Message type{' '}
                  <svg
                    className="set-calling-caret-svg"
                    viewBox="0 0 16 16"
                    width="12"
                    height="12"
                    fill="none"
                    aria-hidden="true"
                  >
                    <path
                      d="m4 6 4 4 4-4"
                      stroke="currentColor"
                      strokeWidth="1.6"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </button>
                {typePopOpen && (
                  <div className="set-calling-filter-pop" data-audio-filter-pop="type">
                    <label className="set-calling-filter-search">
                      <input
                        ref={typeSearchRef}
                        type="search"
                        placeholder="Type to search"
                        aria-label="Search message types"
                        value={typeSearch}
                        onChange={(e) => setTypeSearch(e.target.value)}
                      />
                    </label>
                    <div data-audio-type-options>
                      {typeOptions.map((t) => (
                        <button
                          key={t.value}
                          type="button"
                          className={cn(typeFilter === t.value && 'is-selected')}
                          onClick={() => {
                            setTypeFilter((cur) => (cur === t.value ? '' : t.value));
                            setTypePopOpen(false);
                          }}
                        >
                          {t.label}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              <div
                ref={createdFilterRef}
                className={cn('set-calling-filter-wrap', createdPopOpen && 'is-open')}
              >
                <button
                  type="button"
                  className="set-calling-filter-trigger"
                  aria-expanded={createdPopOpen}
                  aria-haspopup="listbox"
                  onClick={() => {
                    setCreatedPopOpen((v) => !v);
                    setTypePopOpen(false);
                  }}
                >
                  Created by{' '}
                  <svg
                    className="set-calling-caret-svg"
                    viewBox="0 0 16 16"
                    width="12"
                    height="12"
                    fill="none"
                    aria-hidden="true"
                  >
                    <path
                      d="m4 6 4 4 4-4"
                      stroke="currentColor"
                      strokeWidth="1.6"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                </button>
                {createdPopOpen && (
                  <div
                    className="set-calling-filter-pop set-calling-created-pop"
                    data-audio-filter-pop="created"
                  >
                    <label className="set-calling-filter-search">
                      <input
                        ref={createdSearchRef}
                        type="search"
                        placeholder="Type to search"
                        aria-label="Search creators"
                        value={createdSearch}
                        onChange={(e) => setCreatedSearch(e.target.value)}
                      />
                    </label>
                    <div data-audio-created-options>
                      {creatorOptions.length === 0 ? (
                        <p className="field__help crm-p-2">No creators yet.</p>
                      ) : (
                        creatorOptions.map((c) => (
                          <button
                            key={c}
                            type="button"
                            className={cn(creatorFilter === c && 'is-selected')}
                            onClick={() => {
                              setCreatorFilter((cur) => (cur === c ? '' : c));
                              setCreatedPopOpen(false);
                            }}
                          >
                            {c}
                          </button>
                        ))
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="set-calling-existing-table">
              <table className="set-table">
                <thead>
                  <tr>
                    <th className="set-calling-title-col">
                      <button
                        type="button"
                        className="set-calling-sort-trigger"
                        onClick={() => toggleSort('name')}
                      >
                        Message title <span aria-hidden="true">↕</span>
                      </button>
                    </th>
                    <th>
                      <span className="set-calling-heading-label">
                        Message type{' '}
                        <span className="set-calling-info" title="The type of audio message">
                          ⓘ
                        </span>
                      </span>
                      <button
                        type="button"
                        className="set-calling-sort-trigger"
                        aria-label="Sort by message type"
                        onClick={() => toggleSort('type')}
                      >
                        <span aria-hidden="true">↕</span>
                      </button>
                    </th>
                    <th>
                      <button
                        type="button"
                        className="set-calling-sort-trigger"
                        onClick={() => toggleSort('creator')}
                      >
                        Created by <span aria-hidden="true">↕</span>
                      </button>
                    </th>
                    <th>
                      <button
                        type="button"
                        className="set-calling-sort-trigger"
                        onClick={() => toggleSort('date')}
                      >
                        Created date <span aria-hidden="true">↕</span>
                      </button>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.length === 0 ? (
                    <tr>
                      <td colSpan={4} className="set-calling-existing-empty">
                        <svg
                          className="set-calling-empty-art"
                          viewBox="0 0 190 150"
                          role="img"
                          aria-label="No audio messages"
                        >
                          <path d="M20 112 91 73l78 39-77 35-72-35Z" fill="var(--brand-soft)" />
                          <ellipse
                            cx="92"
                            cy="111"
                            rx="29"
                            ry="14"
                            fill="var(--surface)"
                            stroke="var(--border-strong)"
                            strokeDasharray="3 3"
                          />
                          <path
                            d="M70 100 83 63l18 0 13 37"
                            fill="var(--surface)"
                            stroke="var(--border-strong)"
                            strokeDasharray="3 3"
                          />
                          <ellipse
                            cx="91"
                            cy="54"
                            rx="31"
                            ry="20"
                            transform="rotate(-12 91 54)"
                            fill="var(--surface)"
                            stroke="var(--border-strong)"
                            strokeWidth="4"
                          />
                          <ellipse
                            cx="91"
                            cy="54"
                            rx="23"
                            ry="13"
                            transform="rotate(-12 91 54)"
                            fill="var(--surface-2)"
                            stroke="var(--border)"
                            strokeWidth="2"
                          />
                          <path
                            d="m115 65 22 13q7 5 3 11l-3 5q-3 4-8 1l-22-14"
                            fill="var(--surface-2)"
                            stroke="var(--border-strong)"
                            strokeWidth="3"
                          />
                          <path
                            d="m126 27 5-9m7 17 10-4m-7 14 10 2"
                            stroke="var(--brand)"
                            strokeOpacity=".35"
                            strokeWidth="3"
                            strokeLinecap="round"
                          />
                        </svg>
                        <span>No audio messages found.</span>
                      </td>
                    </tr>
                  ) : (
                    filtered.map((item) => (
                      <tr key={item.id}>
                        <td>
                          <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2">
                            <span>{item.name}</span>
                            <button
                              type="button"
                              className="icon-btn crm-rounded-circle h-32 w-32"
                              aria-label={`Delete ${item.name}`}
                              onClick={() =>
                                setItems((prev) => prev.filter((row) => row.id !== item.id))
                              }
                            >
                              <CrmIcon name="trash" className="iconSize-16" />
                            </button>
                          </div>
                        </td>
                        <td>{item.type}</td>
                        <td>{item.creator}</td>
                        <td>{item.date}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </SetDialog>
  );
}
