'use client';

import { useEffect, useMemo, useRef, useState, type RefObject } from 'react';
import { NOT_AVAILABLE_YET } from '@/components/crm/ComposerSelect';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import type { CustomSelectOption } from '@/components/crm/CustomSelect';
import {
  ComposeRichText,
  htmlIsEmpty,
  type ComposeRichTextHandle,
} from '@/components/crm/ComposeRichText';
import { DraggablePopup } from '@/components/crm/DraggablePopup';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { MultiCustomSelect } from '@/components/crm/MultiCustomSelect';
import { RecipientChips } from '@/components/crm/RecipientChips';
import { useToast } from '@/components/crm/ToastProvider';
import { EmailInsertBar } from './EmailInsertBar';
import {
  attachmentProblem,
  connectGmail,
  getMyMailbox,
  listEmailTemplates,
  previewEmailTemplate,
  sendEmail,
  uploadAttachment,
} from '@/features/inbox/api.client';
import { htmlToText, newIdempotencyKey } from '@/features/inbox/format';
import type {
  EmailTemplate,
  EmailTemplatePreview,
  EmailUpload,
  MyMailbox,
  RecipientWarning,
  SendEmailBody,
  SendEmailRecordLink,
} from '@/features/inbox/types';
import { getBusinessSettings } from '@/features/settings/api.client';
import {
  emailTextDefaultsFromSettings,
  wrapEmailHtmlWithDefaults,
  type EmailTextDefaults,
} from '@/features/settings/emailDefaults';
import { createTask } from '@/features/tasks/api.client';
import { errorText, isApiError } from '@/lib/api/errors';
import { isUsable, needsReconnect } from '@/lib/utils/connection';
import { cn } from '@/lib/utils/cn';
import { AssociatedRecordsPanel } from './AssociatedRecordsPanel';
import {
  emailLinksCapped,
  initialRecipients,
  MAX_TASK_EMAIL_LINKS,
  seedAssociations,
  taskLinksCapped,
  type AssocRecord,
} from './assocTypes';
import { FollowUpTaskControls, followUpDueDate, type FollowUpDueKey } from './FollowUpTaskControls';
import { actionErrorText, useOpenCount, useUserPrefs } from './shared';
import { snippetTargetFor } from '@/features/snippets/model';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const EMAIL_ASSOC_TYPES = new Set(['contact', 'company', 'deal']);

export type EmailRecipientOption = CustomSelectOption & {
  /** Used for template merge fields when this recipient is selected. */
  contactId?: string;
};

const warningText = (w: RecipientWarning[]) =>
  `Queued. Note: ${w
    .map((x) => `${x.email} ${x.status === 'bounced' ? 'bounced before' : 'unsubscribed earlier'}`)
    .join(', ')}.`;

interface Chosen {
  template: EmailTemplate;
  preview: EmailTemplatePreview;
}

/**
 * Send an email from my Gmail (POST /inbox/send). Centered HubSpot-style popup.
 */
