'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import {
  createAppNotificationRule,
  deleteAppNotificationRule,
  listAppNotificationRules,
  updateAppNotificationRule,
  type AppNotificationAudience,
  type AppNotificationReminder,
  type AppNotificationRule,
  type AppNotificationRuleBody,
  type AppNotificationType,
  type Connection,
} from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DialogHead, SetDialog } from '../settings-ui';
import {
  AUDIENCE_OPTIONS,
  NOTIFICATION_TYPE_OPTIONS,
  REMINDER_OPTIONS,
  appsLabel,
  assignedToLabel,
  frequencyLabel,
  notificationTypeLabel,
} from './admin-model';
import { useDirectory } from './directory';
import { Icon, connectionLogo } from './icons';
import { PeoplePicker } from './PeoplePicker';
import { DesignDropdown } from './ui';

/*
 * Settings › Connected Apps › Notifications (design #apps-notifications, the "Create an app
 * notification" drawer wizard and the delete modal). Rules are kept by the API, which sends
 * them through the bell / email per each recipient's Notification Preferences.
 */

const PREFERENCES_HREF = '/settings/notifications';

type SortKey = 'name' | 'type' | 'apps' | 'assigned' | 'frequency';

const EMPTY: AppNotificationRuleBody = {
  name: '',
  type: 'app_install',
  reminder: null,
  appIds: [],
  audience: 'specific',
  userIds: [],
  teamIds: [],
};

function useRules() {
  const [state, setState] = useState<
    | { status: 'loading' }
    | { status: 'error'; message: string }
    | { status: 'ready'; rows: AppNotificationRule[] }
  >({ status: 'loading' });
  const seq = useRef(0);
  const load = useCallback(async (quiet = false) => {
    const run = ++seq.current;
    if (!quiet) setState({ status: 'loading' });
    try {
      const res = await listAppNotificationRules();
      if (run === seq.current) setState({ status: 'ready', rows: res.data });
    } catch (err) {
      if (run === seq.current) setState({ status: 'error', message: errorText(err) });
    }
  }, []);
  useEffect(() => {
    void load();
  }, [load]);
  return { state, reload: load };
}

