'use client';

import Link from 'next/link';
import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  linkCompanyCompany,
  linkCompanyContact,
  linkContactCompany,
  linkDealCompany,
  listRelatedCompanies,
  setAssociationLabels,
  unlinkCompanyCompany,
  unlinkCompanyContact,
  unlinkDealCompany,
} from '@/features/associations/api.client';
import type { AssociationLinkInput, RelatedCompany } from '@/features/associations/types';
import { AddAssociationDrawer } from '@/features/associations/ui/AddAssociationDrawer';
import { AddAssociationDesignDrawer } from '@/features/associations/ui/AddAssociationDesignDrawer';
import { createContact } from '@/features/contacts/api.client';
import { createDeal } from '@/features/deals/api.client';
import type { CustomProperties } from '@/types/api';
import { AssociationLabelsDrawer } from '@/features/associations/ui/AssociationLabelsDrawer';
import { AssociationLabelsModal } from '@/features/associations/ui/AssociationLabelsModal';
import { findDealLink } from '@/features/associations/linkLookup';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { canOpenSettingsHref } from '@/features/permission-sets/property-settings';
import { assocMenu, DesignAssocRow } from '@/features/record-layouts/ui/DesignAssocRow';
import type { PreviewTarget } from '@/features/record-pages/AssociatedPreview';
import { propertiesHref } from '@/features/record-pages/usePanelParam';
import { DesignAssocEmpty } from '@/features/associations/ui/DesignAssocEmpty';
import { RemoveAssociationDialog } from '@/features/associations/ui/RemoveAssociationDialog';
import { associationErrorText } from '@/features/associations/ui/shared';
import type { Company } from '@/features/companies/types';
import { CollapsibleCard } from '@/features/contacts/ui/CollapsibleCard';
import { CompanyCard, CompanyCardTitle } from '@/features/contacts/ui/CollapsibleCard';
import { LpIcon } from '@/features/list-page/ui/LpIcon';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import { contactRecord, dealRecord, type DateText } from '@/features/record-layouts/assocRecords';
import { cardTitle, type CardView } from '@/features/record-layouts/ui/AssocLines';
import {
  CardListFooter,
  CardQuickFilters,
  contactFromList,
  dealFromList,
  useCardList,
} from '@/features/record-layouts/ui/CardList';
import { withCardGear } from '@/features/record-layouts/ui/CardGear';
import { companyInitials, formatMoney } from './format';

type LinkedContact = Company['contacts'][number];
type LinkedDeal = Company['deals'][number];

type Action =
  | { kind: 'addContact' }
  | { kind: 'addDeal' }
  | { kind: 'addCompany' }
  | { kind: 'contactLabels'; contact: LinkedContact }
  | { kind: 'dealLabels'; deal: LinkedDeal }
  | { kind: 'companyLabels'; related: RelatedCompany }
  | { kind: 'removeContact'; contact: LinkedContact }
  | { kind: 'removeCompany'; related: RelatedCompany }
  | { kind: 'removeDeal'; deal: LinkedDeal };

const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 8 };
const REMOVE: CSSProperties = { marginLeft: 'auto', flex: 'none' };

/**
 * The Contacts, Related companies and Deals cards of the company page, with add / remove
 * association and link labels. Contacts link through POST /companies/:id/contacts (optional
 * labels, no primary flag); other companies through POST /companies/:id/companies (paired labels,
 * read from this company's side); deals through POST /deals/:dealId/companies (optional labels).
 * `onChanged` reloads the company after every change.
 */
