'use client';

import { useEffect, useRef, useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type {
  AssociationLabel,
  AssociationLabelPreview,
  AssociationObjectType,
  LinkTargetType,
} from '@/features/associations/types';
import {
  associationErrorText,
  currentPairedIds,
  pairedLabelOptions,
  splitPairedIds,
  useAssociationLabels,
  withExclusivePairedPick,
} from './shared';

interface Option {
  id: string;
  name: string;
  /** "Paired with <inverse>" (labels of two different object types). */
  pairedWith?: string;
  group: 'single' | 'paired';
}

/** R6a: the dialog's options (record-tabs.js:458-470): single labels, then paired ones. */
export function labelModalOptions(
  labels: AssociationLabel[],
  current: AssociationLabelPreview[],
  sameType: boolean,
): Option[] {
  const live: Option[] = sameType
    ? // Two records of one type: both names of a paired label, as AssociationLabelsDrawer.
      pairedLabelOptions(labels).map((o) => ({ ...o, group: 'single' as const }))
    : labels.map((l) =>
        l.inverseName && l.inverseName !== l.name
          ? { id: l.id, name: l.name, pairedWith: l.inverseName, group: 'paired' as const }
          : { id: l.id, name: l.name, group: 'single' as const },
      );
  // Labels on the link that were archived since: kept, as AssociationLabelsDrawer does.
  const archived = current
    .filter((c) => !labels.some((l) => l.id === c.id))
    .map((c) => ({ id: c.id, name: c.name, group: 'single' as const }));
  return [...live, ...archived];
}

/**
 * R6a: "Edit association to <name>" as the 28 Oct design's dialog (record-tabs.js:438-497), on
 * the contact and company record pages: chips with a search, "Single labels" and "Paired labels",
 * "Manage Association Labels ↗", Update (off until something changed) and Cancel. Saving works
 * as AssociationLabelsDrawer: `onSave` gets every label id that should be on the link (company
 * to company: plus the paired ones picked by inverse name). `load` (deal rows, which carry no
 * link id) finds the link's labels first; Update stays off until it has.
 */
export function AssociationLabelsModal({
  id,
  open,
  onClose,
  anchorType,
  targetType,
  recordName,
  current,
  load,
  canRemove = true,
  manageHref,
  onSave,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  anchorType: AssociationObjectType;
  targetType: LinkTargetType;
  recordName: string;
  current: AssociationLabelPreview[];
  /** Deal rows: look the link up first (its labels as this record reads them). */
  load?: () => Promise<AssociationLabelPreview[]>;
  /** False: the link has no id, so labels it has can't be taken off (as the drawer). */
  canRemove?: boolean;
  /** Settings › Associations, or null for someone who can't open it. */
  manageHref: string | null;
  onSave: (labelIds: string[], inverseLabelIds: string[]) => Promise<void>;
}) {
  const toast = useToast();
  const { labels, loaded, failed } = useAssociationLabels(anchorType, targetType, open);
  const [linkLabels, setLinkLabels] = useState<AssociationLabelPreview[] | null>(null);
  const [linkFailed, setLinkFailed] = useState(false);
  const [selected, setSelected] = useState<Set<string> | null>(null);
  const [query, setQuery] = useState('');
  const [listOpen, setListOpen] = useState(false);
  const [active, setActive] = useState(-1);
  const [busy, setBusy] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const selRef = useRef<HTMLDivElement>(null);

  // A click outside the picker closes its list (record-tabs.js:481).
  useEffect(() => {
    if (!listOpen) return;
    const onDown = (e: MouseEvent) => {
      if (!selRef.current?.contains(e.target as Node)) setListOpen(false);
    };
    document.addEventListener('mousedown', onDown, true);
    return () => document.removeEventListener('mousedown', onDown, true);
  }, [listOpen]);

  useEffect(() => {
    if (!open) return;
    setSelected(null);
    setQuery('');
    setListOpen(false);
    setLinkFailed(false);
    setLinkLabels(load ? null : current);
    if (!load) return;
    let alive = true;
    load().then(
      (l) => alive && setLinkLabels(l),
      () => alive && setLinkFailed(true),
    );
    return () => {
      alive = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- reset only when it opens
  }, [open]);

  const sameType = anchorType === targetType;
  const start = linkLabels ?? [];
  const startIds = sameType ? currentPairedIds(start, labels) : start.map((l) => l.id);
  const chosen = selected ?? new Set(startIds);
  const options = labelModalOptions(labels, start, sameType);
  const nameOf = (optionId: string) => options.find((o) => o.id === optionId)?.name ?? optionId;
  const locked = canRemove ? new Set<string>() : new Set(startIds);
  const blocked = !loaded || failed || linkLabels === null || linkFailed;
  const unchanged = chosen.size === startIds.length && startIds.every((x) => chosen.has(x));

  const q = query.trim().toLowerCase();
  const shown = options.filter(
    (o) =>
      !chosen.has(o.id) &&
      (!q || o.name.toLowerCase().includes(q) || o.pairedWith?.toLowerCase().includes(q)),
  );
  const singles = shown.filter((o) => o.group === 'single');
  const paired = shown.filter((o) => o.group === 'paired');
  const flat = [...singles, ...paired];

  const toggle = (optionId: string) => {
    if (locked.has(optionId)) return;
    setSelected(withExclusivePairedPick(chosen, optionId, !chosen.has(optionId)));
    setQuery('');
    setActive(-1);
    inputRef.current?.focus();
  };

  const save = async () => {
    if (blocked || unchanged) return;
    setBusy(true);
    try {
      const { labelIds, inverseLabelIds } = splitPairedIds([...chosen]);
      await onSave(labelIds, inverseLabelIds);
      toast('Association labels updated');
      onClose();
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  const listId = `${id}-options`;
  return (
    <CrmModal id={id} open={open} onClose={onClose} className="alm">
      <ModalHeader id={id} title={`Edit association to ${recordName}`} onClose={onClose} />
      <div className="modal__body">
        <h3 className="alm__label" id={`${id}-label`}>
          Labels
        </h3>
        <p className="alm__help" id={`${id}-help`}>
          Describe how these two records are associated. For example, the label could be a role like
          &quot;Contractor.&quot;
        </p>
        {linkFailed || failed ? (
          <p className="alm__note" role="alert">
            Labels could not be loaded. Try again.
          </p>
        ) : blocked ? (
          <p className="alm__note">Loading labels…</p>
        ) : null}
        <div ref={selRef} className={listOpen ? 'alm__sel is-open' : 'alm__sel'}>
          <div className="alm__box" onClick={() => !blocked && setListOpen(true)}>
            {[...chosen].map((c) => (
              <span key={c} className="alm__chip">
                {nameOf(c)}
                {locked.has(c) ? null : (
                  <button
                    type="button"
                    aria-label={`Remove ${nameOf(c)}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      toggle(c);
                    }}
                  >
                    ×
                  </button>
                )}
              </span>
            ))}
            <input
              ref={inputRef}
              type="text"
              className="alm__q"
              placeholder={chosen.size ? '' : 'Search'}
              role="combobox"
              aria-expanded={listOpen}
              aria-controls={listId}
              aria-autocomplete="list"
              aria-labelledby={`${id}-label`}
              aria-describedby={`${id}-help`}
              aria-activedescendant={active >= 0 ? `${listId}-${active}` : undefined}
              disabled={blocked}
              value={query}
              onChange={(e) => {
                setQuery(e.target.value);
                setListOpen(true);
                setActive(-1);
              }}
              onKeyDown={(e) => {
                if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
                  e.preventDefault();
                  if (!listOpen) {
                    setListOpen(true);
                    return;
                  }
                  setActive((a) =>
                    e.key === 'ArrowDown' ? Math.min(flat.length - 1, a + 1) : Math.max(0, a - 1),
                  );
                } else if (e.key === 'Enter' && listOpen && flat[active]) {
                  e.preventDefault();
                  toggle(flat[active].id);
                } else if (e.key === 'Backspace' && !query && chosen.size) {
                  const last = [...chosen].filter((c) => !locked.has(c)).pop();
                  if (last) toggle(last);
                } else if (e.key === 'Escape' && listOpen) {
                  // Close the list only; the next Escape closes the dialog.
                  e.stopPropagation();
                  setListOpen(false);
                }
              }}
            />
            <button
              type="button"
              className="alm__caret"
              tabIndex={-1}
              aria-label="Show labels"
              disabled={blocked}
              onClick={(e) => {
                e.stopPropagation();
                setListOpen((o) => !o);
                inputRef.current?.focus();
              }}
            >
              ▾
            </button>
          </div>
          {listOpen ? (
            <div className="alm__pop">
              <ul className="alm__list" id={listId} role="listbox" aria-multiselectable="true">
                {singles.length ? (
                  <li className="alm__group" role="presentation">
                    Single labels
                  </li>
                ) : null}
                {singles.map((o) => (
                  <OptionRow
                    key={o.id}
                    o={o}
                    index={flat.indexOf(o)}
                    active={active}
                    listId={listId}
                    onPick={toggle}
                  />
                ))}
                {paired.length ? (
                  <li className="alm__group" role="presentation">
                    Paired labels
                  </li>
                ) : null}
                {paired.map((o) => (
                  <OptionRow
                    key={o.id}
                    o={o}
                    index={flat.indexOf(o)}
                    active={active}
                    listId={listId}
                    onPick={toggle}
                  />
                ))}
                {flat.length === 0 ? <li className="alm__empty">No labels found</li> : null}
              </ul>
              {manageHref ? (
                <a className="alm__manage" href={manageHref} target="_blank" rel="noopener">
                  Manage Association Labels ↗
                </a>
              ) : null}
            </div>
          ) : null}
        </div>
      </div>
      <div className="modal__footer">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          disabled={blocked || unchanged || busy}
          onClick={() => void save()}
        >
          Update
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </CrmModal>
  );
}

function OptionRow({
  o,
  index,
  active,
  listId,
  onPick,
}: {
  o: Option;
  index: number;
  active: number;
  listId: string;
  onPick: (id: string) => void;
}) {
  return (
    <li
      id={`${listId}-${index}`}
      role="option"
      aria-selected={false}
      className={index === active ? 'alm__opt is-act' : 'alm__opt'}
      onMouseDown={(e) => e.preventDefault()}
      onClick={() => onPick(o.id)}
    >
      <span>{o.name}</span>
      {o.pairedWith ? (
        <small>
          Paired with <strong>{o.pairedWith}</strong>
        </small>
      ) : null}
    </li>
  );
}
