'use client';

// Right-sidebar cards of contact, company and deal pages for the custom objects linked to the
// record (HUB-269): one card per live object (Events, Leads, Tickets and any object an admin
// creates), each with its linked records, their association labels, Add and Remove.
import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { setAssociationLabels } from '@/features/associations/api.client';
import type { AssociationLinkInput, ObjectNames } from '@/features/associations/types';
import { AddAssociationDrawer } from '@/features/associations/ui/AddAssociationDrawer';
import { AssociationLabelsDrawer } from '@/features/associations/ui/AssociationLabelsDrawer';
import { RemoveAssociationDialog } from '@/features/associations/ui/RemoveAssociationDialog';
import { DesignAssocEmpty } from '@/features/associations/ui/DesignAssocEmpty';
import { AssociationLabelBadges } from '@/features/associations/ui/shared';
import { CollapsibleCard, usePreviewSectionLook } from '@/features/contacts/ui/CollapsibleCard';
import { CompanyCard, CompanyCardTitle } from '@/features/contacts/ui/CollapsibleCard';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import type { CardView } from '@/features/record-layouts/ui/AssocLines';
import { withCardGear } from '@/features/record-layouts/ui/CardGear';
import { errorText } from '@/lib/api/errors';
import {
  linkRecords,
  listLinkedRecords,
  listObjectDefinitions,
  unlinkRecords,
} from '../api.client';
import { objectRecordPath } from '../paths';
import type { LinkedRecord, ObjectDefinition } from '../types';
import { nameInText } from '@/features/objects/paths';

type AnchorType = 'contact' | 'company' | 'deal';

/** Links shown per card at a time; "Show more" loads the next page. */
const PAGE = 10;

interface CardState {
  rows: LinkedRecord[];
  total: number;
  cursor: string | null;
  error: string | null;
}

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

/**
 * Each record page's own card style: contact and deal pages use collapsible cards (each with its
 * own empty state), the company page `company-associated-card`, like their other cards.
 */
type Variant = 'contact' | 'deal' | 'company';

export function LinkedObjectCard({
  variant,
  id,
  title,
  action: addAction,
  onGear,
  children,
}: {
  variant: Variant;
  id: string;
  title: string;
  action?: React.ReactNode;
  /** Opens the card's "Edit default card" drawer (the gear); none: no gear. */
  onGear?: (() => void) | null;
  children: React.ReactNode;
}) {
  const action = withCardGear(addAction, onGear, title);
  if (variant !== 'company') {
    return (
      <CollapsibleCard cardId={id} title={title} action={action} defaultOpen>
        {children}
      </CollapsibleCard>
    );
  }
  return (
    <CompanyCard cardId={id} dataCardId={id}>
      <div className="company-card-head">
        <CompanyCardTitle>{title}</CompanyCardTitle>
        {action}
      </div>
      {children}
    </CompanyCard>
  );
}

const namesOf = (def: ObjectDefinition): ObjectNames => ({
  one: nameInText(def.singularLabel),
  many: nameInText(def.pluralLabel),
});