export function CompanyAssociations({
  company,
  canEdit,
  onChanged,
  look = 'page',
  onPreview,
  only,
  cards,
  dateText,
}: {
  company: Company;
  /** Edit rights on the company: without them the cards are read-only. */
  canEdit: boolean;
  onChanged: () => Promise<void>;
  /**
   * `preview` (B4, Companies' list preview): each block a card (`CollapsibleCard`, drawn as the
   * design's section there) and each record the design's preview row (`lp-pv__assoc`,
   * list-page.js:3608). Default: the company page's cards.
   */
  look?: 'page' | 'preview';
  /** R7: a row's "Preview" (record pages); none: no Preview item. */
  onPreview?: (target: NonNullable<PreviewTarget>) => void;
  /**
   * Page look only: one of the three cards (the record layout's `r-contacts`, `r-related`,
   * `r-deals`), so the page can place each where its layout says; all three when left out.
   */
  only?: 'contacts' | 'related' | 'deals';
  /**
   * The cards' layout settings and gear (company record page only). The design's preview has no
   * gear on these cards, so `preview` ignores them.
   */
  cards?: { contacts?: CardView; related?: CardView; deals?: CardView };
  /** Dates in the viewer's format, for saved Create / Close date properties. */
  dateText?: DateText;
}) {
  const show = (card: 'contacts' | 'related' | 'deals') => !only || only === card;
  const date: DateText = dateText ?? ((iso) => iso?.slice(0, 10) ?? '--');
  const toast = useToast();
  const me = useCurrentUser();
  // the last action stays set while its drawer / dialog animates closed
  const [action, setAction] = useState<Action | null>(null);
  const [open, setOpen] = useState(false);

  const start = (next: Action) => {
    setAction(next);
    setOpen(true);
  };
  const close = useCallback(() => setOpen(false), []);
  const is = (kind: Action['kind']) => open && action?.kind === kind;

  // Batch 2: a page card saved with filters / quick filters / sort loads its own list
  // (`CardView.list`); otherwise the company's preview, as before. A reload of the company
  // reloads it.
  const contactList = useCardList({
    fromType: 'company',
    fromId: company.id,
    toType: 'contact',
    settings: (look === 'page' && cards?.contacts?.list) || null,
    refreshKey: company,
  });
  const dealList = useCardList({
    fromType: 'company',
    fromId: company.id,
    toType: 'deal',
    settings: (look === 'page' && cards?.deals?.list) || null,
    refreshKey: company,
  });
  const contacts = contactList.rows ? contactList.rows.map(contactFromList) : company.contacts;
  const deals = dealList.rows ? dealList.rows.map(dealFromList) : company.deals;
  const contactsCount = contactList.rows
    ? contactList.total
    : (company.contactsCount ?? contacts.length);

  // company to company links are not part of GET /companies/:id: they load on their own
  const [related, setRelated] = useState<RelatedCompany[] | null>(null);
  const [relatedFailed, setRelatedFailed] = useState(false);
  const reloadRelated = useCallback(async () => {
    try {
      setRelated(await listRelatedCompanies(company.id));
      setRelatedFailed(false);
    } catch {
      setRelatedFailed(true);
    }
  }, [company.id]);
  // only the card that shows them loads them
  const wantsRelated = !only || only === 'related';
  useEffect(() => {
    if (wantsRelated) void reloadRelated();
  }, [reloadRelated, wantsRelated]);

  /* ------------------------------------------------------------ API calls */

  /** `quiet` (R6b's panel): no toast or reload; the panel does both once for every record. */
  const addContact = async (
    { record, isPrimary, labelIds }: AssociationLinkInput,
    quiet = false,
  ) => {
    await linkCompanyContact(company.id, {
      contactId: record.id,
      ...(labelIds.length ? { labelIds } : {}),
    });
    // CQS1 #140: Primary makes this company the contact's primary company. The company's route
    // takes no primary; the contact's links again and moves the primary. The link above stands
    // either way, so a failure here is said on its own and the contact still counts as associated.
    if (isPrimary) {
      try {
        await linkContactCompany(record.id, { companyId: company.id, isPrimary: true });
      } catch (err) {
        toast(
          `${record.title} was associated, but not made primary: ${associationErrorText(err)}`,
          'danger',
          { durationMs: 8000 },
        );
      }
    }
    if (quiet) return;
    toast(`${record.title} associated with ${company.name}`);
    await onChanged();
  };

  const addDeal = async ({ record, labelIds }: AssociationLinkInput, quiet = false) => {
    await linkDealCompany(record.id, {
      companyId: company.id,
      ...(labelIds.length ? { labelIds } : {}),
    });
    if (quiet) return;
    toast(`${record.title} associated with ${company.name}`);
    await onChanged();
  };

  /** R6b, Create new: a contact linked to this company in the same call. */
  const createLinkedContact = async (v: Record<string, string>, custom: CustomProperties) => {
    const created = await createContact({
      email: v.email || null,
      firstName: v.firstName || null,
      companyIds: [company.id],
      ...(Object.keys(custom).length ? { customProperties: custom } : {}),
    });
    return [created.firstName, created.lastName].filter(Boolean).join(' ') || created.email || '';
  };

  /** R6b, Create new: a deal linked to this company in the same call. */
  const createLinkedDeal = async (v: Record<string, string>, custom: CustomProperties) => {
    const created = await createDeal({
      name: v.name ?? '',
      ...(v.amount ? { amount: v.amount } : {}),
      companyIds: [company.id],
      ...(Object.keys(custom).length ? { customProperties: custom } : {}),
    });
    return created.name;
  };

  /**
   * With the link's id, PUT /associations/:id/labels replaces the labels (so they can be
   * removed); without it, linking again can only add labels.
   */
  const saveContactLabels = async (
    contact: LinkedContact,
    labelIds: string[],
    /** R6a: the design's dialog toasts itself ("Association labels updated"). */
    quiet = false,
  ) => {
    if (contact.associationId) await setAssociationLabels(contact.associationId, labelIds);
    else await linkCompanyContact(company.id, { contactId: contact.id, labelIds });
    if (!quiet) toast(`Labels saved for ${contact.name}`);
    await onChanged();
  };

  /** R6a: the deal row's link, found when its labels dialog opens (findDealLink). */
  const dealLinkRef = useRef<string | null>(null);
  const loadDealLabels = async (deal: LinkedDeal) => {
    dealLinkRef.current = null;
    const link = await findDealLink('company', company.id, deal.id);
    dealLinkRef.current = link.associationId;
    return link.labels;
  };
  const saveDealLabels = async (labelIds: string[]) => {
    if (!dealLinkRef.current) throw new Error('Labels could not be loaded. Try again.');
    await setAssociationLabels(dealLinkRef.current, labelIds);
    await onChanged();
  };

  const addCompany = async ({ record, labelIds, inverseLabelIds }: AssociationLinkInput) => {
    await linkCompanyCompany(company.id, {
      companyId: record.id,
      ...(labelIds.length ? { labelIds } : {}),
      ...(inverseLabelIds.length ? { inverseLabelIds } : {}),
    });
    toast(`${record.title} associated with ${company.name}`);
    await reloadRelated();
    await onChanged();
  };

  /** The labels are chosen on this company (`viewerId`), so the other one reads the pair. */
  const saveCompanyLabels = async (
    other: RelatedCompany,
    labelIds: string[],
    inverseLabelIds: string[],
  ) => {
    await setAssociationLabels(other.associationId, labelIds, {
      inverseLabelIds,
      viewerId: company.id,
    });
    toast(`Labels saved for ${other.name}`);
    await reloadRelated();
    await onChanged();
  };

  const removeCompany = async (other: RelatedCompany) => {
    await unlinkCompanyCompany(company.id, other.id);
    toast(`${other.name} removed from ${company.name}`);
    setOpen(false);
    await reloadRelated();
    await onChanged();
  };

  const removeContact = async (contact: LinkedContact) => {
    await unlinkCompanyContact(company.id, contact.id);
    toast(`${contact.name} removed from ${company.name}`);
    setOpen(false);
    await onChanged();
  };

  const removeDeal = async (deal: LinkedDeal) => {
    await unlinkDealCompany(deal.id, company.id);
    toast(`${deal.name} removed from ${company.name}`);
    setOpen(false);
    await onChanged();
  };

  /* ------------------------------------------------------------ render */

  const addButton = (kind: 'addContact' | 'addDeal' | 'addCompany', label: string) =>
    canEdit ? (
      <button
        type="button"
        className="company-add-link"
        aria-label={label}
        onClick={() => start({ kind })}
      >
        + Add
      </button>
    ) : null;

  const removeName =
    action?.kind === 'removeContact'
      ? action.contact.name
      : action?.kind === 'removeCompany'
        ? action.related.name
        : action?.kind === 'removeDeal'
          ? action.deal.name
          : '';

  /** B4 preview: a small design link button (`lp-link`), shown only with edit rights. */
  const previewButton = (label: string, ariaLabel: string, next: Action) =>
    canEdit ? (
      <button type="button" className="lp-link" aria-label={ariaLabel} onClick={() => start(next)}>
        {label}
      </button>
    ) : null;
  const previewEdits = (labelsNext: Action | null, removeNext: Action, name: string) =>
    canEdit ? (
      <span className="lp-pv__rowacts">
        {labelsNext ? previewButton('Labels', `Edit labels for ${name}`, labelsNext) : null}
        {previewButton('Remove', `Remove ${name}`, removeNext)}
      </span>
    ) : null;

  const blocks =
    look === 'preview' ? (
      <>
        <CollapsibleCard
          cardId="pv-contacts"
          title={`Contacts (${contactsCount})`}
          action={previewButton('+ Add', 'Add contact association', { kind: 'addContact' })}
        >
          {contacts.length === 0 ? (
            <p className="lp-muted">No contacts linked yet.</p>
          ) : (
            <>
              {contacts.map((c) => (
                <div key={c.id} className="lp-pv__row">
                  <Link className="lp-pv__assoc" href={`/contacts/${c.id}`}>
                    <Avatar name={c.name} size="sm" />
                    <span>
                      <strong>{c.name}</strong>
                      <small>
                        {c.labels.map((l) => l.name).join(', ') ||
                          c.jobTitle ||
                          c.email ||
                          'Contact'}
                      </small>
                    </span>
                  </Link>
                  {previewEdits(
                    { kind: 'contactLabels', contact: c },
                    { kind: 'removeContact', contact: c },
                    c.name,
                  )}
                </div>
              ))}
              <Link className="lp-a" href={`/contacts?q=${encodeURIComponent(company.name)}`}>
                View all {Math.max(contactsCount, contacts.length)} contacts
              </Link>
            </>
          )}
        </CollapsibleCard>
        <CollapsibleCard
          cardId="pv-related-companies"
          title={`Related companies (${related?.length ?? 0})`}
          action={previewButton('+ Add', 'Add related company', { kind: 'addCompany' })}
        >
          {related === null ? (
            <p className="lp-muted">
              {relatedFailed ? 'Could not load related companies.' : 'Loading…'}
            </p>
          ) : related.length === 0 ? (
            <p className="lp-muted">No related companies yet.</p>
          ) : (
            related.map((r) => (
              <div key={r.id} className="lp-pv__row">
                <Link className="lp-pv__assoc" href={`/companies/${r.id}`}>
                  <Avatar name={r.name} size="sm" shape="sq" />
                  <span>
                    <strong>{r.name}</strong>
                    <small>{r.labels.map((l) => l.name).join(', ') || r.domain || 'Company'}</small>
                  </span>
                </Link>
                {previewEdits(
                  { kind: 'companyLabels', related: r },
                  { kind: 'removeCompany', related: r },
                  r.name,
                )}
              </div>
            ))
          )}
        </CollapsibleCard>
        <CollapsibleCard
          cardId="pv-deals"
          title={`Deals (${deals.length})`}
          action={previewButton('+ Add', 'Add deal association', { kind: 'addDeal' })}
        >
          {deals.length === 0 ? (
            <p className="lp-muted">No deals linked to this company.</p>
          ) : (
            deals.map((d) => (
              <div key={d.id} className="lp-pv__row">
                <Link className="lp-pv__assoc" href={`/deals/${d.id}`}>
                  {/* The design's deal avatar (list-page.js:3606), small. */}
                  <span className="lp-av lp-av--sm lp-av--sq lp-av--deal" aria-hidden>
                    <LpIcon name="deal" />
                  </span>
                  <span>
                    <strong>{d.name}</strong>
                    <small>
                      {formatMoney(d.amount, d.currency)} · {d.stage.name}
                      {d.labels?.length ? ` · ${d.labels.map((l) => l.name).join(', ')}` : ''}
                    </small>
                  </span>
                </Link>
                {previewEdits(null, { kind: 'removeDeal', deal: d }, d.name)}
              </div>
            ))
          )}
        </CollapsibleCard>
      </>
    ) : null;

  const contactsTitle = cardTitle(cards?.contacts, `Contacts (${contactsCount})`, contactsCount);
  const relatedTitle = cardTitle(
    cards?.related,
    `Related companies (${related?.length ?? 0})`,
    related?.length ?? 0,
  );
  const dealsCount = dealList.rows ? dealList.total : deals.length;
  const dealsTitle = cardTitle(cards?.deals, `Deals (${dealsCount})`, dealsCount);

  return (
    <>
      {blocks ?? (
        <>
          {show('contacts') ? (
            <CompanyCard cardId="r-contacts" dataCardId={only ? 'r-contacts' : undefined}>
              <div className="company-card-head">
                <CompanyCardTitle>{contactsTitle}</CompanyCardTitle>
                {withCardGear(
                  addButton('addContact', 'Add contact association'),
                  cards?.contacts?.onGear,
                  contactsTitle,
                )}
              </div>
              {cards?.contacts?.list ? (
                <CardQuickFilters
                  settings={cards.contacts.list}
                  fromType="company"
                  toType="contact"
                  list={contactList}
                />
              ) : null}
              {contactList.rows === null && cards?.contacts?.list ? (
                <p className="company-muted">Loading…</p>
              ) : contacts.length === 0 ? (
                // R1: the design's empty card (record-tabs.js:310).
                <DesignAssocEmpty kind="contact" />
              ) : (
                <>
                  {/* R6a: the design's rows (record-tabs.js:290-304). */}
                  <div className="crm-arows">
                    {contacts.map((c) => (
                      <DesignAssocRow
                        key={c.id}
                        obj="contacts"
                        name={c.name}
                        href={`/contacts/${c.id}`}
                        sub={c.jobTitle ? `${c.jobTitle} at ${company.name}` : null}
                        props={cards?.contacts?.props}
                        record={contactRecord(c, date)}
                        labels={c.labels}
                        onEditLabels={
                          canEdit ? () => start({ kind: 'contactLabels', contact: c }) : undefined
                        }
                        menu={assocMenu({
                          onPreview: onPreview
                            ? () => onPreview({ type: 'contact', id: c.id })
                            : undefined,
                          propertiesHref: propertiesHref('contact', c.id),
                          edit: canEdit
                            ? [
                                {
                                  key: 'labels',
                                  label: 'Edit association labels',
                                  onSelect: () => start({ kind: 'contactLabels', contact: c }),
                                },
                                {
                                  key: 'remove',
                                  label: 'Remove association',
                                  onSelect: () => start({ kind: 'removeContact', contact: c }),
                                },
                              ]
                            : [],
                        })}
                      />
                    ))}
                  </div>
                  {/* The design's text; master's filtered list kept (record-tabs.js:309). */}
                  <Link
                    className="rp-link crm-arow__viewall"
                    href={`/contacts?q=${encodeURIComponent(company.name)}`}
                  >
                    View all associated Contacts ↗
                  </Link>
                </>
              )}
              {cards?.contacts?.list ? (
                <CardListFooter list={contactList} plural="contacts" />
              ) : null}
            </CompanyCard>
          ) : null}

          {show('related') ? (
            <CompanyCard cardId="r-related" dataCardId={only ? 'r-related' : undefined}>
              <div className="company-card-head">
                <CompanyCardTitle>{relatedTitle}</CompanyCardTitle>
                {withCardGear(
                  addButton('addCompany', 'Add related company'),
                  cards?.related?.onGear,
                  relatedTitle,
                )}
              </div>
              {related === null ? (
                <p className="company-muted">
                  {relatedFailed ? 'Could not load related companies.' : 'Loading…'}
                </p>
              ) : related.length === 0 ? (
                <p className="company-muted">No related companies yet.</p>
              ) : (
                <div className="company-contacts">
                  {related.map((r) => (
                    <div key={r.id} style={ROW}>
                      <Link href={`/companies/${r.id}`} style={{ minWidth: 0 }}>
                        <span className="mini-avatar" aria-hidden>
                          {companyInitials(r.name)}
                        </span>
                        <span>
                          <strong>{r.name}</strong>
                          <small>
                            {r.labels.map((l) => l.name).join(', ') || r.domain || 'Company'}
                          </small>
                        </span>
                      </Link>
                      {canEdit ? (
                        <span style={{ ...REMOVE, display: 'flex', gap: 10 }}>
                          <button
                            type="button"
                            className="company-add-link"
                            aria-label={`Edit labels for ${r.name}`}
                            onClick={() => start({ kind: 'companyLabels', related: r })}
                          >
                            Labels
                          </button>
                          <button
                            type="button"
                            className="company-add-link"
                            aria-label={`Remove ${r.name}`}
                            onClick={() => start({ kind: 'removeCompany', related: r })}
                          >
                            Remove
                          </button>
                        </span>
                      ) : null}
                    </div>
                  ))}
                </div>
              )}
            </CompanyCard>
          ) : null}

          {show('deals') ? (
            <CompanyCard cardId="r-deals" dataCardId={only ? 'r-deals' : undefined}>
              <div className="company-card-head">
                <CompanyCardTitle>{dealsTitle}</CompanyCardTitle>
                {withCardGear(
                  addButton('addDeal', 'Add deal association'),
                  cards?.deals?.onGear,
                  dealsTitle,
                )}
              </div>
              {cards?.deals?.list ? (
                <CardQuickFilters
                  settings={cards.deals.list}
                  fromType="company"
                  toType="deal"
                  list={dealList}
                />
              ) : null}
              {dealList.rows === null && cards?.deals?.list ? (
                <p className="company-muted">Loading…</p>
              ) : deals.length === 0 ? (
                // R1: the design's empty card (record-tabs.js:310).
                <DesignAssocEmpty kind="deal" />
              ) : (
                // R6a: the design's rows; labels through the link in GET /associations/records.
                <div className="crm-arows">
                  {deals.map((d) => (
                    <DesignAssocRow
                      key={d.id}
                      obj="deals"
                      name={d.name}
                      href={`/deals/${d.id}`}
                      props={cards?.deals?.props}
                      record={dealRecord(d, date)}
                      labels={d.labels ?? []}
                      onEditLabels={
                        canEdit ? () => start({ kind: 'dealLabels', deal: d }) : undefined
                      }
                      menu={assocMenu({
                        onPreview: onPreview
                          ? () => onPreview({ type: 'deal', id: d.id })
                          : undefined,
                        propertiesHref: propertiesHref('deal', d.id),
                        edit: canEdit
                          ? [
                              {
                                key: 'labels',
                                label: 'Edit association labels',
                                onSelect: () => start({ kind: 'dealLabels', deal: d }),
                              },
                              {
                                key: 'remove',
                                label: 'Remove association',
                                onSelect: () => start({ kind: 'removeDeal', deal: d }),
                              },
                            ]
                          : [],
                      })}
                    />
                  ))}
                  <Link className="rp-link crm-arow__viewall" href="/deals">
                    View all associated Deals ↗
                  </Link>
                </div>
              )}
              {cards?.deals?.list ? <CardListFooter list={dealList} plural="deals" /> : null}
            </CompanyCard>
          ) : null}
        </>
      )}

      {canEdit && look === 'page' && (show('contacts') || show('deals')) ? (
        // R6b: the design's + Add panel (record-tabs.js:781-852) on the record page.
        <AddAssociationDesignDrawer
          id={`companyAddDesign-${only ?? 'all'}`}
          open={is('addContact') || is('addDeal')}
          onClose={close}
          anchorType="company"
          targetType={action?.kind === 'addDeal' ? 'deal' : 'contact'}
          // CQS1 #140: Primary for contacts, for each one picked (a company can be primary for many).
          allowPrimary={action?.kind !== 'addDeal'}
          primaryEach
          linkedIds={
            action?.kind === 'addDeal'
              ? [...new Set([...company.deals, ...deals].map((d) => d.id))]
              : [...new Set([...company.contacts, ...contacts].map((c) => c.id))]
          }
          canCreate={
            me.permissionSet.rules.objects[action?.kind === 'addDeal' ? 'deal' : 'contact'].edit !==
            'none'
          }
          editFormHref={
            me.role === 'admin'
              ? `/create-form-editor?object=${action?.kind === 'addDeal' ? 'deal' : 'contact'}`
              : undefined
          }
          link={(input) =>
            action?.kind === 'addDeal' ? addDeal(input, true) : addContact(input, true)
          }
          create={(v, custom) =>
            action?.kind === 'addDeal'
              ? createLinkedDeal(v, custom)
              : createLinkedContact(v, custom)
          }
          onDone={onChanged}
        />
      ) : null}
      {canEdit ? (
        <>
          {show('contacts') && look === 'preview' ? (
            <AddAssociationDrawer
              id="companyAddContactModal"
              open={is('addContact')}
              onClose={close}
              anchorType="company"
              targetType="contact"
              anchorName={company.name}
              linkedIds={[...new Set([...company.contacts, ...contacts].map((c) => c.id))]}
              onLink={addContact}
            />
          ) : null}
          {show('related') ? (
            <AddAssociationDrawer
              id="companyAddCompanyModal"
              open={is('addCompany')}
              onClose={close}
              anchorType="company"
              targetType="company"
              anchorName={company.name}
              linkedIds={[company.id, ...(related ?? []).map((r) => r.id)]}
              onLink={addCompany}
            />
          ) : null}
          {show('deals') && look === 'preview' ? (
            <AddAssociationDrawer
              id="companyAddDealModal"
              open={is('addDeal')}
              onClose={close}
              anchorType="company"
              targetType="deal"
              anchorName={company.name}
              linkedIds={[...new Set([...company.deals, ...deals].map((d) => d.id))]}
              labelsNote="Deal labels are saved on the link but not shown on the company page yet."
              onLink={addDeal}
            />
          ) : null}
          {show('contacts') || show('deals') ? (
            <AssociationLabelsModal
              id="companyLabelsModal"
              open={look === 'page' && (is('contactLabels') || is('dealLabels'))}
              onClose={close}
              anchorType="company"
              targetType={action?.kind === 'dealLabels' ? 'deal' : 'contact'}
              recordName={
                action?.kind === 'dealLabels'
                  ? action.deal.name
                  : action?.kind === 'contactLabels'
                    ? action.contact.name
                    : ''
              }
              current={action?.kind === 'contactLabels' ? action.contact.labels : []}
              load={action?.kind === 'dealLabels' ? () => loadDealLabels(action.deal) : undefined}
              canRemove={action?.kind !== 'contactLabels' || Boolean(action.contact.associationId)}
              manageHref={
                canOpenSettingsHref(me, '/settings/associations') ? '/settings/associations' : null
              }
              onSave={(labelIds) =>
                action?.kind === 'contactLabels'
                  ? saveContactLabels(action.contact, labelIds, true)
                  : action?.kind === 'dealLabels'
                    ? saveDealLabels(labelIds)
                    : Promise.resolve()
              }
            />
          ) : null}
          {show('contacts') ? (
            <AssociationLabelsDrawer
              id="companyContactLabelsModal"
              open={look === 'preview' && is('contactLabels')}
              onClose={close}
              anchorType="company"
              targetType="contact"
              recordName={action?.kind === 'contactLabels' ? action.contact.name : ''}
              current={action?.kind === 'contactLabels' ? action.contact.labels : []}
              canRemove={action?.kind === 'contactLabels' && Boolean(action.contact.associationId)}
              onSave={(labelIds) =>
                action?.kind === 'contactLabels'
                  ? saveContactLabels(action.contact, labelIds)
                  : Promise.resolve()
              }
            />
          ) : null}
          {show('related') ? (
            <AssociationLabelsDrawer
              id="companyRelatedLabelsModal"
              open={is('companyLabels')}
              onClose={close}
              anchorType="company"
              targetType="company"
              recordName={action?.kind === 'companyLabels' ? action.related.name : ''}
              current={action?.kind === 'companyLabels' ? action.related.labels : []}
              canRemove
              onSave={(labelIds, inverseLabelIds) =>
                action?.kind === 'companyLabels'
                  ? saveCompanyLabels(action.related, labelIds, inverseLabelIds)
                  : Promise.resolve()
              }
            />
          ) : null}
          <RemoveAssociationDialog
            id={only ? `companyRemoveAssociationModal-${only}` : 'companyRemoveAssociationModal'}
            open={is('removeContact') || is('removeCompany') || is('removeDeal')}
            onClose={close}
            targetType={
              action?.kind === 'removeDeal'
                ? 'deal'
                : action?.kind === 'removeCompany'
                  ? 'company'
                  : 'contact'
            }
            recordName={removeName}
            anchorName={company.name}
            onConfirm={() =>
              action?.kind === 'removeContact'
                ? removeContact(action.contact)
                : action?.kind === 'removeCompany'
                  ? removeCompany(action.related)
                  : action?.kind === 'removeDeal'
                    ? removeDeal(action.deal)
                    : Promise.resolve()
            }
          />
        </>
      ) : null}
    </>
  );
}
