'use client';

import Link from 'next/link';
import { useCallback, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  linkContactCompany,
  linkDealContact,
  setAssociationLabels,
  unlinkContactCompany,
  unlinkDealContact,
} from '@/features/associations/api.client';
import type { AssociationLinkInput } from '@/features/associations/types';
import { AddAssociationDrawer } from '@/features/associations/ui/AddAssociationDrawer';
import { AddAssociationDesignDrawer } from '@/features/associations/ui/AddAssociationDesignDrawer';
import { createCompany } from '@/features/companies/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 { RemoveAssociationDialog } from '@/features/associations/ui/RemoveAssociationDialog';
import { DesignAssocEmpty } from '@/features/associations/ui/DesignAssocEmpty';
import { associationErrorText, AssociationLabelBadges } from '@/features/associations/ui/shared';
import type { Contact, LinkedCompanyPreview, LinkedDealPreview } from '@/features/contacts/types';
import { companyRecord, dealRecord, type DateText } from '@/features/record-layouts/assocRecords';
import { AssocLines, cardTitle, type CardView } from '@/features/record-layouts/ui/AssocLines';
import {
  CardListFooter,
  CardQuickFilters,
  companyFromList,
  dealFromList,
  useCardList,
} from '@/features/record-layouts/ui/CardList';
import { withCardGear } from '@/features/record-layouts/ui/CardGear';
import { recordMoney } from '@/features/list-page/money';
import { CollapsibleCard } from './CollapsibleCard';

type Action =
  | { kind: 'addCompany' }
  | { kind: 'addDeal' }
  | { kind: 'companyLabels'; company: LinkedCompanyPreview }
  | { kind: 'dealLabels'; deal: LinkedDealPreview }
  | { kind: 'removeCompany'; company: LinkedCompanyPreview }
  | { kind: 'removeDeal'; deal: LinkedDealPreview };

/**
 * The Companies and Deals cards of the contact page, with add / remove association, primary
 * company and link labels. `onChanged` reloads the contact after every change.
 */
