'use client';

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

/**
 * "Add association" drawer: search a record of `targetType`, pick it, optionally make it the
 * primary one and add link labels. `onLink` does the API call (and the success toast); when it
 * throws, the error shows as a toast and the drawer stays open.
 */
export function AddAssociationDrawer({
  id,
  open,
  onClose,
  anchorType,
  targetType,
  targetNames,
  anchorName,
  linkedIds,
  allowPrimary = false,
  hasPrimary = false,
  labelsSupported = true,
  labelsNote,
  onLink,
}: {
  id: string;
  open: boolean;
  onClose: () => void;
  /** The record whose page this is. */
  anchorType: AssociationObjectType;
  /** What gets linked to it: a built-in type or a custom object key. */
  targetType: LinkTargetType;
  /** A custom object's names ("event" / "events"); built-in types have their own. */
  targetNames?: ObjectNames;
  anchorName: string;
  /** Records already linked (shown, but cannot be picked again). */
  linkedIds: string[];
  /** Offer "Make primary" (company links of contacts and deals). */
  allowPrimary?: boolean;
  /** The anchor already has a primary; without one the first link becomes primary anyway. */
  hasPrimary?: boolean;
  /** Offer link labels (the API takes `labelIds` on this link). */
  labelsSupported?: boolean;
  /** Shown under the labels, e.g. where the labels will be visible. */
  labelsNote?: string;
  onLink: (input: AssociationLinkInput) => Promise<void>;
}) {
  const toast = useToast();
  const [record, setRecord] = useState<AssociationCandidate | null>(null);
  const [isPrimary, setIsPrimary] = useState(false);
  const [labelIds, setLabelIds] = useState<Set<string>>(new Set());
  // fresh fields every time the drawer opens (the search box is keyed on `session`)
  const [session, setSession] = useState(0);
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) {
      setSession((n) => n + 1);
      setRecord(null);
      setIsPrimary(false);
      setLabelIds(new Set());
    }
  }
  const {
    labels,
    loaded,
    failed: labelsFailed,
  } = useAssociationLabels(anchorType, targetType, open && labelsSupported);
  // two records of one type: paired labels read differently from each side
  const sameType = anchorType === targetType;
  const options = sameType ? pairedLabelOptions(labels) : labels;
  const names = namesOf(targetType, targetNames);
  const title = `Add ${names.one} to ${anchorName}`;
  const searchId = `${id}-search`;
  const labelsBlocked = labelsSupported && (!loaded || labelsFailed);

  const onSubmit = async () => {
    if (!record) return false;
    if (labelsBlocked) {
      toast(
        labelsFailed
          ? 'Labels could not be loaded. Try again before adding.'
          : 'Still loading labels…',
        'danger',
        { durationMs: 8000 },
      );
      return false;
    }
    try {
      await onLink({
        record,
        isPrimary: allowPrimary && isPrimary,
        ...splitPairedIds(labelIds),
      });
    } catch (err) {
      toast(associationErrorText(err), 'danger', { durationMs: 8000 });
      return false;
    }
  };

  return (
    <FormDrawer
      id={id}
      title={title}
      submitLabel="Add"
      open={open}
      onClose={onClose}
      onSubmit={onSubmit}
      submitDisabled={labelsBlocked}
    >
      <Field
        label={names.one.charAt(0).toUpperCase() + names.one.slice(1)}
        htmlFor={searchId}
        error={`Pick a ${names.one} from the list.`}
      >
        <RecordSearchInput
          key={session}
          id={searchId}
          type={targetType}
          names={names}
          value={record}
          onPick={(picked) => {
            setRecord(picked);
            if (picked) {
              document.getElementById(searchId)?.closest('.field')?.classList.remove('is-invalid');
            }
          }}
          linkedIds={new Set(linkedIds)}
        />
        <input type="hidden" name="recordId" value={record?.id ?? ''} required />
      </Field>

      {allowPrimary ? (
        <div className="field">
          <label className="check">
            <input
              type="checkbox"
              checked={isPrimary || !hasPrimary}
              disabled={!hasPrimary}
              onChange={(e) => setIsPrimary(e.target.checked)}
            />
            <span className="check__box" aria-hidden />
            <span>Make primary {names.one}</span>
          </label>
          {!hasPrimary ? (
            <p className="crm-text-body-secondary" style={{ marginTop: 6 }}>
              The first {names.one} linked becomes the primary one.
            </p>
          ) : null}
        </div>
      ) : null}

      {labelsSupported ? (
        <div className="field">
          <span className="field__label">Association labels (optional)</span>
          {!loaded ? (
            <p className="crm-text-body-secondary">Loading labels…</p>
          ) : labelsFailed ? (
            <p className="crm-text-body-secondary" role="alert">
              Labels could not be loaded. Close and try again — adding is blocked so paired labels
              are not flipped by mistake.
            </p>
          ) : labels.length === 0 ? (
            <p className="crm-text-body-secondary">
              No labels are set up for {OBJECT_NAMES[anchorType].one} – {names.one} links. An admin
              can add them in Settings.
            </p>
          ) : (
            <LabelChecklist labels={options} selected={labelIds} onChange={setLabelIds} />
          )}
          {sameType && loaded && !labelsFailed && labels.length > 0 ? (
            <p className="crm-text-body-secondary" style={{ marginTop: 6 }}>
              Pick what the {names.one} is to {anchorName}. It sees the paired label for{' '}
              {anchorName}.
            </p>
          ) : null}
          {labelsNote && loaded && !labelsFailed && labels.length > 0 ? (
            <p className="crm-text-body-secondary" style={{ marginTop: 6 }}>
              {labelsNote}
            </p>
          ) : null}
        </div>
      ) : null}
    </FormDrawer>
  );
}