export function LinkedObjectCards({
  anchorType,
  anchorId,
  anchorName,
  canEdit,
  variant,
  onViewHistory,
  onlyLinked = false,
  cardView,
  designEmpty = false,
}: {
  anchorType: AnchorType;
  anchorId: string;
  anchorName: string;
  /** Edit rights on the record: without them the cards are read-only. */
  canEdit: boolean;
  variant: Variant;
  /** HUB-617: "View association history" under each card (pages that pass it). */
  onViewHistory?: (objectKey: string, plural: string) => void;
  /** B4 (Companies' list preview): a card only for objects with links, once loaded. */
  onlyLinked?: boolean;
  /**
   * Each object card's layout settings (card id `object-<key>`: a saved title) and gear; only
   * the contact and company record pages pass it.
   */
  cardView?: (objectKey: string, plural: string) => CardView | undefined;
  /**
   * R1 (contact record page only): the Events card's empty state as the design
   * (record-tabs.js:328). Other object cards keep their text: the design has none for them.
   */
  designEmpty?: boolean;
}) {
  const previewRows = usePreviewSectionLook();
  const actionClass = previewRows
    ? 'lp-link'
    : variant === 'company'
      ? 'company-add-link'
      : 'crm-collapsible-card__action';
  const mutedClass = previewRows
    ? 'lp-muted'
    : variant === 'company'
      ? 'company-muted'
      : 'crm-fs-8 crm-text-muted crm-mb-0';
  const toast = useToast();
  const [defs, setDefs] = useState<ObjectDefinition[]>([]);
  const [cards, setCards] = useState<Record<string, CardState>>({});
  const [action, setAction] = useState<Action | null>(null);
  const [open, setOpen] = useState(false);
  const [moreBusy, setMoreBusy] = useState<string | null>(null);

  // The live objects (archived ones have no card).
  useEffect(() => {
    let alive = true;
    listObjectDefinitions().then(
      (list) =>
        alive && setDefs([...list].sort((a, b) => a.pluralLabel.localeCompare(b.pluralLabel))),
      () => alive && setDefs([]),
    );
    return () => {
      alive = false;
    };
  }, []);

  const loadCard = useCallback(
    async (key: string): Promise<CardState> => {
      try {
        const page = await listLinkedRecords({
          fromType: anchorType,
          fromId: anchorId,
          toType: key,
          limit: PAGE,
        });
        return {
          rows: page.data,
          total: page.total ?? page.data.length,
          cursor: page.nextCursor ?? null,
          error: null,
        };
      } catch (err) {
        return { rows: [], total: 0, cursor: null, error: errorText(err) };
      }
    },
    [anchorId, anchorType],
  );

  const reloadCard = useCallback(
    async (key: string) => {
      const state = await loadCard(key);
      setCards((current) => ({ ...current, [key]: state }));
    },
    [loadCard],
  );

  useEffect(() => {
    let alive = true;
    void Promise.all(defs.map(async (def) => [def.key, await loadCard(def.key)] as const)).then(
      (entries) => alive && setCards(Object.fromEntries(entries)),
    );
    return () => {
      alive = false;
    };
  }, [defs, loadCard]);

  const showMore = async (key: string) => {
    const card = cards[key];
    if (!card?.cursor || moreBusy) return;
    setMoreBusy(key);
    try {
      const page = await listLinkedRecords({
        fromType: anchorType,
        fromId: anchorId,
        toType: key,
        limit: PAGE,
        cursor: card.cursor,
      });
      setCards((current) => ({
        ...current,
        [key]: {
          ...card,
          rows: [...card.rows, ...page.data],
          cursor: page.nextCursor ?? null,
        },
      }));
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setMoreBusy(null);
    }
  };

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

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

  const add = async ({ record, labelIds }: AssociationLinkInput) => {
    if (!def) return;
    await linkRecords({
      from: { type: anchorType, id: anchorId },
      to: { type: def.key, id: record.id },
      ...(labelIds.length ? { labelIds } : {}),
    });
    toast(`${record.title} associated with ${anchorName}`);
    await reloadCard(def.key);
  };

  const saveLabels = async (labelIds: string[]) => {
    if (action?.kind !== 'labels') return;
    await setAssociationLabels(action.row.associationId, labelIds);
    toast(`Labels saved for ${action.row.name ?? 'the record'}`);
    await reloadCard(action.def.key);
  };

  const remove = async () => {
    if (action?.kind !== 'remove') return;
    await unlinkRecords({
      fromType: anchorType,
      fromId: anchorId,
      toType: action.def.key,
      toId: action.row.id,
    });
    toast(`${action.row.name ?? 'The record'} removed from ${anchorName}`);
    setOpen(false);
    await reloadCard(action.def.key);
  };

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

  return (
    <>
      {defs.map((d) => {
        const card = cards[d.key];
        const rows = card?.rows ?? [];
        if (onlyLinked && (!card || (!card.error && rows.length === 0))) return null;
        return (
          <LinkedObjectCard
            key={d.key}
            variant={variant}
            id={`object-${d.key}`}
            title={
              cardView?.(d.key, d.pluralLabel)?.title
                ? `${cardView(d.key, d.pluralLabel)!.title} (${card?.total ?? 0})`
                : card
                  ? `${d.pluralLabel} (${card.total})`
                  : d.pluralLabel
            }
            onGear={cardView?.(d.key, d.pluralLabel)?.onGear}
            action={
              canEdit ? (
                <button
                  type="button"
                  className={actionClass}
                  aria-label={`Add ${nameInText(d.singularLabel)} association`}
                  onClick={() => start({ kind: 'add', def: d })}
                >
                  + Add
                </button>
              ) : undefined
            }
          >
            {!card ? (
              <p className={mutedClass}>Loading…</p>
            ) : card.error ? (
              <p className={mutedClass} role="alert">
                {card.error}
              </p>
            ) : rows.length === 0 ? (
              designEmpty && d.key === 'event' ? (
                <DesignAssocEmpty kind="event" />
              ) : variant === 'contact' ? (
                <div className="crm-empty-association">
                  <p>No {nameInText(d.pluralLabel)} linked.</p>
                </div>
              ) : (
                <p className={mutedClass}>No {nameInText(d.pluralLabel)} linked yet.</p>
              )
            ) : (
              <div>
                {rows.map((row) =>
                  previewRows ? (
                    // The design's preview row (list-page.js:3608), with the labels as its line.
                    <div key={row.associationId} className="lp-pv__row">
                      <Link className="lp-pv__assoc" href={objectRecordPath(d.key, row.id)}>
                        <Avatar name={row.name || 'Untitled'} size="sm" />
                        <span>
                          <strong>{row.name || 'Untitled'}</strong>
                          <small>
                            {row.labels.map((l) => l.name).join(', ') || d.singularLabel}
                          </small>
                        </span>
                      </Link>
                      {canEdit ? (
                        <span className="lp-pv__rowacts">
                          <button
                            type="button"
                            className="lp-link"
                            onClick={() => start({ kind: 'labels', def: d, row })}
                          >
                            Labels
                          </button>
                          <button
                            type="button"
                            className="lp-link"
                            onClick={() => start({ kind: 'remove', def: d, row })}
                          >
                            Remove
                          </button>
                        </span>
                      ) : null}
                    </div>
                  ) : (
                    <div key={row.associationId} className="deal-card-item">
                      <div className="deal-card-title">
                        <Link
                          className="crm-associated-link"
                          href={objectRecordPath(d.key, row.id)}
                          style={{ marginTop: 0 }}
                        >
                          {row.name || 'Untitled'}
                        </Link>
                      </div>
                      <AssociationLabelBadges labels={row.labels} />
                      {canEdit ? (
                        <div
                          className="deal-association"
                          style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}
                        >
                          <button
                            type="button"
                            className={actionClass}
                            onClick={() => start({ kind: 'labels', def: d, row })}
                          >
                            {row.labels.length ? 'Edit labels' : 'Add association label'}
                          </button>
                          <button
                            type="button"
                            className={actionClass}
                            onClick={() => start({ kind: 'remove', def: d, row })}
                          >
                            Remove
                          </button>
                        </div>
                      ) : null}
                    </div>
                  ),
                )}
                {card.cursor ? (
                  <button
                    type="button"
                    className={actionClass}
                    disabled={moreBusy === d.key}
                    onClick={() => void showMore(d.key)}
                  >
                    {moreBusy === d.key
                      ? 'Loading…'
                      : `Show more (${rows.length} of ${card.total})`}
                  </button>
                ) : null}
              </div>
            )}
            {onViewHistory ? (
              <button
                type="button"
                className="rp-link--btn crm-mt-2"
                onClick={() => onViewHistory(d.key, d.pluralLabel)}
              >
                View association history
              </button>
            ) : null}
          </LinkedObjectCard>
        );
      })}

      {canEdit && def ? (
        <>
          <AddAssociationDrawer
            id={`${anchorType}AddObjectRecordModal`}
            open={is('add')}
            onClose={close}
            anchorType={anchorType}
            targetType={def.key}
            targetNames={namesOf(def)}
            anchorName={anchorName}
            linkedIds={(cards[def.key]?.rows ?? []).map((r) => r.id)}
            onLink={add}
          />
          <AssociationLabelsDrawer
            id={`${anchorType}ObjectRecordLabelsModal`}
            open={is('labels')}
            onClose={close}
            anchorType={anchorType}
            targetType={def.key}
            targetNames={namesOf(def)}
            recordName={action?.kind === 'labels' ? (action.row.name ?? 'Untitled') : ''}
            current={action?.kind === 'labels' ? action.row.labels : []}
            canRemove
            onSave={saveLabels}
          />
          <RemoveAssociationDialog
            id={`${anchorType}RemoveObjectRecordModal`}
            open={is('remove')}
            onClose={close}
            targetType={def.key}
            targetNames={namesOf(def)}
            recordName={action?.kind === 'remove' ? (action.row.name ?? 'Untitled') : ''}
            anchorName={anchorName}
            // A refused unlink (a lead must keep a contact or company, HUB-338) shows the API's
            // message and the dialog stays open.
            onConfirm={remove}
          />
        </>
      ) : null}
    </>
  );
}
