'use client';

/**
 * HUB-323: "Additional owners" on a record's About card (contacts, companies, deals and custom
 * objects): users who own the record together with its owner (HUB-322). Shown by name and
 * edited in place: pick several owners, saved when focus leaves the field (Enter saves too).
 * They don't change who may see the record; access follows the owner.
 */
import type { Owner } from '@/features/owners/api.client';
import { ownerDisplayName } from '@/features/owners/labels';
import type { AdditionalOwner } from '@/types/api';
import { InlineDropdown, InlineEdit } from './InlineEdit';

/** "Ann Lee, Bo Chen (deactivated)", or "--" when there are none. */
export function additionalOwnersText(owners: AdditionalOwner[] | undefined): string {
  if (!owners?.length) return '--';
  return owners.map((o) => (o.isActive ? o.name : `${o.name} (deactivated)`)).join(', ');
}

export function AdditionalOwnersEdit({
  current,
  owners,
  canEdit,
  lockedTitle,
  onSave,
}: {
  current: AdditionalOwner[] | undefined;
  /** The business's owners (members and HubSpot owners), from useOwners. */
  owners: Owner[];
  canEdit: boolean;
  lockedTitle?: string;
  /** Saves the record with `additionalOwnerIds` and updates it on the page. */
  onSave: (ids: string[]) => Promise<void>;
}) {
  const list = current ?? [];
  // Active owners to pick from, plus anyone already listed (a deactivated one stays shown).
  const options = owners
    .filter((o) => o.active || list.some((c) => c.id === o.userId))
    .map((o) => ({ value: o.userId, label: ownerDisplayName(o) }));
  for (const c of list) {
    if (!options.some((o) => o.value === c.id)) options.push({ value: c.id, label: c.name });
  }
  return (
    <InlineEdit<string[]>
      label="Additional owners"
      dropdown
      display={additionalOwnersText(list)}
      canEdit={canEdit}
      lockedTitle={lockedTitle}
      initial={() => list.map((o) => o.id)}
      renderInput={({ id, value, onChange }) => (
        <InlineDropdown
          id={id}
          value={value}
          onChange={(next) => onChange(Array.isArray(next) ? next : next ? [next] : [])}
          options={options}
          multiple
        />
      )}
      onSave={async (ids) => {
        const before = list.map((o) => o.id);
        const same = ids.length === before.length && ids.every((id) => before.includes(id));
        if (same) return;
        await onSave(ids);
      }}
    />
  );
}
