'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import { OBJECT_NAMES } from '@/features/associations/ui/shared';
import type { ObjectNames } from '@/features/associations/types';
import { listObjectDefinitions } from '@/features/objects/api.client';
import { nameInText } from '@/features/objects/paths';
import type { ObjectDefinition } from '@/features/objects/types';
import { linkHref } from '@/features/tasks/format';
import { MAX_TASK_LINKS, type TaskLink, type TaskLinkType } from '@/features/tasks/types';

/** Built-in types the search always adds. */
const TYPES = ['contact', 'company', 'deal'] as const;

/**
 * TK6 (QA #677): the custom objects the design's "Associate Task with" lists that this CRM has
 * (task-create.js ASSOC_TYPES: Events, Leads, Tickets). The task API takes them (EV1).
 */
export const TASK_CUSTOM_LINK_KEYS = ['event', 'lead', 'ticket'] as const;

/** A search choice: a built-in type, or a custom object with its names. */
export interface LinkSearchType {
  type: TaskLinkType;
  label: string;
  names?: ObjectNames;
}

const BUILT_IN_CHOICES: LinkSearchType[] = TYPES.map((t) => ({
  type: t,
  label: OBJECT_NAMES[t].one[0]!.toUpperCase() + OBJECT_NAMES[t].one.slice(1),
}));

/**
 * The picker's record types: the built-in ones, then the live definitions among
 * TASK_CUSTOM_LINK_KEYS (an archived or missing object is left out), in that order.
 */
export function linkSearchTypes(defs: ObjectDefinition[]): LinkSearchType[] {
  const custom = TASK_CUSTOM_LINK_KEYS.flatMap((key) => {
    const def = defs.find((d) => d.key === key);
    if (!def) return [];
    return [
      {
        type: def.key,
        label: def.singularLabel,
        names: { one: nameInText(def.singularLabel), many: nameInText(def.pluralLabel) },
      },
    ];
  });
  return [...BUILT_IN_CHOICES, ...custom];
}

/** A chip's type name: "contact", or a custom object's name (an event, EV1). */
const typeName = (type: TaskLinkType, choices: LinkSearchType[]): string =>
  (OBJECT_NAMES as Partial<Record<string, { one: string }>>)[type]?.one ??
  choices.find((c) => c.type === type)?.names?.one ??
  type;

/** Same record (type + id). */
export const sameLink = (a: TaskLink, b: Pick<TaskLink, 'objectType' | 'id'>) =>
  a.objectType === b.objectType && a.id === b.id;

/**
 * "Associated with": the records a task links to, as chips (× removes), plus a search to add
 * more (GET /search per type), up to MAX_TASK_LINKS. Contacts, companies and deals; with
 * `customTypes` (the task drawer, TK6) also events, leads and tickets.
 */
export function TaskLinksPicker({
  id,
  value,
  onChange,
  disabled,
  customTypes = false,
}: {
  id: string;
  value: TaskLink[];
  onChange: (links: TaskLink[]) => void;
  disabled?: boolean;
  /** TK6: offer the custom objects too (the Calls log dialog leaves it off). */
  customTypes?: boolean;
}) {
  const [choices, setChoices] = useState<LinkSearchType[]>(BUILT_IN_CHOICES);
  useEffect(() => {
    if (!customTypes) return;
    let alive = true;
    // A failed load keeps the built-in types; the custom ones just don't show.
    listObjectDefinitions().then(
      (defs) => {
        if (alive) setChoices(linkSearchTypes(defs));
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [customTypes]);

  const [type, setType] = useState<TaskLinkType>('contact');
  const current = choices.find((c) => c.type === type) ?? BUILT_IN_CHOICES[0]!;
  /** Bumped after a pick, so the search box starts empty again. */
  const [picks, setPicks] = useState(0);
  const linkedIds = useMemo(
    () => new Set(value.filter((l) => l.objectType === current.type).map((l) => l.id)),
    [value, current.type],
  );
  const full = value.length >= MAX_TASK_LINKS;

  return (
    <div>
      {value.length ? (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
          {value.map((link) => (
            <span
              key={`${link.objectType}:${link.id}`}
              className="badge badge--brand"
              style={{ gap: 6 }}
            >
              <span className="crm-text-muted">{typeName(link.objectType, choices)}:</span>
              <Link href={linkHref(link)} target="_blank" style={{ color: 'inherit' }}>
                {link.displayName}
              </Link>
              {disabled ? null : (
                <button
                  type="button"
                  aria-label={`Remove ${link.displayName}`}
                  title="Remove"
                  style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer' }}
                  onClick={() => onChange(value.filter((l) => !sameLink(l, link)))}
                >
                  ×
                </button>
              )}
            </span>
          ))}
        </div>
      ) : (
        <p className="crm-fs-8 crm-text-muted" style={{ marginBottom: 8 }}>
          Not associated with any record.
        </p>
      )}
      {disabled ? null : (
        <div style={{ display: 'flex', gap: 8 }}>
          <select
            className="input"
            style={{ width: 130, flex: 'none' }}
            aria-label="Record type"
            value={current.type}
            disabled={full}
            onChange={(e) => setType(e.target.value)}
          >
            {choices.map((c) => (
              <option key={c.type} value={c.type}>
                {c.label}
              </option>
            ))}
          </select>
          <div style={{ flex: 1, minWidth: 0 }}>
            <RecordSearchInput
              key={`${current.type}:${picks}`}
              id={id}
              type={current.type}
              names={current.names}
              value={null}
              linkedIds={linkedIds}
              disabled={full}
              onPick={(record) => {
                if (
                  !record ||
                  value.some((l) => sameLink(l, { objectType: current.type, id: record.id }))
                )
                  return;
                onChange([
                  ...value,
                  { objectType: current.type, id: record.id, displayName: record.title },
                ]);
                setPicks((n) => n + 1);
              }}
            />
          </div>
        </div>
      )}
      {full && !disabled ? (
        <p className="crm-fs-8 crm-text-muted crm-mt-2">
          A task links to at most {MAX_TASK_LINKS} records.
        </p>
      ) : null}
    </div>
  );
}
