'use client';

import { useState } from 'react';
import { FormDrawer } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type {
  AssociationLabelPreview,
  AssociationObjectType,
  LinkTargetType,
  ObjectNames,
} from '@/features/associations/types';
import {
  associationErrorText,
  currentPairedIds,
  LabelChecklist,
  namesOf,
  OBJECT_NAMES,
  pairedLabelOptions,
  splitPairedIds,
  useAssociationLabels,
} from './shared';

/**
 * Edit the labels of one existing link. `onSave` gets every label id that should be on the link
 * (company to company: plus the paired ones picked by inverse name) and does the API call (and
 * the success toast). With `canRemove` false (the API can only add labels to this link), labels
 * the link already has stay ticked.
 */
export function AssociationLabelsDrawer({
  id,
  open,
  onClose,
  anchorType,
  targetType,
  targetNames,
  recordName,
  current,
  canRemove,
  onSave,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  anchorType: AssociationObjectType;
  /** A built-in type or a custom object key. */
  targetType: LinkTargetType;
  /** A custom object's names; built-in types have their own. */
  targetNames?: ObjectNames;
  /** The linked record whose labels are edited. */
  recordName: string;
  current: AssociationLabelPreview[];
  canRemove: boolean;
  onSave: (labelIds: string[], inverseLabelIds: string[]) => Promise<void>;
}) {
  const toast = useToast();
  // null until the user ticks something: then the link's own labels show
  const [edited, setEdited] = useState<Set<string> | null>(null);
  const [wasOpen, setWasOpen] = useState(false);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) setEdited(null);
  }
  const { labels, loaded, failed } = useAssociationLabels(anchorType, targetType, open);

  // two records of one type: paired labels read differently from each side
  const sameType = anchorType === targetType;
  const currentIds = sameType ? currentPairedIds(current, labels) : current.map((l) => l.id);
  const selected = edited ?? new Set(currentIds);

  // live labels, plus ones on the link that were archived since (they can be kept)
  const options: AssociationLabelPreview[] = [
    ...(sameType ? pairedLabelOptions(labels) : labels.map((l) => ({ id: l.id, name: l.name }))),
    ...current.filter((c) => !labels.some((l) => l.id === c.id)),
  ];
  const locked = canRemove ? undefined : new Set(currentIds);
  const blockSave = !loaded || failed;

  const onSubmit = async () => {
    if (blockSave) {
      toast(
        failed ? 'Labels could not be loaded. Try again before saving.' : 'Still loading labels…',
        'danger',
        { durationMs: 8000 },
      );
      return false;
    }
    const next = [...selected];
    const unchanged = next.length === currentIds.length && currentIds.every((i) => selected.has(i));
    if (unchanged) return; // nothing to save: just close
    try {
      const { labelIds, inverseLabelIds } = splitPairedIds(next);
      await onSave(labelIds, inverseLabelIds);
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id={id}
      title={`Labels: ${recordName}`}
      submitLabel="Save labels"
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
      submitDisabled={blockSave}
    >
      <div className="field">
        <span className="field__label">Association labels</span>
        {!loaded ? (
          <p className="crm-text-body-secondary">Loading labels…</p>
        ) : failed ? (
          <p className="crm-text-body-secondary">
            Labels could not be loaded. Close and try again — saving is blocked so paired labels are
            not flipped by mistake.
          </p>
        ) : options.length === 0 ? (
          <p className="crm-text-body-secondary">
            No labels are set up for {OBJECT_NAMES[anchorType].one} –{' '}
            {namesOf(targetType, targetNames).one} links. An admin can add them in Settings.
          </p>
        ) : (
          <LabelChecklist
            labels={options}
            selected={selected}
            locked={locked}
            onChange={setEdited}
          />
        )}
        {sameType && loaded && !failed && options.length > 0 ? (
          <p className="crm-text-body-secondary" style={{ marginTop: 8 }}>
            Pick what {recordName} is to this {OBJECT_NAMES[anchorType].one}. It sees the paired
            label for this {OBJECT_NAMES[anchorType].one}.
          </p>
        ) : null}
        {!canRemove && current.length > 0 ? (
          <p className="crm-text-body-secondary" style={{ marginTop: 8 }}>
            Labels can be added here but not removed yet. To clear them, remove the association and
            add it again.
          </p>
        ) : null}
      </div>
    </FormDrawer>
  );
}