export function SendEmailDrawer({
  open,
  onClose,
  contactId,
  contactEmail,
  recipientOptions,
  dealId,
  recordLink,
  recordName,
  initialAssociations,
  signature,
  onSent,
  initialSubject = '',
  initialBodyHtml = '',
  composer,
  prefillAllRecipients = false,
}: {
  /**
   * EV2 (event, lead and ticket pages): To starts with every recipient option, as the design's
   * composer pre-fills all of the record's contacts. Off: the primary contact only.
   */
  prefillAllRecipients?: boolean;
  /** What the composer opens with (a sequence's manual email task, QA 16 Oct #143). */
  initialSubject?: string;
  initialBodyHtml?: string;
  open: boolean;
  onClose: () => void;
  contactId?: string;
  contactEmail?: string | null;
  recipientOptions?: EmailRecipientOption[];
  dealId?: string;
  recordLink?: SendEmailRecordLink;
  recordName?: string;
  /** Extra records to pre-check (e.g. contact's companies). */
  initialAssociations?: AssocRecord[];
  signature: string | null;
  onSent: () => void;
  /** Contacts: the design's floating window. */
  composer?: RefObject<ComposerWindowHandle | null>;
}) {
  const toast = useToast();
  const prefs = useUserPrefs();
  const [mailbox, setMailbox] = useState<MyMailbox | null>(null);
  const [composeKey, setComposeKey] = useState(newIdempotencyKey);
  const [templates, setTemplates] = useState<EmailTemplate[] | null>(null);
  const [chosen, setChosen] = useState<Chosen | null>(null);
  const [loadingTemplate, setLoadingTemplate] = useState(false);
  const [subject, setSubject] = useState('');
  const [bodyHtml, setBodyHtml] = useState('');
  const [connecting, setConnecting] = useState(false);
  const [selectedTo, setSelectedTo] = useState<string[]>([]);
  const [showCc, setShowCc] = useState(false);
  const [showBcc, setShowBcc] = useState(false);
  const [selectedCc, setSelectedCc] = useState<string[]>([]);
  const [selectedBcc, setSelectedBcc] = useState<string[]>([]);
  const [busy, setBusy] = useState(false);
  const [track, setTrack] = useState(true);
  /** Which address boxes hold text that isn't an email: Send waits, or it would be dropped. */
  const [badBoxes, setBadBoxes] = useState<{ to?: boolean; cc?: boolean; bcc?: boolean }>({});
  const [followUp, setFollowUp] = useState(false);
  const [followDue, setFollowDue] = useState<FollowUpDueKey>('biz3');
  const [customDueDate, setCustomDueDate] = useState('');
  const [taskType, setTaskType] = useState('todo');
  const [uploads, setUploads] = useState<EmailUpload[]>([]);
  const [editorKey, setEditorKey] = useState(0);
  const [emailDefaults, setEmailDefaults] = useState<EmailTextDefaults | null>(null);
  const composeRef = useRef<ComposeRichTextHandle>(null);
  const primaryAssoc: AssocRecord | null = useMemo(() => {
    if (!recordLink) return null;
    return {
      type: recordLink.type,
      id: recordLink.id,
      displayName: recordName ?? recordLink.type,
      subtitle: contactEmail ?? null,
    };
  }, [recordLink, recordName, contactEmail]);
  const seedAssoc = useMemo(
    () => seedAssociations(primaryAssoc, initialAssociations).slice(0, MAX_TASK_EMAIL_LINKS),
    [primaryAssoc, initialAssociations],
  );
  const [assoc, setAssoc] = useState<AssocRecord[]>(seedAssoc);

  const pickerOptions = useMemo(() => {
    const fromProps = (recipientOptions ?? []).map(({ value, label }) => ({
      value: value.trim().toLowerCase(),
      label,
    }));
    const fallback = contactEmail?.trim().toLowerCase();
    if (
      fallback &&
      EMAIL_RE.test(fallback) &&
      !fromProps.some((o) => o.value === fallback) &&
      !recipientOptions?.length
    ) {
      fromProps.push({ value: fallback, label: fallback });
    }
    const seen = new Set<string>();
    return fromProps.filter((o) => {
      if (!o.value || seen.has(o.value)) return false;
      seen.add(o.value);
      return true;
    });
  }, [recipientOptions, contactEmail]);

  const mergeContactId = useMemo(() => {
    const match = recipientOptions?.find(
      (o) => selectedTo.includes(o.value.toLowerCase()) && o.contactId,
    );
    return match?.contactId ?? contactId;
  }, [recipientOptions, selectedTo, contactId]);

  const openCount = useOpenCount(open, () => {
    setComposeKey(newIdempotencyKey());
    setChosen(null);
    setSubject(initialSubject);
    setBodyHtml(initialBodyHtml);
    setShowCc(false);
    setShowBcc(false);
    setSelectedCc([]);
    setSelectedBcc([]);
    setTrack(true);
    setBadBoxes({});
    setFollowUp(false);
    setFollowDue('biz3');
    setCustomDueDate('');
    setTaskType('todo');
    setUploads([]);
    setAssoc(seedAssoc);
    setEditorKey(0);
  });

  useEffect(() => {
    if (!open) return;
    setSelectedTo(initialRecipients(pickerOptions, contactEmail, prefillAllRecipients));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, openCount]);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    getMyMailbox().then(
      (box) => {
        if (alive) setMailbox(box);
      },
      (err) => {
        if (alive) toast(errorText(err), 'danger');
      },
    );
    return () => {
      alive = false;
    };
  }, [open, toast]);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    getBusinessSettings().then(
      (s) => {
        if (!cancelled) setEmailDefaults(emailTextDefaultsFromSettings(s));
      },
      () => {
        if (!cancelled) setEmailDefaults(null);
      },
    );
    return () => {
      cancelled = true;
    };
  }, [open]);

  useEffect(() => {
    if (!open || templates !== null) return;
    listEmailTemplates().then(
      (res) => setTemplates(res.data),
      () => setTemplates([]),
    );
  }, [open, templates]);

  const blocked = mailbox !== null && !isUsable(mailbox);
  const reconnect = needsReconnect(mailbox);
  const missing = chosen?.preview.missingFields ?? [];
  const fromLabel = mailbox?.emailAddress ? mailbox.emailAddress : 'Your connected Gmail';

  const onConnect = async () => {
    setConnecting(true);
    try {
      const { authUrl } = await connectGmail();
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
      setConnecting(false);
    }
  };

  const pickTemplate = async (id: string) => {
    const template = templates?.find((t) => t.id === id);
    if (!template) return;
    if (!mergeContactId) {
      const hasMerge = /\{\{[^}]+\}\}/.test(`${template.subject}\n${template.bodyHtml}`);
      if (hasMerge) {
        toast(
          'This template has merge fields. Pick a CRM contact as the recipient first.',
          'danger',
        );
        return;
      }
      setChosen(null);
      setSubject(template.subject);
      setBodyHtml(template.bodyHtml);
      setEditorKey((k) => k + 1);
      return;
    }
    setLoadingTemplate(true);
    try {
      const preview = await previewEmailTemplate(id, { contactId: mergeContactId, dealId });
      setChosen({ template, preview });
      setSubject(preview.subject);
      setBodyHtml(preview.bodyHtml);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setLoadingTemplate(false);
    }
  };

  const insertIntoBody = (html: string) => {
    if (chosen) {
      setChosen({
        ...chosen,
        preview: { ...chosen.preview, bodyHtml: `${chosen.preview.bodyHtml}${html}` },
      });
      return;
    }
    composeRef.current?.insertHtml(html);
  };

  const clearTemplate = () => {
    if (!chosen) return;
    setBodyHtml(chosen.preview.bodyHtml);
    setChosen(null);
    setEditorKey((k) => k + 1);
  };

  const cleanEmails = (list: string[]) => [
    ...new Set(list.map((s) => s.trim().toLowerCase()).filter(Boolean)),
  ];

  const submit = async () => {
    if (busy || loadingTemplate) return;
    const to = cleanEmails(selectedTo);
    const bad = to.find((a) => !EMAIL_RE.test(a));
    if (!to.length || bad) {
      toast(bad ? `Not an email address: ${bad}` : 'Add a recipient', 'danger');
      return;
    }
    const ccList = cleanEmails(selectedCc);
    const bccList = cleanEmails(selectedBcc);
    const badCc = ccList.find((a) => !EMAIL_RE.test(a));
    const badBcc = bccList.find((a) => !EMAIL_RE.test(a));
    if (badCc || badBcc) {
      toast(`Not an email address: ${badCc ?? badBcc}`, 'danger');
      return;
    }
    if (missing.length) {
      toast(`These merge fields have no value for this contact: ${missing.join(', ')}`, 'danger');
      return;
    }
    const subjectLine = subject.trim();
    // EV2: an event, lead or ticket stays pinned too (API #330).
    const emailLinks: SendEmailRecordLink[] = emailLinksCapped(assoc);
    const body: SendEmailBody = {
      to,
      idempotencyKey: composeKey,
      track,
      ...(emailLinks.length ? { links: emailLinks } : recordLink ? { links: [recordLink] } : {}),
      ...(uploads.length ? { attachmentIds: uploads.map((u) => u.attachmentId) } : {}),
    };
    if (ccList.length) body.cc = ccList;
    if (bccList.length) body.bcc = bccList;

    if (chosen && mergeContactId) {
      body.template = {
        templateId: chosen.template.id,
        contactId: mergeContactId,
        ...(dealId && { dealId }),
      };
      if (subjectLine) body.subject = subjectLine;
    } else {
      if (!subjectLine || htmlIsEmpty(bodyHtml)) {
        toast('Write a subject and a message', 'danger');
        return;
      }
      // Editor HTML is already escaped — never run textToHtml on it (double-escape).
      // Wrap with account email defaults so font/color survive into Gmail (contenteditable
      // inheritance alone is not inlined into the HTML).
      body.subject = subjectLine;
      const styled = emailDefaults ? wrapEmailHtmlWithDefaults(bodyHtml, emailDefaults) : bodyHtml;
      body.bodyHtml = signature ? `${styled}<p><br></p>${signature}` : styled;
    }

    setBusy(true);
    try {
      const res = await sendEmail(body);
      if (followUp) {
        const links = taskLinksCapped(assoc);
        if (links.length) {
          await createTask({
            title: `Follow up: ${subjectLine || recordName || 'email'}`,
            taskType,
            dueDate: followUpDueDate(followDue, prefs.timeZone, customDueDate),
            links,
          });
        }
      }
      if (res.warnings.length) toast(warningText(res.warnings), 'info', { durationMs: null });
      else toast(`Email queued to ${body.to.join(', ')}`);
      onSent();
      onClose();
    } catch (err) {
      if (isApiError(err) && (err.code === 'MAILBOX_NEEDS_REAUTH' || err.isConflict)) {
        const fresh = await getMyMailbox().catch(() => null);
        if (fresh && !isUsable(fresh)) {
          setMailbox(fresh);
          return;
        }
        if (err.code === 'MAILBOX_NEEDS_REAUTH') {
          setMailbox({
            connected: true,
            emailAddress: fresh?.emailAddress ?? null,
            status: 'needs_reauth',
            lastSyncedAt: null,
            lastError: null,
          });
          return;
        }
      }
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  if (blocked) {
    return (
      <CrmModal id="contactEmailConnect" open={open} onClose={onClose}>
        <ModalHeader id="contactEmailConnect" title="Send email" onClose={onClose} />
        <div className="modal__body">
          <h3 className="crm-mb-2" style={{ fontSize: 16, fontWeight: 600 }}>
            {reconnect ? 'Reconnect your Gmail' : 'Connect your Gmail'}
          </h3>
          <p className="crm-text-muted crm-mb-4">
            {reconnect
              ? `Your Gmail connection (${mailbox?.emailAddress ?? 'Gmail'}) stopped working. Reconnect it to send email from the CRM.`
              : 'Email is sent from your own Gmail. Connect it first to email contacts from the CRM.'}
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            onClick={onConnect}
            disabled={connecting}
            aria-busy={connecting}
          >
            {reconnect ? 'Reconnect Gmail' : 'Connect Gmail'}
          </button>
        </div>
      </CrmModal>
    );
  }

  const canSend =
    selectedTo.length > 0 &&
    subject.trim().length > 0 &&
    (chosen ? missing.length === 0 : !htmlIsEmpty(bodyHtml)) &&
    !loadingTemplate &&
    !Object.values(badBoxes).some(Boolean);

  const followUpRow = (
    <FollowUpTaskControls
      enabled={followUp}
      onEnabledChange={setFollowUp}
      taskType={taskType}
      onTaskTypeChange={setTaskType}
      dueKey={followDue}
      onDueKeyChange={setFollowDue}
      customDate={customDueDate}
      onCustomDateChange={setCustomDueDate}
      timeZone={prefs.timeZone}
      composer={Boolean(composer)}
    />
  );

  return (
    <DraggablePopup
      composer={composer}
      id="contactEmailModal"
      open={open}
      onClose={onClose}
      confirmClose={
        !chosen && (!htmlIsEmpty(bodyHtml) || subject.trim().length > 0 || uploads.length > 0)
      }
      title="Email"
      size="xl"
      footer={
        composer ? (
          <>
            <span className="acx-split">
              <button
                type="button"
                className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
                disabled={!canSend || busy}
                aria-busy={busy}
                onClick={() => void submit()}
              >
                Send
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--primary acx-split__more"
                aria-label="More send options"
                title={NOT_AVAILABLE_YET}
                disabled
              >
                <svg viewBox="0 0 24 24" aria-hidden className="acx-caret">
                  <path d="M7 10l5 5 5-5z" fill="currentColor" />
                </svg>
              </button>
            </span>
            <label className="acx-track">
              <input type="checkbox" checked={track} onChange={(e) => setTrack(e.target.checked)} />
              <span>Track email</span>
            </label>
          </>
        ) : (
          <>
            <button
              type="button"
              className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
              disabled={!canSend || busy}
              aria-busy={busy}
              onClick={() => void submit()}
            >
              Send
            </button>
            <div style={{ flex: 1, minWidth: 200 }}>{followUpRow}</div>
          </>
        )
      }
    >
      {composer ? (
        <div className="acx-stack">
          <div className="acx-field acx-field--row">
            <span className="acx-field__label">From</span>
            <span className="acx-static">{fromLabel}</span>
          </div>
          <div className="acx-field acx-field--row">
            <span className="acx-field__label">To</span>
            <RecipientChips
              value={selectedTo}
              onChange={setSelectedTo}
              options={pickerOptions}
              onInvalidChange={(to) => setBadBoxes((cur) => ({ ...cur, to }))}
            />
            <span className="acx-cc">
              {showCc ? null : (
                <button type="button" onClick={() => setShowCc(true)}>
                  Cc
                </button>
              )}
              {showBcc ? null : (
                <button type="button" onClick={() => setShowBcc(true)}>
                  Bcc
                </button>
              )}
            </span>
          </div>
          {showCc ? (
            <div className="acx-field acx-field--row">
              <span className="acx-field__label">Cc</span>
              <RecipientChips
                value={selectedCc}
                onChange={setSelectedCc}
                options={pickerOptions}
                label="Add Cc"
                autoFocus
                onInvalidChange={(cc) => setBadBoxes((cur) => ({ ...cur, cc }))}
              />
            </div>
          ) : null}
          {showBcc ? (
            <div className="acx-field acx-field--row">
              <span className="acx-field__label">Bcc</span>
              <RecipientChips
                value={selectedBcc}
                onChange={setSelectedBcc}
                options={pickerOptions}
                label="Add Bcc"
                autoFocus
                onInvalidChange={(bcc) => setBadBoxes((cur) => ({ ...cur, bcc }))}
              />
            </div>
          ) : null}
          <div className="acx-field acx-field--row">
            <span className="acx-field__label">Subject</span>
            <input
              className="acx-input acx-input--bare"
              id="emailSubject"
              maxLength={998}
              placeholder="Subject"
              aria-label="Subject"
              autoComplete="off"
              value={subject}
              onChange={(e) => setSubject(e.target.value.replace(/[\r\n]+/g, ' '))}
            />
          </div>
        </div>
      ) : (
        <>
          <div className="activity-popup__address">
            <div className="activity-popup__address-head">
              <span className="activity-popup__row-label">To</span>
              <div className="activity-popup__row-actions">
                {!showCc ? (
                  <button
                    type="button"
                    className="activity-popup__link-btn"
                    onClick={() => setShowCc(true)}
                  >
                    Cc
                  </button>
                ) : null}
                {!showBcc ? (
                  <button
                    type="button"
                    className="activity-popup__link-btn"
                    onClick={() => setShowBcc(true)}
                  >
                    Bcc
                  </button>
                ) : null}
              </div>
            </div>
            <MultiCustomSelect
              id="emailTo"
              name="to"
              placeholder="Select or type an email"
              value={selectedTo}
              options={pickerOptions}
              onChange={setSelectedTo}
              selectedText="recipients"
              menuMinWidth={320}
              allowCustomEmail
            />
          </div>

          {showCc ? (
            <div className="activity-popup__address">
              <div className="activity-popup__address-head">
                <span className="activity-popup__row-label">Cc</span>
              </div>
              <MultiCustomSelect
                id="emailCc"
                name="cc"
                placeholder="Search or type an email"
                value={selectedCc}
                options={pickerOptions}
                onChange={setSelectedCc}
                selectedText="recipients"
                menuMinWidth={320}
                allowCustomEmail
              />
            </div>
          ) : null}

          {showBcc ? (
            <div className="activity-popup__address">
              <div className="activity-popup__address-head">
                <span className="activity-popup__row-label">Bcc</span>
              </div>
              <MultiCustomSelect
                id="emailBcc"
                name="bcc"
                placeholder="Search or type an email"
                value={selectedBcc}
                options={pickerOptions}
                onChange={setSelectedBcc}
                selectedText="recipients"
                menuMinWidth={320}
                allowCustomEmail
              />
            </div>
          ) : null}

          <div className="activity-popup__address">
            <div className="activity-popup__address-head">
              <span className="activity-popup__row-label">From</span>
            </div>
            <span className="activity-popup__from">{fromLabel}</span>
          </div>

          <div>
            <div className="activity-popup__row-label" style={{ marginBottom: 4 }}>
              Subject
            </div>
            <input
              className="activity-popup__subject"
              id="emailSubject"
              maxLength={998}
              placeholder="Subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value.replace(/[\r\n]+/g, ' '))}
            />
          </div>
        </>
      )}

      <EmailInsertBar
        templates={templates}
        templatesLoading={loadingTemplate}
        onPickTemplate={(id) => void pickTemplate(id)}
        hasTemplate={Boolean(chosen)}
        onClearTemplate={clearTemplate}
        contactId={mergeContactId}
        recipientEmail={selectedTo[0]}
        contactName={
          recipientOptions?.find((o) => o.contactId === mergeContactId)?.label ??
          (contactId ? recordName : undefined) ??
          'this contact'
        }
        dealId={dealId}
        mailboxId={mailbox?.id}
        mailboxReady={mailbox !== null && isUsable(mailbox)}
        onInsertHtml={insertIntoBody}
        onToast={toast}
        showMeetings={Boolean(composer)}
      />

      {chosen ? (
        <div>
          <textarea
            className="input"
            rows={10}
            readOnly
            style={{ height: 'auto', minHeight: 160, lineHeight: 1.5 }}
            value={htmlToText(chosen.preview.bodyHtml)}
          />
          {missing.length ? (
            <span className="field__hint">
              No value for this contact: {missing.join(', ')}. Fill these in on the contact first.
            </span>
          ) : (
            <span className="crm-fs-8 crm-text-muted">
              Merge fields are filled in for this contact when the email is sent.
            </span>
          )}
        </div>
      ) : (
        <ComposeRichText
          ref={composeRef}
          openKey={`${openCount}-${editorKey}`}
          value={bodyHtml}
          onChange={setBodyHtml}
          label="Message"
          placeholder="Write your email…"
          minHeight={composer ? 102 : 200}
          plannedTools={Boolean(composer)}
          textDefaults={emailDefaults}
          snippetTarget={snippetTargetFor(
            recordLink,
            mergeContactId,
            // A company's first deal need not be the contact's: without a contact, leave it out.
            mergeContactId ? dealId : undefined,
          )}
          onPickFile={async (file) => {
            const bytes = uploads.reduce((n, u) => n + u.sizeBytes, 0);
            const problem = attachmentProblem(file, bytes);
            if (problem) {
              toast(problem, 'danger');
              return;
            }
            try {
              const up = await uploadAttachment(file);
              setUploads((prev) => [...prev, up]);
              toast(`Attached ${file.name}`);
            } catch (err) {
              toast(actionErrorText(err), 'danger');
            }
          }}
        />
      )}

      {uploads.length ? (
        <ul className="activity-popup__attachments">
          {uploads.map((u) => (
            <li key={u.attachmentId}>
              <span>
                {u.filename} ({Math.max(1, Math.round(u.sizeBytes / 1024))} KB)
              </span>
              <button
                type="button"
                className="btn-crm btn-crm--ghost btn-crm--sm"
                onClick={() =>
                  setUploads((prev) => prev.filter((x) => x.attachmentId !== u.attachmentId))
                }
              >
                Remove
              </button>
            </li>
          ))}
        </ul>
      ) : null}

      <AssociatedRecordsPanel
        className={composer ? 'acx-row' : undefined}
        value={assoc}
        onChange={setAssoc}
        locked={primaryAssoc}
        allowTypes={EMAIL_ASSOC_TYPES}
        maxSelected={MAX_TASK_EMAIL_LINKS}
      />

      {composer ? followUpRow : null}

      {signature && !chosen ? (
        <p className="crm-fs-8 crm-text-muted crm-mb-0">Your signature is added at the end.</p>
      ) : null}
    </DraggablePopup>
  );
}
