'use client';

import Link from 'next/link';
import { useCallback, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  linkDealCompany,
  linkDealContact,
  setAssociationLabels,
  unlinkDealCompany,
  unlinkDealContact,
} from '@/features/associations/api.client';
import type { AssociationLinkInput } from '@/features/associations/types';
import { AddAssociationDesignDrawer } from '@/features/associations/ui/AddAssociationDesignDrawer';
import { AssociationLabelsModal } from '@/features/associations/ui/AssociationLabelsModal';
import { DesignAssocEmpty } from '@/features/associations/ui/DesignAssocEmpty';
import { RemoveAssociationDialog } from '@/features/associations/ui/RemoveAssociationDialog';
import { associationErrorText } from '@/features/associations/ui/shared';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { createCompany } from '@/features/companies/api.client';
import { createContact } from '@/features/contacts/api.client';
import { CollapsibleCard } from '@/features/contacts/ui/CollapsibleCard';
import { createDeal } from '@/features/deals/api.client';
import type { Deal } from '@/features/deals/types';
import { linkRecords, unlinkRecords } from '@/features/objects/api.client';
import type { LinkedRecord } from '@/features/objects/types';
import { canOpenSettingsHref } from '@/features/permission-sets/property-settings';
import {
  companyRecord,
  contactRecord,
  dealRecord,
  type DateText,
} from '@/features/record-layouts/assocRecords';
import type { AssocCardSettings } from '@/features/record-layouts/api.client';
import { ASSOC_DEFAULT_PROPS } from '@/features/record-layouts/cardSettings';
import { cardTitle, type CardView } from '@/features/record-layouts/ui/AssocLines';
import { withCardGear } from '@/features/record-layouts/ui/CardGear';
import {
  CardListFooter,
  CardQuickFilters,
  companyFromList,
  contactFromList,
  dealFromList,
  useCardList,
} from '@/features/record-layouts/ui/CardList';
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 type { CustomProperties } from '@/types/api';

export type DealCardKind = 'contacts' | 'companies' | 'deals';

const TARGET = { contacts: 'contact', companies: 'company', deals: 'deal' } as const;
const PLURAL = { contacts: 'Contacts', companies: 'Companies', deals: 'Deals' } as const;
/** EV11's "View all associated …" links: the object's list (record-tabs.js:309). */
const LIST_HREF = { contacts: '/contacts', companies: '/companies', deals: '/deals' } as const;

/**
 * DR4a: the list a deal card loads without saved filters: the design's default properties,
 * newest first (record-layout-editor.js:443). The deal's own payload carries only names and
 * emails, so the card always loads its rows (GET /associations/records, `card=true`) with the
 * phone, job title, labels, primary flag and link id the design's rows show.
 */
export function dealCardSettings(
  kind: DealCardKind,
  saved: AssocCardSettings | undefined,
): AssocCardSettings {
  return saved ?? { obj: kind, props: ASSOC_DEFAULT_PROPS[kind], sort: 'createDate', dir: 'desc' };
}

type Action =
  { kind: 'add' } | { kind: 'labels'; row: LinkedRecord } | { kind: 'remove'; row: LinkedRecord };

/**
 * DR4a: a right-column association card of the deal page (Contacts, Companies or Deals), as the
 * 28 Oct design (record-tabs.js:281-316) and the contact and company pages' cards (R6a, R7,
 * card-gear batches 1-2): the design's rows with Preview, Edit association labels, View all
 * properties and Remove; Companies keep master's Set as primary (Q2). The card's "Edit default
 * card" settings apply: title, properties, filters, quick filters and sort.
 */