export function ContactAssociations({
  contact,
  contactName,
  canEdit,
  onChanged,
  onViewHistory,
  only,
  cards,
  dateText,
  design = false,
  onPreview,
}: {
  contact: Contact;
  contactName: string;
  /** Edit rights on the contact: without them the cards are read-only. */
  canEdit: boolean;
  onChanged: () => Promise<void>;
  /** HUB-617: "View association history" under the Companies and Deals cards. */
  onViewHistory?: (otherType: 'company' | 'deal') => void;
  /**
   * One of the two cards (the record page's layout ids `r-companies` and `r-deals`); both when
   * left out (the contact preview).
   */
  only?: 'companies' | 'deals';
  /** The cards' layout settings and gear (record page only); none: as before. */
  cards?: { companies?: CardView; deals?: CardView };
  /** Dates in the viewer's format, for saved Create / Close date properties. */
  dateText?: DateText;
  /**
   * R1: the record page's design look: "Companies (0)" and the design's empty cards
   * (record-tabs.js:310-311). Off: as before (the contact preview).
   */
  design?: boolean;
  /** R7: a row's "Preview" (record pages); none: no Preview item. */
  onPreview?: (target: NonNullable<PreviewTarget>) => void;
}) {
  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);
  /** Company whose "Set as primary" is running. */
  const [primaryBusy, setPrimaryBusy] = useState<string | null>(null);

  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 card saved with filters / quick filters / sort loads its own list (`CardView.list`);
  // otherwise it shows the contact's preview, as before. A reload of the contact reloads it.
  const companyList = useCardList({
    fromType: 'contact',
    fromId: contact.id,
    toType: 'company',
    settings: cards?.companies?.list ?? null,
    refreshKey: contact,
  });
  const dealList = useCardList({
    fromType: 'contact',
    fromId: contact.id,
    toType: 'deal',
    settings: cards?.deals?.list ?? null,
    refreshKey: contact,
  });
  const companies = companyList.rows ? companyList.rows.map(companyFromList) : contact.companies;
  const deals = dealList.rows ? dealList.rows.map(dealFromList) : contact.deals;
  const companiesCount = companyList.rows ? companyList.total : companies.length;
  const dealsCount = dealList.rows ? dealList.total : deals.length;
  // from all the contact's companies: a card filter may leave the primary out
  const hasPrimary = contact.companies.some((c) => c.isPrimary);

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

  /** `quiet` (R6b's panel): no toast or reload; the panel does both once for every record. */
  const addCompany = async (
    { record, isPrimary, labelIds }: AssociationLinkInput,
    quiet = false,
  ) => {
    await linkContactCompany(contact.id, {
      companyId: record.id,
      ...(isPrimary ? { isPrimary: true } : {}),
      ...(labelIds.length ? { labelIds } : {}),
    });
    if (quiet) return;
    toast(`${record.title} associated with ${contactName}`);
    await onChanged();
  };

  const addDeal = async ({ record, labelIds }: AssociationLinkInput, quiet = false) => {
    await linkDealContact(record.id, {
      contactId: contact.id,
      ...(labelIds.length ? { labelIds } : {}),
    });
    if (quiet) return;
    toast(`${record.title} associated with ${contactName}`);
    await onChanged();
  };

  /** R6b, Create new: a company, then its link to this contact. */
  const createLinkedCompany = async (v: Record<string, string>, custom: CustomProperties) => {
    const created = await createCompany({
      name: v.name ?? '',
      domain: v.domain || null,
      ...(Object.keys(custom).length ? { customProperties: custom } : {}),
    });
    await linkContactCompany(contact.id, { companyId: created.id });
    return created.name;
  };

  /** R6b, Create new: a deal linked to this contact 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 } : {}),
      contactIds: [contact.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 saveCompanyLabels = async (
    company: LinkedCompanyPreview,
    labelIds: string[],
    /** R6a: the design's dialog toasts itself ("Association labels updated"). */
    quiet = false,
  ) => {
    if (company.associationId) await setAssociationLabels(company.associationId, labelIds);
    else await linkContactCompany(contact.id, { companyId: company.id, labelIds });
    if (!quiet) toast(`Labels saved for ${company.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: LinkedDealPreview) => {
    dealLinkRef.current = null;
    const link = await findDealLink('contact', contact.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 removeCompany = async (company: LinkedCompanyPreview) => {
    await unlinkContactCompany(contact.id, company.id);
    toast(`${company.name} removed from ${contactName}`);
    setOpen(false);
    await onChanged();
  };

  const removeDeal = async (deal: LinkedDealPreview) => {
    await unlinkDealContact(deal.id, contact.id);
    toast(`${deal.name} removed from ${contactName}`);
    setOpen(false);
    await onChanged();
  };

  const setPrimary = async (company: LinkedCompanyPreview) => {
    if (primaryBusy) return;
    setPrimaryBusy(company.id);
    try {
      await linkContactCompany(contact.id, { companyId: company.id, isPrimary: true });
      toast(`${company.name} is now the primary company`);
      await onChanged();
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setPrimaryBusy(null);
    }
  };

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

  const addButton = (kind: 'addCompany' | 'addDeal', label: string) =>
    canEdit ? (
      <button
        type="button"
        className="crm-collapsible-card__action"
        aria-label={label}
        onClick={() => start({ kind })}
      >
        + Add
      </button>
    ) : undefined;

  const removeTarget =
    action?.kind === 'removeCompany'
      ? action.company
      : action?.kind === 'removeDeal'
        ? action.deal
        : null;
  const primaryNote =
    action?.kind === 'removeCompany' && action.company.isPrimary && companies.length > 1
      ? 'This is the primary company: the oldest remaining company becomes primary.'
      : undefined;
  const companiesView = cards?.companies;
  const dealsView = cards?.deals;
  const companiesTitle = cardTitle(
    companiesView,
    design || companiesCount > 0 ? `Companies (${companiesCount})` : 'Companies',
    companiesCount,
  );
  const dealsTitle = cardTitle(dealsView, `Deals (${dealsCount})`, dealsCount);
  const date: DateText = dateText ?? ((iso) => iso?.slice(0, 10) ?? '--');

  return (
    <>
      {only !== 'deals' ? (
        <CollapsibleCard
          title={companiesTitle}
          cardId={only ? 'r-companies' : undefined}
          action={withCardGear(
            addButton('addCompany', 'Add company association'),
            companiesView?.onGear,
            companiesTitle,
          )}
          defaultOpen
        >
          {companiesView?.list ? (
            <CardQuickFilters
              settings={companiesView.list}
              fromType="contact"
              toType="company"
              list={companyList}
            />
          ) : null}
          {companyList.rows === null && companiesView?.list ? (
            <p className="rp-empty">Loading…</p>
          ) : companies.length === 0 ? (
            design ? (
              <DesignAssocEmpty kind="company" />
            ) : (
              <div className="crm-empty-association">
                <p>No companies linked.</p>
              </div>
            )
          ) : design ? (
            // R6a: the design's rows (record-tabs.js:290-304).
            <div className="crm-arows">
              {companies.map((c) => (
                <DesignAssocRow
                  key={c.id}
                  obj="companies"
                  name={c.name}
                  href={`/companies/${c.id}`}
                  primary={c.isPrimary}
                  props={companiesView?.props}
                  record={companyRecord(c, date)}
                  labels={(c.labels ?? []).filter((l) => l.name !== 'Primary')}
                  onEditLabels={
                    canEdit ? () => start({ kind: 'companyLabels', company: c }) : undefined
                  }
                  menu={assocMenu({
                    onPreview: onPreview
                      ? () => onPreview({ type: 'company', id: c.id })
                      : undefined,
                    propertiesHref: propertiesHref('company', c.id),
                    edit: canEdit
                      ? [
                          {
                            key: 'labels',
                            label: 'Edit association labels',
                            onSelect: () => start({ kind: 'companyLabels', company: c }),
                          },
                          // Master's own, kept: the design sets Primary only in + Add.
                          ...(!c.isPrimary
                            ? [
                                {
                                  key: 'primary',
                                  label:
                                    primaryBusy === c.id ? 'Setting primary…' : 'Set as primary',
                                  disabled: primaryBusy !== null,
                                  onSelect: () => void setPrimary(c),
                                },
                              ]
                            : []),
                          {
                            key: 'remove',
                            label: 'Remove association',
                            onSelect: () => start({ kind: 'removeCompany', company: c }),
                          },
                        ]
                      : [],
                  })}
                />
              ))}
              <Link className="rp-link crm-arow__viewall" href="/companies">
                View all associated Companies ↗
              </Link>
            </div>
          ) : (
            <div className="crm-sidebar-info-card">
              {companies.map((c) => (
                <div key={c.id} className="company-card-item company-card-item--hubspot">
                  <div className="company-card-logo" aria-hidden>
                    {c.name.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="company-card-info">
                    <div className="company-card-title-row">
                      <Link href={`/companies/${c.id}`}>{c.name}</Link>
                      {c.isPrimary ? <span className="company-primary-tag">Primary</span> : null}
                    </div>
                    {companiesView?.props ? (
                      <AssocLines
                        obj="companies"
                        props={companiesView.props}
                        record={companyRecord(c, date)}
                      />
                    ) : c.domain ? (
                      <div className="company-card-detail">
                        <a href={`https://${c.domain}`} target="_blank" rel="noreferrer">
                          {c.domain}
                        </a>
                      </div>
                    ) : null}
                    <AssociationLabelBadges labels={c.labels ?? []} />
                    {canEdit ? (
                      <div
                        className="company-card-association"
                        style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}
                      >
                        <button
                          type="button"
                          className="crm-collapsible-card__action"
                          disabled={primaryBusy !== null}
                          onClick={() => start({ kind: 'companyLabels', company: c })}
                        >
                          {c.labels?.length ? 'Edit labels' : 'Add association label'}
                        </button>
                        {!c.isPrimary ? (
                          <button
                            type="button"
                            className="crm-collapsible-card__action"
                            disabled={primaryBusy !== null}
                            aria-busy={primaryBusy === c.id}
                            onClick={() => void setPrimary(c)}
                          >
                            {primaryBusy === c.id ? 'Setting primary…' : 'Set as primary'}
                          </button>
                        ) : null}
                        <button
                          type="button"
                          className="crm-collapsible-card__action"
                          disabled={primaryBusy !== null}
                          onClick={() => start({ kind: 'removeCompany', company: c })}
                        >
                          Remove
                        </button>
                      </div>
                    ) : null}
                  </div>
                </div>
              ))}
            </div>
          )}
          {companiesView?.list ? <CardListFooter list={companyList} plural="companies" /> : null}
          {onViewHistory ? (
            <button
              type="button"
              className="rp-link--btn crm-mt-2"
              onClick={() => onViewHistory('company')}
            >
              View association history
            </button>
          ) : null}
        </CollapsibleCard>
      ) : null}

      {only !== 'companies' ? (
        <CollapsibleCard
          title={dealsTitle}
          cardId={only ? 'r-deals' : undefined}
          action={withCardGear(
            addButton('addDeal', 'Add deal association'),
            dealsView?.onGear,
            dealsTitle,
          )}
          defaultOpen
        >
          {dealsView?.list ? (
            <CardQuickFilters
              settings={dealsView.list}
              fromType="contact"
              toType="deal"
              list={dealList}
            />
          ) : null}
          {dealList.rows === null && dealsView?.list ? (
            <p className="rp-empty">Loading…</p>
          ) : deals.length === 0 ? (
            design ? (
              <DesignAssocEmpty kind="deal" />
            ) : (
              <div className="crm-empty-association">
                <p>No deals linked.</p>
              </div>
            )
          ) : design ? (
            // R6a: the design's rows; labels through the link found 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={dealsView?.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>
          ) : (
            <div>
              {deals.map((d) => (
                <div key={d.id} className="deal-card-item">
                  <div className="deal-card-title">
                    <Link
                      className="crm-associated-link"
                      href={`/deals/${d.id}`}
                      style={{ marginTop: 0 }}
                    >
                      {d.name}
                    </Link>
                  </div>
                  {dealsView?.props ? (
                    <AssocLines obj="deals" props={dealsView.props} record={dealRecord(d, date)} />
                  ) : (
                    <div className="deal-meta">
                      <span>Stage </span>
                      <strong>{d.stage.name}</strong>
                      {d.amount != null ? (
                        <>
                          {' '}
                          {/* DL5: as the design's record cards ("$1,123"), not the raw "USD 3623.00". */}
                          · {recordMoney(d.amount, d.currency)}
                        </>
                      ) : null}
                    </div>
                  )}
                  <AssociationLabelBadges labels={d.labels ?? []} />
                  {canEdit ? (
                    <div className="deal-association">
                      <button
                        type="button"
                        className="crm-collapsible-card__action"
                        onClick={() => start({ kind: 'removeDeal', deal: d })}
                      >
                        Remove
                      </button>
                    </div>
                  ) : null}
                </div>
              ))}
            </div>
          )}
          {dealsView?.list ? <CardListFooter list={dealList} plural="deals" /> : null}
          {onViewHistory ? (
            <button
              type="button"
              className="rp-link--btn crm-mt-2"
              onClick={() => onViewHistory('deal')}
            >
              View association history
            </button>
          ) : null}
        </CollapsibleCard>
      ) : null}

      {canEdit && design ? (
        // R6b: the design's + Add panel (record-tabs.js:781-852) on the record page.
        <AddAssociationDesignDrawer
          id={`contactAddDesign-${only ?? 'all'}`}
          open={is('addCompany') || is('addDeal')}
          onClose={close}
          anchorType="contact"
          targetType={action?.kind === 'addDeal' ? 'deal' : 'company'}
          linkedIds={
            action?.kind === 'addDeal'
              ? [...new Set([...contact.deals, ...deals].map((d) => d.id))]
              : [...new Set([...contact.companies, ...companies].map((c) => c.id))]
          }
          allowPrimary={action?.kind !== 'addDeal'}
          canCreate={
            me.permissionSet.rules.objects[action?.kind === 'addDeal' ? 'deal' : 'company'].edit !==
            'none'
          }
          editFormHref={
            me.role === 'admin'
              ? `/create-form-editor?object=${action?.kind === 'addDeal' ? 'deal' : 'company'}`
              : undefined
          }
          link={(input) =>
            action?.kind === 'addDeal' ? addDeal(input, true) : addCompany(input, true)
          }
          create={(v, custom) =>
            action?.kind === 'addDeal'
              ? createLinkedDeal(v, custom)
              : createLinkedCompany(v, custom)
          }
          onDone={onChanged}
        />
      ) : null}
      {canEdit ? (
        <>
          {only !== 'deals' && !design ? (
            <AddAssociationDrawer
              id="contactAddCompanyModal"
              open={is('addCompany')}
              onClose={close}
              anchorType="contact"
              targetType="company"
              anchorName={contactName}
              linkedIds={[...new Set([...contact.companies, ...companies].map((c) => c.id))]}
              allowPrimary
              hasPrimary={hasPrimary}
              onLink={addCompany}
            />
          ) : null}
          {only !== 'companies' && !design ? (
            <AddAssociationDrawer
              id="contactAddDealModal"
              open={is('addDeal')}
              onClose={close}
              anchorType="contact"
              targetType="deal"
              anchorName={contactName}
              linkedIds={[...new Set([...contact.deals, ...deals].map((d) => d.id))]}
              labelsNote="Deal labels are saved on the link but not shown on the contact page yet."
              onLink={addDeal}
            />
          ) : null}
          {design ? (
            // R6a: the design's "Edit association to <name>" (record-tabs.js:438-497).
            <AssociationLabelsModal
              id={`contactLabelsModal-${only ?? 'all'}`}
              open={is('companyLabels') || is('dealLabels')}
              onClose={close}
              anchorType="contact"
              targetType={action?.kind === 'dealLabels' ? 'deal' : 'company'}
              recordName={
                action?.kind === 'dealLabels'
                  ? action.deal.name
                  : action?.kind === 'companyLabels'
                    ? action.company.name
                    : ''
              }
              current={action?.kind === 'companyLabels' ? (action.company.labels ?? []) : []}
              load={action?.kind === 'dealLabels' ? () => loadDealLabels(action.deal) : undefined}
              canRemove={action?.kind !== 'companyLabels' || Boolean(action.company.associationId)}
              manageHref={
                canOpenSettingsHref(me, '/settings/associations') ? '/settings/associations' : null
              }
              onSave={(labelIds) =>
                action?.kind === 'companyLabels'
                  ? saveCompanyLabels(action.company, labelIds, true)
                  : action?.kind === 'dealLabels'
                    ? saveDealLabels(labelIds)
                    : Promise.resolve()
              }
            />
          ) : null}
          {only !== 'deals' && !design ? (
            <AssociationLabelsDrawer
              id="contactCompanyLabelsModal"
              open={is('companyLabels')}
              onClose={close}
              anchorType="contact"
              targetType="company"
              recordName={action?.kind === 'companyLabels' ? action.company.name : ''}
              current={action?.kind === 'companyLabels' ? (action.company.labels ?? []) : []}
              canRemove={action?.kind === 'companyLabels' && Boolean(action.company.associationId)}
              onSave={(labelIds) =>
                action?.kind === 'companyLabels'
                  ? saveCompanyLabels(action.company, labelIds)
                  : Promise.resolve()
              }
            />
          ) : null}
          <RemoveAssociationDialog
            id={only ? `contactRemoveAssociationModal-${only}` : 'contactRemoveAssociationModal'}
            open={is('removeCompany') || is('removeDeal')}
            onClose={close}
            targetType={action?.kind === 'removeDeal' ? 'deal' : 'company'}
            recordName={removeTarget?.name ?? ''}
            anchorName={contactName}
            note={primaryNote}
            onConfirm={() =>
              action?.kind === 'removeCompany'
                ? removeCompany(action.company)
                : action?.kind === 'removeDeal'
                  ? removeDeal(action.deal)
                  : Promise.resolve()
            }
          />
        </>
      ) : null}
    </>
  );
}