export function NotificationsTab({ connections }: { connections: Connection[] }) {
  const toast = useToast();
  const { state, reload } = useRules();
  const [sort, setSort] = useState<{ key: SortKey; asc: boolean } | null>(null);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [editing, setEditing] = useState<AppNotificationRule | 'new' | null>(null);
  const [deleting, setDeleting] = useState<AppNotificationRule | null>(null);
  const [busy, setBusy] = useState(false);

  const nameOf = useCallback(
    (id: string) => connections.find((c) => c.id === id)?.name,
    [connections],
  );
  const rows = useMemo(() => (state.status === 'ready' ? state.rows : []), [state]);
  const ordered = useMemo(() => {
    if (!sort) return rows;
    const text = (r: AppNotificationRule) => {
      switch (sort.key) {
        case 'type':
          return notificationTypeLabel(r.type);
        case 'apps':
          return appsLabel(r, nameOf);
        case 'assigned':
          return assignedToLabel(r);
        case 'frequency':
          return frequencyLabel(r);
        default:
          return r.name;
      }
    };
    return [...rows].sort((a, b) => {
      const c = text(a).localeCompare(text(b), undefined, { sensitivity: 'base', numeric: true });
      return sort.asc ? c : -c;
    });
  }, [rows, sort, nameOf]);
  const totalPages = Math.max(1, Math.ceil(ordered.length / pageSize));
  const current = Math.min(page, totalPages);
  const shown = ordered.slice((current - 1) * pageSize, current * pageSize);

  const head = (key: SortKey, label: string, className: string) => {
    const active = sort?.key === key;
    return (
      <th
        scope="col"
        className={className}
        aria-sort={active ? (sort?.asc ? 'ascending' : 'descending') : undefined}
        onClick={() => {
          setSort({ key, asc: active ? !sort?.asc : true });
          setPage(1);
        }}
      >
        <div className="th-content">
          <span>{label}</span>
          <span className="sort-icon-wrap">
            {active ? sort?.asc ? '↑' : '↓' : <Icon name="sort" size={14} />}
          </span>
        </div>
      </th>
    );
  };

  const confirmDelete = async () => {
    if (!deleting || busy) return;
    setBusy(true);
    try {
      await deleteAppNotificationRule(deleting.id);
      toast('Notification deleted successfully', 'info');
      setDeleting(null);
      await reload(true);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <div className="ca-notifications-heading crm-d-flex crm-justify-content-between crm-align-items-start crm-mb-3">
        <div>
          <h2 id="heading-connected-notifications">Notifications</h2>
          <p>
            Create, manage, and assign how you’re notified by your connected apps. Note: newly
            installed apps must be added to notification configurations
          </p>
        </div>
        <button
          type="button"
          className="btn-crm btn-crm--primary ca-notifications-create"
          aria-haspopup="dialog"
          onClick={() => setEditing('new')}
        >
          Create new notification
        </button>
      </div>

      <div className="card set-table-card ca-notifications-table-wrap">
        {rows.length > 0 ? (
          <table
            className="set-table su-table ca-notifications-table"
            aria-label="Connected app notifications"
          >
            <thead>
              <tr>
                {head('name', 'Notification', 'col-notif')}
                {head('type', 'Notification Type', 'col-type')}
                {head('apps', 'Apps', 'col-apps')}
                {head('assigned', 'Assigned To', 'col-assigned')}
                {head('frequency', 'Frequency', 'col-freq')}
                <th scope="col" className="col-actions crm-text-end">
                  <span className="crm-visually-hidden">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {shown.map((r) => (
                <tr key={r.id} data-notif-id={r.id}>
                  <td>
                    <span className="crm-fs-7">{r.name}</span>
                  </td>
                  <td>
                    <span className="crm-fs-8">{notificationTypeLabel(r.type)}</span>
                  </td>
                  <td className="crm-fs-8 crm-text-muted">{appsLabel(r, nameOf)}</td>
                  <td>
                    <button type="button" className="ca-link-btn" onClick={() => setEditing(r)}>
                      {assignedToLabel(r)}
                    </button>
                  </td>
                  <td className="crm-fs-8 crm-text-muted">{frequencyLabel(r)}</td>
                  <td className="crm-text-end">
                    <DesignDropdown
                      className="ca-notif-actions-dropdown"
                      toggleClassName="btn-crm btn-crm--outline btn-crm--sm ca-notif-actions-btn"
                      menuClassName="dropdown__menu--right"
                      toggle={
                        <>
                          <span>Actions</span>
                          <Icon name="caret-down" size={14} />
                        </>
                      }
                    >
                      {(close) => (
                        <>
                          <button
                            type="button"
                            className="dropdown__item"
                            onClick={() => {
                              close();
                              setEditing(r);
                            }}
                          >
                            Manage notification
                          </button>
                          <button
                            type="button"
                            className="dropdown__item text-danger ca-notif-delete-item"
                            onClick={() => {
                              close();
                              setDeleting(r);
                            }}
                          >
                            Delete notification
                          </button>
                        </>
                      )}
                    </DesignDropdown>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : state.status === 'loading' ? (
          <p className="su-empty" role="status">
            Loading notifications…
          </p>
        ) : state.status === 'error' ? (
          <div className="ca-state" role="alert">
            <p className="crm-mb-0">Couldn’t load notifications. {state.message}</p>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={() => void reload()}
            >
              Try again
            </button>
          </div>
        ) : (
          <div className="ca-notifications-empty">
            <div className="ca-notifications-empty-art">
              <svg
                width="68"
                height="68"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="crm-text-muted"
                aria-hidden="true"
              >
                <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
                <path d="M13.73 21a2 2 0 0 1-3.46 0" />
              </svg>
            </div>
            <p className="crm-text-muted crm-fs-7 crm-mt-2">
              You haven’t created any app notifications.
            </p>
          </div>
        )}
      </div>

      <nav
        className="wf-pager ca-pager crm-mt-3"
        aria-label="Notifications pagination"
        hidden={rows.length === 0}
      >
        <button
          type="button"
          className="wf-pager__btn"
          disabled={current <= 1}
          aria-label="Previous page"
          onClick={() => setPage(current - 1)}
        >
          <Icon name="chevron-left" size={14} />
          Prev
        </button>
        <span className="wf-pager__nums">
          {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
            <button
              key={p}
              type="button"
              className={cn('wf-pager__num', p === current && 'is-active')}
              aria-current={p === current ? 'page' : undefined}
              onClick={() => setPage(p)}
            >
              {p}
            </button>
          ))}
        </span>
        <button
          type="button"
          className="wf-pager__btn"
          disabled={current >= totalPages}
          aria-label="Next page"
          onClick={() => setPage(current + 1)}
        >
          Next
          <Icon name="chevron-right" size={14} />
        </button>
        <DesignDropdown
          className="ca-page-size-dropdown"
          toggleClassName="wf-pager__btn wf-pager__size"
          toggleLabel="Rows per page"
          menuClassName="dropdown__menu--up dropdown__menu--right"
          toggle={
            <>
              <span>{pageSize}</span> per page
              <Icon name="chevron-down" size={14} />
            </>
          }
        >
          {(close) =>
            [10, 25, 50].map((n) => (
              <button
                key={n}
                type="button"
                className={cn('dropdown__item', n === pageSize && 'is-selected')}
                onClick={() => {
                  setPageSize(n);
                  setPage(1);
                  close();
                }}
              >
                {n} per page
              </button>
            ))
          }
        </DesignDropdown>
      </nav>

      <NotificationWizard
        key={editing === null ? 'closed' : editing === 'new' ? 'new' : editing.id}
        rule={editing}
        connections={connections}
        onClose={() => setEditing(null)}
        onSaved={() => void reload(true)}
      />

      <SetDialog
        open={deleting !== null}
        onClose={() => {
          if (!busy) setDeleting(null);
        }}
        labelledBy="del-notif-title"
        className="ca-delete-notif-modal"
      >
        <div className="ca-delete-notif-modal-content">
          <h2 className="ca-delete-notif-title" id="del-notif-title">
            Delete notification?
          </h2>
          <p className="ca-delete-notif-desc">
            By deleting this notification, you’ll remove your configured settings and won’t be
            notified when any of your integrated apps get{' '}
            <span>{deleting ? notificationTypeLabel(deleting.type) : ''}</span>.
          </p>
          <div className="ca-delete-notif-actions">
            <button
              type="button"
              className={cn('btn-crm btn-crm--danger', busy && 'is-loading')}
              disabled={busy}
              aria-busy={busy}
              onClick={() => void confirmDelete()}
            >
              Delete notification
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--secondary"
              disabled={busy}
              onClick={() => setDeleting(null)}
            >
              Cancel
            </button>
          </div>
        </div>
      </SetDialog>
    </>
  );
}

const STEPS = ['Basic info', 'Choose apps', 'Assign users'] as const;

function StepCheck() {
  return (
    <svg
      className="ca-step-check-icon"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  );
}

/** The 3-step drawer: "Create an app notification" / "Manage app notification". */
function NotificationWizard({
  rule,
  connections,
  onClose,
  onSaved,
}: {
  rule: AppNotificationRule | 'new' | null;
  connections: Connection[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  const open = rule !== null;
  const existing = rule && rule !== 'new' ? rule : null;
  const directory = useDirectory(open);
  const [step, setStep] = useState(1);
  const [body, setBody] = useState<AppNotificationRuleBody>(() =>
    existing
      ? {
          name: existing.name,
          type: existing.type,
          reminder: existing.reminder,
          appIds: existing.appIds,
          audience: existing.audience,
          userIds: existing.userIds,
          teamIds: existing.teamIds,
        }
      : EMPTY,
  );
  const [typeChosen, setTypeChosen] = useState(existing !== null);
  const [reminderInvalid, setReminderInvalid] = useState(false);
  const [busy, setBusy] = useState(false);
  const nameRef = useRef<HTMLInputElement>(null);

  const isDisconnect = body.type === 'app_disconnect';
  // Apps that are gone keep their place while managing, so saving does not drop them silently.
  const appRows = useMemo(() => {
    const rows: Array<{ id: string; name: string; c: Connection | null }> = connections.map(
      (c) => ({ id: c.id, name: c.name, c }),
    );
    for (const id of body.appIds) {
      if (!rows.some((r) => r.id === id)) rows.push({ id, name: `${id} (removed)`, c: null });
    }
    return rows.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
  }, [connections, body.appIds]);
  const allApps = appRows.length > 0 && appRows.every((r) => body.appIds.includes(r.id));
  const someApps = body.appIds.length > 0 && !allApps;
  const selectAllRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (selectAllRef.current) selectAllRef.current.indeterminate = someApps;
  }, [someApps, step]);

  const close = () => {
    if (!busy) onClose();
  };

  const next = () => {
    if (step === 1) {
      if (!body.name.trim()) {
        nameRef.current?.focus();
        toast('Please enter a notification name', 'danger');
        return;
      }
      if (!typeChosen) {
        toast('Please select a notification type', 'danger');
        return;
      }
      if (isDisconnect && !body.reminder) {
        setReminderInvalid(true);
        toast('Please select a notification reminder', 'danger');
        return;
      }
    }
    if (step === 2 && isDisconnect && body.appIds.length === 0) {
      toast('Choose at least one app', 'danger');
      return;
    }
    setStep((s) => Math.min(3, s + 1));
  };

  const save = async () => {
    if (busy) return;
    if (body.audience === 'specific' && body.userIds.length + body.teamIds.length === 0) {
      toast('Choose at least one user or team', 'danger');
      return;
    }
    const payload: AppNotificationRuleBody = {
      name: body.name.trim(),
      type: body.type,
      reminder: isDisconnect ? body.reminder : null,
      appIds: isDisconnect ? body.appIds : [],
      audience: body.audience,
      userIds: body.audience === 'specific' ? body.userIds : [],
      teamIds: body.audience === 'specific' ? body.teamIds : [],
    };
    setBusy(true);
    try {
      if (existing) {
        await updateAppNotificationRule(existing.id, payload);
        toast(`Notification "${payload.name}" updated successfully`, 'success');
      } else {
        await createAppNotificationRule(payload);
        toast(`Notification "${payload.name}" created successfully`, 'success');
      }
      onSaved();
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const title = existing ? 'Manage app notification' : 'Create an app notification';

  return (
    <SetDialog
      open={open}
      onClose={close}
      drawer
      labelledBy="create-notif-title"
      className="ca-notification-drawer"
    >
      <form
        noValidate
        className="ca-drawer-wrap"
        onSubmit={(e) => {
          e.preventDefault();
          if (step < 3) next();
          else void save();
        }}
      >
        <DialogHead id="create-notif-title" title={title} onClose={close} />

        <div className="ca-wizard-stepper-wrap">
          <div className="ca-wizard-stepper-track">
            <div
              className="ca-wizard-stepper-progress"
              style={{ width: step === 1 ? '0%' : step === 2 ? '50%' : '100%' }}
            />
          </div>
          <div className="ca-wizard-steps">
            {STEPS.map((label, i) => (
              <div
                key={label}
                className={cn(
                  'ca-wizard-step',
                  step === i + 1 && 'is-active',
                  step > i + 1 && 'is-complete',
                )}
                aria-current={step === i + 1 ? 'step' : undefined}
              >
                <span className="ca-step-num">
                  <StepCheck />
                </span>
                <span className="ca-step-title">{label}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="set-modal__body">
          {step === 1 ? (
            <div className="ca-wizard-page">
              <div className="field crm-mb-3">
                <label className="field__label" htmlFor="notif-name-input">
                  Notification name <span className="crm-text-danger">*</span>
                </label>
                <input
                  ref={nameRef}
                  type="text"
                  id="notif-name-input"
                  className="input"
                  placeholder="e.g. test"
                  maxLength={100}
                  required
                  value={body.name}
                  onChange={(e) => setBody({ ...body, name: e.target.value })}
                />
              </div>
              <div className="field crm-mb-3">
                <label className="field__label" htmlFor="notif-type-select">
                  Notification type <span className="crm-text-danger">*</span>
                </label>
                <CustomSelect
                  id="notif-type-select"
                  className="crm-w-100"
                  placeholder="Select notification type"
                  value={typeChosen ? body.type : ''}
                  options={NOTIFICATION_TYPE_OPTIONS}
                  menuActions={false}
                  onChange={(v) => {
                    if (!v) return;
                    setTypeChosen(true);
                    setBody({ ...body, type: v as AppNotificationType });
                  }}
                />
                <span className="crm-fs-8 crm-text-subtle crm-d-block crm-mt-1">
                  Please specify an event type
                </span>
              </div>
              {isDisconnect ? (
                <div className="field crm-mb-3">
                  <label className="field__label" htmlFor="notif-reminder-select">
                    Notification reminder <span className="crm-text-danger">*</span>
                  </label>
                  <CustomSelect
                    id="notif-reminder-select"
                    className={cn('crm-w-100', reminderInvalid && 'is-invalid')}
                    placeholder="Select notification reminder"
                    value={body.reminder ?? ''}
                    options={REMINDER_OPTIONS}
                    menuActions={false}
                    onChange={(v) => {
                      if (!v) return;
                      setReminderInvalid(false);
                      setBody({ ...body, reminder: v as AppNotificationReminder });
                    }}
                  />
                  <span className="crm-fs-8 crm-text-subtle crm-d-block crm-mt-1">
                    How often you are reminded while a chosen app stays disconnected or needs
                    attention.
                  </span>
                </div>
              ) : null}
            </div>
          ) : null}

          {step === 2 ? (
            <div className="ca-wizard-page">
              {!isDisconnect ? (
                <div className="alert alert--neutral crm-my-4">
                  <p className="crm-fs-7 crm-mb-0">
                    This notification is not tied to specific apps. You&apos;ll be subscribed to
                    this notification for all apps, so you do not have to choose a specific one.
                  </p>
                </div>
              ) : (
                <div className="ca-choose-apps-wrap">
                  <p className="ca-choose-apps-desc crm-mb-3">
                    Choose which app(s) you would like to create an App Disconnect notification for.
                  </p>
                  <div className="ca-choose-apps-table">
                    <div className="ca-choose-apps-head">
                      <label
                        className="check ca-choose-apps-select-all-check"
                        title="Select all apps"
                      >
                        <input
                          ref={selectAllRef}
                          type="checkbox"
                          aria-label="Select all apps"
                          checked={allApps}
                          onChange={(e) =>
                            setBody({
                              ...body,
                              appIds: e.target.checked ? appRows.map((r) => r.id) : [],
                            })
                          }
                        />
                        <span className="check__box" />
                      </label>
                      <span className="ca-choose-apps-head-title crm-d-flex crm-align-items-center crm-gap-1">
                        App Name
                      </span>
                    </div>
                    <div className="ca-choose-apps-list">
                      {appRows.map((r) => {
                        const checked = body.appIds.includes(r.id);
                        const logo = r.c ? connectionLogo(r.c) : null;
                        return (
                          <label
                            key={r.id}
                            className={cn('ca-choose-app-row', checked && 'is-selected')}
                          >
                            <span className="check">
                              <input
                                type="checkbox"
                                checked={checked}
                                onChange={(e) =>
                                  setBody({
                                    ...body,
                                    appIds: e.target.checked
                                      ? [...body.appIds, r.id]
                                      : body.appIds.filter((x) => x !== r.id),
                                  })
                                }
                              />
                              <span className="check__box" />
                            </span>
                            <div className="ca-choose-app-item crm-d-flex crm-align-items-center crm-gap-2">
                              {logo ? (
                                <span
                                  className="ca-choose-app-logo"
                                  style={{ background: logo.bg, color: '#ffffff' }}
                                >
                                  <Icon name={logo.icon} size={14} />
                                </span>
                              ) : null}
                              <span className="ca-choose-app-name">{r.name}</span>
                            </div>
                          </label>
                        );
                      })}
                      {appRows.length === 0 ? (
                        <p className="crm-fs-8 crm-text-muted crm-p-3 crm-mb-0">
                          No connected apps yet.
                        </p>
                      ) : null}
                    </div>
                  </div>
                </div>
              )}
            </div>
          ) : null}

          {step === 3 ? (
            <div className="ca-wizard-page">
              <p className="crm-fs-7 crm-text-muted crm-mb-3">
                Customize the level of access users and teams have to notifications.
              </p>
              <div className="alert alert--neutral crm-mb-4">
                <div className="crm-d-flex crm-align-items-start crm-gap-2">
                  <Icon name="info" size={16} />
                  <div>
                    <strong>Notification Preferences required</strong>
                    <p className="crm-fs-8 crm-text-muted crm-mb-1">
                      Notifications will only be delivered to recipients who have the Integrations
                      category enabled in their Notification Preferences. Remind recipients to check
                      their settings.
                    </p>
                    <Link href={PREFERENCES_HREF} className="set-link-inline crm-fs-8">
                      Go to Notification Preferences
                    </Link>
                  </div>
                </div>
              </div>
              <div className="ca-notif-access-radios crm-mb-3" role="radiogroup">
                {AUDIENCE_OPTIONS.map((o) => (
                  <label
                    key={o.value}
                    className="crm-d-flex crm-align-items-center crm-gap-2 crm-mb-2"
                  >
                    <input
                      type="radio"
                      name="notif_access"
                      value={o.value}
                      checked={body.audience === o.value}
                      onChange={() =>
                        setBody({ ...body, audience: o.value as AppNotificationAudience })
                      }
                    />
                    <span className="crm-fs-7">{o.label}</span>
                  </label>
                ))}
              </div>
              {body.audience === 'specific' ? (
                <div className="ca-notif-specific-wrap">
                  <PeoplePicker
                    directory={directory}
                    userIds={body.userIds}
                    teamIds={body.teamIds}
                    idPrefix="notif"
                    onChange={(n) => setBody({ ...body, userIds: n.userIds, teamIds: n.teamIds })}
                  />
                </div>
              ) : null}
            </div>
          ) : null}
        </div>

        <div className="set-modal__foot ca-notif-drawer-foot crm-d-flex crm-justify-content-between crm-align-items-center">
          <div className="ca-wizard-foot-left crm-d-flex crm-gap-2">
            {step === 2 ? (
              <button type="button" className="btn-crm btn-crm--outline" onClick={() => setStep(1)}>
                Back
              </button>
            ) : null}
            {step === 3 ? (
              <>
                <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
                  Cancel
                </button>
                <button
                  type="submit"
                  className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
                  disabled={busy}
                  aria-busy={busy}
                >
                  Apply
                </button>
              </>
            ) : null}
          </div>
          <div className="ca-wizard-foot-right crm-d-flex crm-gap-2">
            {step === 1 ? (
              <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
                Cancel
              </button>
            ) : null}
            {step === 3 ? (
              <button type="button" className="btn-crm btn-crm--outline" onClick={() => setStep(2)}>
                Back
              </button>
            ) : null}
            {step < 3 ? (
              <button type="submit" className="btn-crm btn-crm--primary">
                Next
              </button>
            ) : null}
          </div>
        </div>
      </form>
    </SetDialog>
  );
}
