'use client';

import { scopeCovers } from '@/features/auth/record-access';
import { useCallback, useState, type ReactNode } from 'react';
import { CrmModal, Field, FormDrawer, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import {
  COMMUNICATION_CHANNELS,
  deleteCall,
  deleteCommunication,
  deleteNote,
  deletePostalMail,
  updateCall,
  updateCommunication,
  updateNote,
  updatePostalMail,
  type CommunicationChannel,
  type UpdateCallBody,
  type UpdateCommunicationBody,
} from '@/features/activities/api.client';
import {
  callEditDirection,
  callNotesToSend,
  directionToSend,
} from '@/features/activities/callEdit';
import { useConfirm } from '@/components/crm/useConfirm';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { cancelMeeting, deleteMeeting, updateMeeting } from '@/features/meetings/api.client';
import { matchOption, optionLabel, useMeetingOptions } from '@/features/meetings/useMeetingOptions';
import type { TimelineItem } from '@/features/contacts/types';
import type { UpdateMeetingBody } from '@/features/meetings/types';
import {
  actionErrorText,
  fromLocalInput,
  TEXTAREA_STYLE,
  toLocalInput,
} from '@/features/contacts/ui/actions/shared';
import { htmlToText, textToHtml } from '@/features/inbox/format';
import type { PicklistOption } from '@/features/picklists/api.client';
import { cn } from '@/lib/utils/cn';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';

/**
 * Edit and delete notes, logged calls, communications and postal mail (HUB-327) from a record
 * timeline (PATCH / DELETE /activities/notes/:id, /calls/:id, /communications/:id and
 * /postal-mail/:id). Meetings: change the outcome in the card, edit outcome / type / notes,
 * cancel (a scheduled one, in Google) or delete for good (PATCH / DELETE /meetings/:id). Shared by the contact, company and deal
 * pages: `actions(item)` renders the Edit / Delete links of one timeline entry, `dialogs` the
 * drawers and the confirm dialog (render it once).
 */

type EditableKind = 'note' | 'call' | 'communication' | 'postal_mail' | 'meeting';

const KIND_NAMES: Record<EditableKind, string> = {
  note: 'note',
  call: 'call',
  communication: 'communication',
  postal_mail: 'postal mail',
  meeting: 'meeting',
};

const str = (value: unknown): string | null => (typeof value === 'string' && value ? value : null);

/** The activity behind an editable entry (`activityId`), or null for other entries. */
function editableActivity(item: TimelineItem): { kind: EditableKind; id: string } | null {
  if (!Object.hasOwn(KIND_NAMES, item.type)) return null;
  const id = str(item.activityId);
  return id ? { kind: item.type as EditableKind, id } : null;
}

function actorId(item: TimelineItem): string | null {
  const actor = item.actor;
  if (actor && typeof actor === 'object' && 'id' in actor) {
    return String((actor as { id: unknown }).id);
  }
  return null;
}

export function useTimelineEditing({
  outcomes,
  timeZone,
  disabled = false,
  onUpdated,
  onDeleted,
}: {
  /** Active `activity.callOutcome` options. */
  outcomes: PicklistOption[];
  timeZone: string;
  /** e.g. the record is deleted: no actions. */
  disabled?: boolean;
  onUpdated: (item: TimelineItem, patch: Partial<TimelineItem>) => void;
  onDeleted: (item: TimelineItem) => void;
}): { actions: (item: TimelineItem) => ReactNode; dialogs: ReactNode } {
  const me = useCurrentUser();
  // the last target stays set while its drawer / dialog animates closed
  const [target, setTarget] = useState<{ mode: 'edit' | 'delete'; item: TimelineItem } | null>(
    null,
  );
  const [open, setOpen] = useState(false);
  const close = useCallback(() => setOpen(false), []);
  const meetingOptions = useMeetingOptions();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const toast = useToast();

  // activities are owned by whoever logged them (the timeline `actor`); the API checks again
  const rule = me.permissionSet.rules.objects.activity;
  const canEdit = (item: TimelineItem) =>
    !disabled && me.role !== 'read_only' && scopeCovers(rule.edit, actorId(item), me);
  const canDelete = (item: TimelineItem) => canEdit(item) && rule.delete;

  const start = (mode: 'edit' | 'delete', item: TimelineItem) => {
    setTarget({ mode, item });
    setOpen(true);
  };

  const actions = (item: TimelineItem): ReactNode => {
    const activity = editableActivity(item);
    if (!activity) return null;
    const edit = canEdit(item);
    const del = canDelete(item);
    if (!edit && !del) return null;
    const what = KIND_NAMES[activity.kind];
    const meeting = activity.kind === 'meeting';
    const cancellable = meeting && item.origin === 'calendar' && item.status !== 'cancelled';
    return (
      <div className="crm-d-flex crm-gap-3 crm-align-items-center" style={{ marginTop: 8 }}>
        {meeting && edit && meetingOptions.outcomes.length ? (
          <select
            className="input"
            aria-label="Meeting outcome"
            style={{ width: 'auto', minHeight: 0, padding: '2px 8px' }}
            value={
              matchOption(meetingOptions.outcomes, str(item.outcome)) ?? str(item.outcome) ?? ''
            }
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => void setMeetingOutcome(item, activity.id, e.target.value || null)}
          >
            <option value="">Outcome</option>
            {meetingOptions.outcomes.map((o) => (
              <option key={o} value={o}>
                {o}
              </option>
            ))}
            {str(item.outcome) && !matchOption(meetingOptions.outcomes, str(item.outcome)) ? (
              <option value={str(item.outcome) ?? ''}>{optionLabel([], str(item.outcome))}</option>
            ) : null}
          </select>
        ) : null}
        {edit ? (
          <button
            type="button"
            className="crm-collapsible-card__action"
            aria-label={`Edit ${what}`}
            onClick={(e) => {
              e.stopPropagation();
              start('edit', item);
            }}
          >
            Edit
          </button>
        ) : null}
        {edit && cancellable ? (
          <button
            type="button"
            className="crm-collapsible-card__action"
            aria-label="Cancel meeting"
            onClick={(e) => {
              e.stopPropagation();
              void cancelScheduled(item, activity.id);
            }}
          >
            Cancel meeting
          </button>
        ) : null}
        {del ? (
          <button
            type="button"
            className="crm-collapsible-card__action"
            aria-label={`Delete ${what}`}
            onClick={(e) => {
              e.stopPropagation();
              start('delete', item);
            }}
          >
            Delete
          </button>
        ) : null}
      </div>
    );
  };

  const setMeetingOutcome = async (item: TimelineItem, id: string, outcome: string | null) => {
    try {
      const saved = await updateMeeting(id, { outcome });
      onUpdated(item, { outcome: saved.outcome });
      toast(outcome ? `Outcome updated: ${outcome}` : 'Outcome cleared');
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const cancelScheduled = async (item: TimelineItem, id: string) => {
    const ok = await confirm({
      title: 'Cancel this meeting?',
      message:
        'Google Calendar tells the attendees. The meeting stays on the timeline as cancelled.',
      confirmLabel: 'Cancel meeting',
      danger: true,
    });
    if (!ok) return;
    try {
      await cancelMeeting(id);
      onUpdated(item, { status: 'cancelled' });
      toast('Meeting cancelled');
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    }
  };

  const item = target?.item ?? null;
  const activity = item ? editableActivity(item) : null;
  const dialogs = (
    <>
      {confirmDialog}
      <EditMeetingDrawer
        open={open && target?.mode === 'edit' && activity?.kind === 'meeting'}
        onClose={close}
        item={activity?.kind === 'meeting' ? item : null}
        outcomes={meetingOptions.outcomes}
        types={meetingOptions.types}
        onUpdated={onUpdated}
      />
      <EditNoteDrawer
        open={open && target?.mode === 'edit' && activity?.kind === 'note'}
        onClose={close}
        item={activity?.kind === 'note' ? item : null}
        onUpdated={onUpdated}
      />
      <EditCallDrawer
        open={open && target?.mode === 'edit' && activity?.kind === 'call'}
        onClose={close}
        item={activity?.kind === 'call' ? item : null}
        outcomes={outcomes}
        timeZone={timeZone}
        onUpdated={onUpdated}
      />
      <EditMessageDrawer
        open={open && target?.mode === 'edit' && isMessage(activity?.kind)}
        onClose={close}
        item={isMessage(activity?.kind) ? item : null}
        timeZone={timeZone}
        onUpdated={onUpdated}
      />
      <DeleteActivityDialog
        open={open && target?.mode === 'delete'}
        onClose={close}
        item={item}
        onDeleted={(deleted) => {
          setOpen(false);
          onDeleted(deleted);
        }}
      />
    </>
  );

  return { actions, dialogs };
}

function EditNoteDrawer({
  open,
  onClose,
  item,
  onUpdated,
}: {
  open: boolean;
  onClose: () => void;
  item: TimelineItem | null;
  onUpdated: (item: TimelineItem, patch: Partial<TimelineItem>) => void;
}) {
  const toast = useToast();
  const loadedHtml = item ? (str(item.bodyHtml) ?? '') : '';

  const onSubmit = async (d: Record<string, string>) => {
    if (!item) return;
    const activity = editableActivity(item);
    if (!activity) return;
    const text = (d.body ?? '').trim();
    if (!text) return false;
    if (text === htmlToText(loadedHtml).trim()) return; // nothing changed: just close
    try {
      const saved = await updateNote(activity.id, { bodyHtml: textToHtml(text) });
      onUpdated(item, { bodyHtml: saved.bodyHtml });
      toast('Note updated');
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="timelineEditNoteModal"
      title="Edit note"
      submitLabel="Save note"
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      <Field label="Note" htmlFor="timelineNoteBody" error="Write a note first.">
        {item ? (
          <SnippetTextarea
            key={item.id}
            className="input"
            id="timelineNoteBody"
            name="body"
            rows={8}
            required
            maxLength={100_000}
            style={TEXTAREA_STYLE}
            defaultValue={htmlToText(loadedHtml)}
          />
        ) : null}
      </Field>
    </FormDrawer>
  );
}

/** Outcome, type and notes of a meeting (PATCH /meetings/:id; saved in the CRM only). */
function EditMeetingDrawer({
  open,
  onClose,
  item,
  outcomes,
  types,
  onUpdated,
}: {
  open: boolean;
  onClose: () => void;
  item: TimelineItem | null;
  outcomes: string[];
  types: string[];
  onUpdated: (item: TimelineItem, patch: Partial<TimelineItem>) => void;
}) {
  const toast = useToast();
  const outcome = matchOption(outcomes, str(item?.outcome)) ?? str(item?.outcome) ?? '';
  const meetingType = matchOption(types, str(item?.meetingType)) ?? str(item?.meetingType) ?? '';
  const notes = str(item?.body) ? htmlToText(str(item?.body) ?? '').trim() : '';
  const withCurrent = (list: string[], current: string) =>
    current && !list.includes(current) ? [...list, current] : list;

  const onSubmit = async (d: Record<string, string>) => {
    if (!item) return;
    const activity = editableActivity(item);
    if (!activity) return;
    const body: UpdateMeetingBody = {};
    if ((d.outcome ?? '') !== outcome) body.outcome = d.outcome || null;
    if (types.length && (d.meetingType ?? '') !== meetingType)
      body.meetingType = d.meetingType || null;
    const nextNotes = (d.notes ?? '').trim();
    if (nextNotes !== notes) body.notes = nextNotes ? textToHtml(nextNotes) : null;
    if (Object.keys(body).length === 0) return; // nothing changed: just close
    try {
      const saved = await updateMeeting(activity.id, body);
      onUpdated(item, {
        outcome: saved.outcome,
        meetingType: saved.meetingType ?? null,
        body: saved.notes,
      });
      toast('Meeting updated');
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="timelineEditMeetingModal"
      title="Edit meeting"
      size="wide"
      submitLabel="Save meeting"
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      {item ? (
        <div className="form-grid" key={item.id}>
          {outcomes.length ? (
            <Field label="Meeting outcome" htmlFor="timelineMeetingOutcome">
              <select
                className="input"
                id="timelineMeetingOutcome"
                name="outcome"
                defaultValue={outcome}
              >
                <option value="">--</option>
                {withCurrent(outcomes, outcome).map((o) => (
                  <option key={o} value={o}>
                    {o}
                  </option>
                ))}
              </select>
            </Field>
          ) : null}
          {types.length ? (
            <Field label="Call and meeting type" htmlFor="timelineMeetingType">
              <select
                className="input"
                id="timelineMeetingType"
                name="meetingType"
                defaultValue={meetingType}
              >
                <option value="">--</option>
                {withCurrent(types, meetingType).map((o) => (
                  <option key={o} value={o}>
                    {o}
                  </option>
                ))}
              </select>
            </Field>
          ) : null}
          <Field label="Notes" htmlFor="timelineMeetingNotes" className="span-2">
            <SnippetTextarea
              className="input"
              id="timelineMeetingNotes"
              name="notes"
              rows={6}
              maxLength={50_000}
              style={TEXTAREA_STYLE}
              defaultValue={notes}
            />
          </Field>
        </div>
      ) : null}
    </FormDrawer>
  );
}

function EditCallDrawer({
  open,
  onClose,
  item,
  outcomes,
  timeZone,
  onUpdated,
}: {
  open: boolean;
  onClose: () => void;
  item: TimelineItem | null;
  outcomes: PicklistOption[];
  timeZone: string;
  onUpdated: (item: TimelineItem, patch: Partial<TimelineItem>) => void;
}) {
  const toast = useToast();
  // A call logged with no direction (QA D-11) starts on "--", not "Outbound".
  const direction = callEditDirection(item);
  const outcome = str(item?.outcome);
  // Call notes are HTML (the Log call composer is rich text); the box edits them as text.
  const notes = str(item?.notes) ? htmlToText(str(item?.notes) ?? '').trim() : '';
  const seconds = typeof item?.durationSeconds === 'number' ? item.durationSeconds : null;
  const minutes = seconds !== null ? String(Math.round((seconds / 60) * 100) / 100) : '';
  const occurredLocal = item ? toLocalInput(new Date(item.occurredAt), timeZone) : '';
  // live outcomes, plus the call's current one when it was archived since
  const outcomeOptions = outcomes.map((o) => ({ value: o.value, label: o.label }));
  if (outcome && !outcomeOptions.some((o) => o.value === outcome)) {
    outcomeOptions.push({ value: outcome, label: outcome });
  }

  const onSubmit = async (d: Record<string, string>) => {
    if (!item) return;
    const activity = editableActivity(item);
    if (!activity) return;
    const body: UpdateCallBody = {};

    const nextDirection = directionToSend(direction, d.direction);
    if (nextDirection) body.direction = nextDirection;

    const nextOutcome = d.outcome || null;
    if (nextOutcome !== outcome) body.outcome = nextOutcome;

    if ((d.occurredAt ?? '') !== occurredLocal) {
      const at = fromLocalInput(d.occurredAt ?? '', timeZone);
      if (!at) {
        toast('Enter when the call happened', 'danger');
        return false;
      }
      body.occurredAt = at;
    }

    const rawMinutes = (d.minutes ?? '').trim();
    if (rawMinutes !== minutes) {
      const n = rawMinutes ? Number(rawMinutes) : null;
      if (n !== null && (!Number.isFinite(n) || n < 0 || n > 1440)) {
        toast('Duration must be between 0 and 1440 minutes', 'danger');
        return false;
      }
      body.durationSeconds = n === null ? null : Math.round(n * 60);
    }

    const nextNotes = callNotesToSend(notes, d.notes);
    if (nextNotes !== undefined) body.notes = nextNotes;

    if (Object.keys(body).length === 0) return; // nothing changed: just close
    try {
      const saved = await updateCall(activity.id, body);
      onUpdated(item, {
        direction: saved.direction,
        durationSeconds: saved.durationSeconds,
        outcome: saved.outcome,
        notes: saved.notes,
        occurredAt: saved.occurredAt,
      });
      toast('Call updated');
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="timelineEditCallModal"
      title="Edit call"
      size="wide"
      submitLabel="Save call"
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      {item ? (
        <div className="form-grid" key={item.id}>
          <Field label="Direction" htmlFor="timelineCallDirection">
            <select
              className="input"
              id="timelineCallDirection"
              name="direction"
              defaultValue={direction}
            >
              {direction ? null : <option value="">--</option>}
              <option value="outbound">Outbound</option>
              <option value="inbound">Inbound</option>
            </select>
          </Field>
          <Field label="Outcome" htmlFor="timelineCallOutcome">
            <select
              className="input"
              id="timelineCallOutcome"
              name="outcome"
              defaultValue={outcome ?? ''}
            >
              <option value="">--</option>
              {outcomeOptions.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </Field>
          <Field label="Date and time" htmlFor="timelineCallAt">
            <input
              className="input"
              id="timelineCallAt"
              type="datetime-local"
              name="occurredAt"
              required
              defaultValue={occurredLocal}
            />
          </Field>
          <Field label="Duration (minutes)" htmlFor="timelineCallMinutes">
            <input
              className="input"
              id="timelineCallMinutes"
              type="number"
              name="minutes"
              min={0}
              max={1440}
              step="any"
              defaultValue={minutes}
            />
          </Field>
          <Field label="Notes" htmlFor="timelineCallNotes" className="span-2">
            <SnippetTextarea
              className="input"
              id="timelineCallNotes"
              name="notes"
              rows={5}
              maxLength={50_000}
              style={TEXTAREA_STYLE}
              defaultValue={notes}
            />
          </Field>
        </div>
      ) : null}
      <p className="crm-fs-8 crm-text-muted crm-mt-3">Times are in {timeZone}.</p>
    </FormDrawer>
  );
}

/** Communications and postal mail share one edit drawer. */
const isMessage = (kind: EditableKind | undefined) =>
  kind === 'communication' || kind === 'postal_mail';

/** Edit a communication (channel, time, message) or postal mail (date sent, description). */
function EditMessageDrawer({
  open,
  onClose,
  item,
  timeZone,
  onUpdated,
}: {
  open: boolean;
  onClose: () => void;
  item: TimelineItem | null;
  timeZone: string;
  onUpdated: (item: TimelineItem, patch: Partial<TimelineItem>) => void;
}) {
  const toast = useToast();
  const isCommunication = item?.type === 'communication';
  const what = isCommunication ? 'communication' : 'postal mail';
  const channel = str(item?.channel) ?? 'sms';
  const body = str(item?.body) ?? '';
  const occurredLocal = item ? toLocalInput(new Date(item.occurredAt), timeZone) : '';

  const onSubmit = async (d: Record<string, string>) => {
    if (!item) return;
    const activity = editableActivity(item);
    if (!activity) return;
    const patch: UpdateCommunicationBody = {};
    const nextBody = (d.body ?? '').trim();
    if (!nextBody) return false;
    if (nextBody !== body.trim()) patch.body = nextBody;
    if ((d.occurredAt ?? '') !== occurredLocal) {
      const at = fromLocalInput(d.occurredAt ?? '', timeZone);
      if (!at) {
        toast(`Enter when the ${what} was sent`, 'danger');
        return false;
      }
      patch.occurredAt = at;
    }
    if (isCommunication && d.channel && d.channel !== channel) {
      patch.channel = d.channel as CommunicationChannel;
    }
    if (Object.keys(patch).length === 0) return; // nothing changed: just close
    try {
      if (activity.kind === 'communication') {
        const saved = await updateCommunication(activity.id, patch);
        onUpdated(item, { body: saved.body, occurredAt: saved.occurredAt, channel: saved.channel });
        toast('Communication updated');
      } else {
        const saved = await updatePostalMail(activity.id, {
          body: patch.body,
          occurredAt: patch.occurredAt,
        });
        onUpdated(item, { body: saved.body, occurredAt: saved.occurredAt });
        toast('Postal mail updated');
      }
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id="timelineEditMessageModal"
      title={`Edit ${what}`}
      size="wide"
      submitLabel={isCommunication ? 'Save communication' : 'Save postal mail'}
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
    >
      {item ? (
        <div className="form-grid" key={item.id}>
          {isCommunication ? (
            <Field label="Channel" htmlFor="timelineMessageChannel">
              <select
                className="input"
                id="timelineMessageChannel"
                name="channel"
                defaultValue={channel}
              >
                {COMMUNICATION_CHANNELS.map((c) => (
                  <option key={c.value} value={c.value}>
                    {c.label}
                  </option>
                ))}
              </select>
            </Field>
          ) : null}
          <Field
            label={isCommunication ? 'Date and time' : 'Date sent'}
            htmlFor="timelineMessageAt"
          >
            <input
              className="input"
              id="timelineMessageAt"
              type="datetime-local"
              name="occurredAt"
              required
              defaultValue={occurredLocal}
            />
          </Field>
          <Field
            label={isCommunication ? 'Message' : 'Description'}
            htmlFor="timelineMessageBody"
            className="span-2"
            error="This can't be empty."
          >
            <SnippetTextarea
              className="input"
              id="timelineMessageBody"
              name="body"
              rows={6}
              required
              maxLength={50_000}
              style={TEXTAREA_STYLE}
              defaultValue={body}
            />
          </Field>
        </div>
      ) : null}
      <p className="crm-fs-8 crm-text-muted crm-mt-3">Times are in {timeZone}.</p>
    </FormDrawer>
  );
}

function DeleteActivityDialog({
  open,
  onClose,
  item,
  onDeleted,
}: {
  open: boolean;
  onClose: () => void;
  item: TimelineItem | null;
  onDeleted: (item: TimelineItem) => void;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState(false);
  const activity = item ? editableActivity(item) : null;
  const what = activity ? KIND_NAMES[activity.kind] : 'note';

  const onDelete = async () => {
    if (busy || !item || !activity) return;
    setBusy(true);
    try {
      if (activity.kind === 'note') await deleteNote(activity.id);
      else if (activity.kind === 'call') await deleteCall(activity.id);
      else if (activity.kind === 'meeting') await deleteMeeting(activity.id);
      else if (activity.kind === 'communication') await deleteCommunication(activity.id);
      else await deletePostalMail(activity.id);
      toast(`${what.charAt(0).toUpperCase()}${what.slice(1)} deleted`);
      onDeleted(item);
    } catch (err) {
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="timelineDeleteActivityModal" open={open} onClose={busy ? () => {} : onClose}>
      <ModalHeader id="timelineDeleteActivityModal" title={`Delete ${what}?`} onClose={onClose} />
      <div className="modal__body">
        <p>
          This {what} will be removed from the timeline of every record it is linked to.
          {item?.type === 'meeting' && item.origin === 'calendar' && item.status !== 'cancelled'
            ? ' It is cancelled in Google Calendar first, and the attendees are told.'
            : ''}
        </p>
      </div>
      <div className="modal__footer">
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          onClick={onClose}
          disabled={busy}
        >
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          onClick={onDelete}
          disabled={busy}
          aria-busy={busy}
          style={{ background: 'var(--danger)', borderColor: 'var(--danger)' }}
        >
          Delete
        </button>
      </div>
    </CrmModal>
  );
}
