'use client';

import { useEffect, useState } from 'react';
import { listAssociationLabels } from '@/features/associations/api.client';
import type {
  AssociationLabel,
  AssociationLabelPreview,
  AssociationObjectType,
  LinkTargetType,
  ObjectNames,
} from '@/features/associations/types';
import { errorText, isApiError } from '@/lib/api/errors';

/** Singular / plural names of the record types, for titles and messages. */
export const OBJECT_NAMES: Record<AssociationObjectType, ObjectNames> = {
  contact: { one: 'contact', many: 'contacts' },
  company: { one: 'company', many: 'companies' },
  deal: { one: 'deal', many: 'deals' },
};

/** The names of a built-in type, else the ones passed (a custom object's labels), else its key. */
export function namesOf(type: LinkTargetType, custom?: ObjectNames): ObjectNames {
  return (
    custom ?? OBJECT_NAMES[type as AssociationObjectType] ?? { one: type, many: `${type} records` }
  );
}

/**
 * The message for a failed link / unlink: 404 means one of the records is gone, 409 that it
 * changed meanwhile; a 400 lists the fields the API rejected (e.g. an archived label).
 */
export function associationErrorText(err: unknown): string {
  if (isApiError(err) && err.isNotFound) {
    return `${err.message}. It may have been deleted; reload the page.`;
  }
  if (isApiError(err) && err.isConflict) return 'Someone else changed this, reload';
  if (isApiError(err) && err.status === 400 && err.details?.length) {
    const parts = err.details
      .map((d) => {
        if (!d || typeof d !== 'object') return null;
        const { field, message } = d as { field?: unknown; message?: unknown };
        if (typeof message !== 'string') return null;
        return typeof field === 'string' && field ? `${field}: ${message}` : message;
      })
      .filter(Boolean);
    if (parts.length) return `${err.message} (${parts.join('; ')})`;
  }
  return errorText(err);
}

/**
 * Live labels for links between `aType` and `bType`, loaded once `enabled` turns true.
 * A failed request sets `failed` so callers can block save (avoid guessing paired sides).
 */
export function useAssociationLabels(
  aType: LinkTargetType,
  bType: LinkTargetType,
  enabled: boolean,
): { labels: AssociationLabel[]; loaded: boolean; failed: boolean } {
  const [state, setState] = useState<{
    key: string;
    labels: AssociationLabel[];
    failed: boolean;
  } | null>(null);
  const key = `${aType}:${bType}`;
  useEffect(() => {
    if (!enabled || state?.key === key) return;
    let alive = true;
    listAssociationLabels(aType, bType).then(
      (labels) => {
        if (alive) setState({ key, labels, failed: false });
      },
      () => {
        if (alive) setState({ key, labels: [], failed: true });
      },
    );
    return () => {
      alive = false;
    };
  }, [aType, bType, enabled, key, state?.key]);
  const ready = state?.key === key;
  return {
    labels: ready ? state.labels : [],
    loaded: ready,
    failed: ready ? state.failed : false,
  };
}

export const INVERSE_SUFFIX = '~inverse';

const isPaired = (label: AssociationLabel) =>
  Boolean(label.inverseName) && label.inverseName !== label.name;

/**
 * Selecting one side of a paired label clears the other (same underlying label id cannot be
 * sent in both `labelIds` and `inverseLabelIds`).
 */
export function withExclusivePairedPick(
  selected: ReadonlySet<string>,
  id: string,
  checked: boolean,
): Set<string> {
  const next = new Set(selected);
  if (checked) {
    next.add(id);
    if (id.endsWith(INVERSE_SUFFIX)) next.delete(id.slice(0, -INVERSE_SUFFIX.length));
    else next.delete(`${id}${INVERSE_SUFFIX}`);
  } else {
    next.delete(id);
  }
  return next;
}

/**
 * Picker options for a link between two records of one type (company to company). A paired label
 * is offered by both of its names, each as the viewed record reads the other one ("Parent
 * Company", "Child Company"); the other record reads the paired name. The inverse option's id
 * carries a suffix: `splitPairedIds` turns the picked ids back into `labelIds` / `inverseLabelIds`.
 */
export function pairedLabelOptions(labels: AssociationLabel[]): AssociationLabelPreview[] {
  return labels.flatMap((label) => {
    if (!isPaired(label)) return [{ id: label.id, name: label.name }];
    const inverse = label.inverseName as string;
    return [
      { id: label.id, name: `${label.name} (they see "${inverse}")` },
      { id: `${label.id}${INVERSE_SUFFIX}`, name: `${inverse} (they see "${label.name}")` },
    ];
  });
}

/** Picked option ids of `pairedLabelOptions`, split the way the company links API takes them. */
export function splitPairedIds(ids: Iterable<string>): {
  labelIds: string[];
  inverseLabelIds: string[];
} {
  const labelIds: string[] = [];
  const inverseLabelIds: string[] = [];
  const claimed = new Set<string>();
  for (const id of ids) {
    if (id.endsWith(INVERSE_SUFFIX)) {
      const base = id.slice(0, -INVERSE_SUFFIX.length);
      if (claimed.has(base)) continue;
      claimed.add(base);
      inverseLabelIds.push(base);
    } else {
      if (claimed.has(id)) continue;
      claimed.add(id);
      labelIds.push(id);
    }
  }
  return { labelIds, inverseLabelIds };
}

/**
 * The option ids of the labels a link has now. A link's labels are named as the viewed record
 * reads them, so one that shows a label's inverse name is that label's inverse option.
 */
export function currentPairedIds(
  current: AssociationLabelPreview[],
  labels: AssociationLabel[],
): string[] {
  return current.map((c) => {
    const label = labels.find((l) => l.id === c.id);
    // Unresolved labels (archived / labels request failed): keep the forward id so we do not
    // guess reverse from the display name and flip Parent ↔ Child on save.
    if (!label) return c.id;
    return isPaired(label) && c.name === label.inverseName ? `${c.id}${INVERSE_SUFFIX}` : c.id;
  });
}

/** Label names on a linked record, as small badges. */
export function AssociationLabelBadges({ labels }: { labels: AssociationLabelPreview[] }) {
  if (labels.length === 0) return null;
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
      {labels.map((label) => (
        <span key={label.id} className="badge badge--brand">
          {label.name}
        </span>
      ))}
    </div>
  );
}

/**
 * Checkboxes for picking link labels. `locked` ids stay checked and cannot be unticked (labels
 * the link already has when the API can only add labels).
 */
export function LabelChecklist({
  labels,
  selected,
  locked,
  onChange,
  disabled,
}: {
  labels: AssociationLabelPreview[];
  selected: ReadonlySet<string>;
  locked?: ReadonlySet<string>;
  onChange: (next: Set<string>) => void;
  disabled?: boolean;
}) {
  return (
    <div style={{ display: 'grid', gap: 10 }}>
      {labels.map((label) => {
        const isLocked = locked?.has(label.id) ?? false;
        return (
          <label key={label.id} className="check">
            <input
              type="checkbox"
              checked={selected.has(label.id) || isLocked}
              disabled={disabled || isLocked}
              onChange={(e) => {
                onChange(withExclusivePairedPick(selected, label.id, e.target.checked));
              }}
            />
            <span className="check__box" aria-hidden />
            <span>{label.name}</span>
          </label>
        );
      })}
    </div>
  );
}