export function DealAssociationCard({
  kind,
  deal,
  canEdit,
  view,
  onChanged,
  onPreview,
  dateText,
}: {
  kind: DealCardKind;
  deal: Deal;
  /** Edit rights on the deal: without them the card is read-only. */
  canEdit: boolean;
  /** The card's layout settings and gear. */
  view?: CardView;
  /** Reloads the deal after a change. */
  onChanged: () => Promise<void>;
  onPreview: (target: NonNullable<PreviewTarget>) => void;
  dateText: DateText;
}) {
  const toast = useToast();
  const me = useCurrentUser();
  const target = TARGET[kind];
  const [action, setAction] = useState<Action | null>(null);
  const [open, setOpen] = useState(false);
  const [primaryBusy, setPrimaryBusy] = useState<string | null>(null);
  const start = (next: Action) => {
    setAction(next);
    setOpen(true);
  };
  const close = useCallback(() => setOpen(false), []);
  const settings = useMemo(() => dealCardSettings(kind, view?.list), [kind, view?.list]);
  const list = useCardList({
    fromType: 'deal',
    fromId: deal.id,
    toType: target,
    settings,
    excludeId: kind === 'deals' ? deal.id : undefined,
    refreshKey: deal,
  });
  const rows = list.rows ?? [];
  const title = cardTitle(view, `${PLURAL[kind]} (${list.total})`, list.total);
  const sameType = kind === 'deals';

  const changed = async (text: string) => {
    toast(text);
    await onChanged();
  };

  /* ------------------------------------------------------------ links */

  const link = async ({ record, isPrimary, labelIds, inverseLabelIds }: AssociationLinkInput) => {
    if (kind === 'contacts') {
      await linkDealContact(deal.id, {
        contactId: record.id,
        ...(labelIds.length ? { labelIds } : {}),
      });
    } else if (kind === 'companies') {
      await linkDealCompany(deal.id, {
        companyId: record.id,
        ...(isPrimary ? { isPrimary: true } : {}),
        ...(labelIds.length ? { labelIds } : {}),
      });
    } else {
      // HUB-574: two deals, with paired labels picked on this one.
      await linkRecords({
        from: { type: 'deal', id: deal.id },
        to: { type: 'deal', id: record.id },
        ...(labelIds.length ? { labelIds } : {}),
        ...(inverseLabelIds.length ? { inverseLabelIds } : {}),
      });
    }
  };

  /** R6b, Create new: the record, then its link to this deal. */
  const create = async (v: Record<string, string>, custom: CustomProperties) => {
    const extra = Object.keys(custom).length ? { customProperties: custom } : {};
    if (kind === 'contacts') {
      const c = await createContact({
        email: v.email || null,
        firstName: v.firstName || null,
        ...extra,
      });
      await linkDealContact(deal.id, { contactId: c.id });
      return [c.firstName, c.lastName].filter(Boolean).join(' ') || c.email || '';
    }
    if (kind === 'companies') {
      const c = await createCompany({ name: v.name ?? '', domain: v.domain || null, ...extra });
      await linkDealCompany(deal.id, { companyId: c.id });
      return c.name;
    }
    const d = await createDeal({
      name: v.name ?? '',
      ...(v.amount ? { amount: v.amount } : {}),
      ...extra,
    });
    await linkRecords({ from: { type: 'deal', id: deal.id }, to: { type: 'deal', id: d.id } });
    return d.name;
  };

  const remove = async (row: LinkedRecord) => {
    if (kind === 'contacts') await unlinkDealContact(deal.id, row.id);
    else if (kind === 'companies') await unlinkDealCompany(deal.id, row.id);
    else await unlinkRecords({ fromType: 'deal', fromId: deal.id, toType: 'deal', toId: row.id });
    setOpen(false);
    await changed(`${row.name ?? ''} removed from ${deal.name}`);
  };

  /** The link's id replaces its labels; deal to deal labels are paired, read from this deal. */
  const saveLabels = async (row: LinkedRecord, labelIds: string[], inverseLabelIds: string[]) => {
    await setAssociationLabels(
      row.associationId,
      labelIds,
      sameType ? { inverseLabelIds, viewerId: deal.id } : undefined,
    );
    await onChanged();
  };

  /** Master's Set as primary on company rows (Q2). */
  const makePrimary = async (row: LinkedRecord) => {
    if (primaryBusy) return;
    setPrimaryBusy(row.id);
    try {
      await linkDealCompany(deal.id, { companyId: row.id, isPrimary: true });
      await changed(`${row.name ?? ''} is now the primary company`);
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setPrimaryBusy(null);
    }
  };

  /* ------------------------------------------------------------ rows */

  const rowView = (r: LinkedRecord) => {
    if (kind === 'contacts') {
      const c = contactFromList(r);
      return { name: c.name, sub: c.jobTitle, record: contactRecord(c, dateText) };
    }
    if (kind === 'companies') {
      const c = companyFromList(r);
      return { name: c.name, sub: null, record: companyRecord(c, dateText) };
    }
    const d = dealFromList(r);
    return { name: d.name, sub: null, record: dealRecord(d, dateText) };
  };

  const removeRow = action?.kind === 'remove' ? action.row : null;
  const labelsRow = action?.kind === 'labels' ? action.row : null;

  return (
    <>
      <CollapsibleCard
        title={title}
        cardId={`r-${kind}`}
        action={withCardGear(
          canEdit ? (
            <button
              type="button"
              className="crm-collapsible-card__action"
              aria-label={`Add ${target} association`}
              onClick={() => start({ kind: 'add' })}
            >
              + Add
            </button>
          ) : null,
          view?.onGear,
          title,
        )}
      >
        {view?.list ? (
          <CardQuickFilters settings={view.list} fromType="deal" toType={target} list={list} />
        ) : null}
        {list.rows === null && !list.error ? (
          <p className="crm-fs-8 crm-text-muted crm-mb-0">Loading…</p>
        ) : rows.length === 0 && !list.error ? (
          // R1: the design's empty card (record-tabs.js:310).
          <DesignAssocEmpty kind={target} />
        ) : (
          <>
            {/* R6a: the design's rows (record-tabs.js:286-304). */}
            <div className="crm-arows">
              {rows.map((r) => {
                const v = rowView(r);
                return (
                  <DesignAssocRow
                    key={r.id}
                    obj={kind}
                    name={v.name}
                    href={`/${kind}/${r.id}`}
                    primary={kind === 'companies' && r.isPrimary}
                    sub={v.sub}
                    props={view?.props}
                    record={v.record}
                    labels={r.labels}
                    onEditLabels={canEdit ? () => start({ kind: 'labels', row: r }) : undefined}
                    menu={assocMenu({
                      onPreview: () => onPreview({ type: target, id: r.id }),
                      propertiesHref: propertiesHref(target, r.id),
                      edit: canEdit
                        ? [
                            {
                              key: 'labels',
                              label: 'Edit association labels',
                              onSelect: () => start({ kind: 'labels', row: r }),
                            },
                            ...(kind === 'companies' && !r.isPrimary
                              ? [
                                  {
                                    key: 'primary',
                                    label: 'Set as primary',
                                    disabled: primaryBusy !== null,
                                    onSelect: () => void makePrimary(r),
                                  },
                                ]
                              : []),
                            {
                              key: 'remove',
                              label: 'Remove association',
                              onSelect: () => start({ kind: 'remove', row: r }),
                            },
                          ]
                        : [],
                    })}
                  />
                );
              })}
            </div>
            {rows.length ? (
              <Link className="rp-link crm-arow__viewall" href={LIST_HREF[kind]}>
                View all associated {PLURAL[kind]} ↗
              </Link>
            ) : null}
          </>
        )}
        <CardListFooter list={list} plural={kind} />
      </CollapsibleCard>

      {canEdit ? (
        <>
          {/* R6b: the design's + Add panel (record-tabs.js:781-852). */}
          <AddAssociationDesignDrawer
            id={`dealAddDesign-${kind}`}
            open={open && action?.kind === 'add'}
            onClose={close}
            anchorType="deal"
            targetType={target}
            allowPrimary={kind === 'companies'}
            linkedIds={[
              ...new Set([
                ...(kind === 'deals' ? [deal.id] : []),
                ...(kind === 'contacts' ? deal.contacts.map((c) => c.id) : []),
                ...(kind === 'companies' ? deal.companies.map((c) => c.id) : []),
                ...rows.map((r) => r.id),
              ]),
            ]}
            canCreate={me.permissionSet.rules.objects[target].edit !== 'none'}
            editFormHref={me.role === 'admin' ? `/create-form-editor?object=${target}` : undefined}
            link={link}
            create={create}
            onDone={onChanged}
          />
          <AssociationLabelsModal
            id={`dealLabels-${kind}`}
            open={open && action?.kind === 'labels'}
            onClose={close}
            anchorType="deal"
            targetType={target}
            recordName={labelsRow?.name ?? ''}
            current={labelsRow?.labels ?? []}
            canRemove={Boolean(labelsRow?.associationId)}
            manageHref={
              canOpenSettingsHref(me, '/settings/associations') ? '/settings/associations' : null
            }
            onSave={(labelIds, inverseLabelIds) =>
              labelsRow ? saveLabels(labelsRow, labelIds, inverseLabelIds) : Promise.resolve()
            }
          />
          <RemoveAssociationDialog
            id={`dealRemove-${kind}`}
            open={open && action?.kind === 'remove'}
            onClose={close}
            targetType={target}
            recordName={removeRow?.name ?? ''}
            anchorName={deal.name}
            note={
              kind === 'companies' && removeRow?.isPrimary && deal.companies.length > 1
                ? 'This is the primary company: the oldest remaining company becomes primary.'
                : undefined
            }
            onConfirm={() => (removeRow ? remove(removeRow) : Promise.resolve())}
          />
        </>
      ) : null}
    </>
  );
}
