'use client';

import { useEffect, useState } from 'react';
import { LIMIT_MESSAGE, limitProblem } from '../associationLimit';
import { listAssociationLabelHistory } from '@/features/associations/api.client';
import type {
  AssociationLabel,
  AssociationLabelHistoryEntry,
  CreateAssociationLabelBody,
} from '@/features/associations/types';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  createBody,
  internalNameOf,
  limitSentences,
  step1Check,
  type LabelDraft,
} from '../labelCreate';
import type { DmObject } from '../model';
import { historyTimeText } from '../zoneText';
import { DmIcon } from './icons';
import { Drawer, DrawerHead, Modal } from './primitives';

type Side = { name: string; singular: string; icon: string };

/** The design's target node in the limit diagram: a stack ("Many") or the number (data-model.js). */
function TargetNode({ limit }: { limit: number | null }) {
  return (
    <div className="dm-al-flow__node dm-al-flow__node--target">
      <DmIcon name={limit === null ? 'copy' : 'square'} size={14} />
      <span>{limit === null ? 'Many' : limit}</span>
    </div>
  );
}

/**
 * Step 2, "Configure label limit" (data-model.js:4044-4110), also the one-label limit drawer
 * (D9): each direction Many or Custom, and the live diagram with its two sentences.
 */
function LimitStep({
  draft,
  from,
  to,
  self,
  onChange,
  onProblem,
}: {
  draft: LabelDraft;
  from: Side;
  to: Side;
  self: boolean;
  onChange: (patch: Partial<LabelDraft>) => void;
  /** #559: whether a Custom box holds text that isn't a limit (the action stays off). */
  onProblem: (has: boolean) => void;
}) {
  const text = limitSentences(draft, from, to, self);
  // #559: what each Custom box holds, and whether the browser couldn't read it (badInput).
  const [typed, setTyped] = useState({
    fromLimit: draft.fromLimit === null ? '1' : String(draft.fromLimit),
    toLimit: draft.toLimit === null ? '1' : String(draft.toLimit),
  });
  const [bad, setBad] = useState({ fromLimit: false, toLimit: false });
  const problemOf = (key: 'fromLimit' | 'toLimit') =>
    draft[key] === null
      ? null
      : typed[key].trim()
        ? limitProblem(typed[key], bad[key])
        : LIMIT_MESSAGE;
  const anyProblem = Boolean(problemOf('fromLimit') || problemOf('toLimit'));
  useEffect(() => onProblem(anyProblem), [anyProblem, onProblem]);
  const single = draft.kind === 'single';
  const l1 = single ? draft.single.trim() : draft.pairFrom.trim();
  const l2 = single ? draft.single.trim() : draft.pairTo.trim();
  const direction = (
    key: 'fromLimit' | 'toLimit',
    title: string,
    others: string,
    label: string,
  ) => {
    const value = draft[key];
    const problem = problemOf(key);
    return (
      <div className="dm-al-section">
        <div className="dm-al-section__title">{title}</div>
        <label className="dm-al-radio-row">
          <input
            type="radio"
            name={key}
            checked={value === null}
            onChange={() => onChange({ [key]: null })}
          />
          <span>
            Many {others} can have label &quot;{label}&quot;
          </span>
        </label>
        <label className="dm-al-radio-row">
          <input
            type="radio"
            name={key}
            checked={value !== null}
            onChange={() => onChange({ [key]: Number(typed[key]) >= 1 ? Number(typed[key]) : 1 })}
          />
          <span>Custom</span>
        </label>
        {value !== null && (
          <label className="dm-al-custom-wrap">
            <input
              type="number"
              min={1}
              max={10000}
              className="dm-al-num-input"
              aria-label={`${title} limit`}
              aria-invalid={Boolean(problem)}
              value={typed[key]}
              onInput={(e) => {
                const badInput = e.currentTarget.validity.badInput;
                setBad((cur) => ({ ...cur, [key]: badInput }));
              }}
              onChange={(e) => {
                const v = e.target.value;
                setTyped((cur) => ({ ...cur, [key]: v }));
                if (v.trim() && !limitProblem(v)) onChange({ [key]: Number(v) });
              }}
            />
            {problem && <span className="dm-field__error">{problem}</span>}
          </label>
        )}
      </div>
    );
  };
  return (
    <>
      {direction('fromLimit', `${from.singular}-to-${to.name}`, to.name, text.fromLabel)}
      {direction('toLimit', `${to.singular}-to-${from.name}`, from.name, text.toLabel)}
      <div className="dm-al-diagram">
        {(
          [
            [from, text.fromLabel, l1, l2, draft.fromLimit, text.s1],
            [to, text.toLabel, l2, l1, draft.toLimit, text.s2],
          ] as const
        ).map(([o, pill, a, b, limit, sentence], i) => (
          <div key={i} className="dm-al-diagram-item">
            <div className="dm-al-flow">
              <div className="dm-al-flow__node">
                <DmIcon name={o.icon} size={14} />
                <span>{o.singular}</span>
              </div>
              <div className="dm-al-flow__line">
                {single ? (
                  <span className="dm-al-flow__pill">{pill}</span>
                ) : (
                  <div className="dm-al-split-pill">
                    <span>{a}</span>
                    <span>{b}</span>
                  </div>
                )}
              </div>
              <TargetNode limit={limit} />
            </div>
            <div className="dm-al-diagram__sentence">{sentence}</div>
          </div>
        ))}
      </div>
    </>
  );
}

const EMPTY: LabelDraft = {
  kind: 'single',
  single: '',
  pairFrom: '',
  pairTo: '',
  internal: '',
  fromLimit: null,
  toLimit: null,
};

/**
 * D6 (DMG11): the design's two-step "Create a new association label" drawer
 * (data-model.js:3883-4321). Step 1: the objects, a single label or a pair (each pair label
 * unique), the internal name (pencil to change it). Step 2: each direction's limit (D7).
 */
export function CreateLabelDrawer({
  from,
  to,
  targets,
  onClose,
  onCreate,
}: {
  from: DmObject;
  /** The other object when the page chose it; null: picked here. */
  to: DmObject | null;
  /** The objects a label can link \`from\` to (when \`to\` is null). */
  targets: DmObject[];
  onClose: () => void;
  /** Resolves false to keep the drawer open (the API refused it). */
  onCreate: (body: CreateAssociationLabelBody) => Promise<boolean | void>;
}) {
  const [step, setStep] = useState<1 | 2>(1);
  const [draft, setDraft] = useState<LabelDraft>(EMPTY);
  const [target, setTarget] = useState<DmObject | null>(to ?? targets[0] ?? null);
  const [editInternal, setEditInternal] = useState(false);
  const [busy, setBusy] = useState(false);
  const [limitBad, setLimitBad] = useState(false);
  const change = (patch: Partial<LabelDraft>) => setDraft((d) => ({ ...d, ...patch }));
  const self = target?.key === from.key;
  const check = step1Check(draft);
  const internal = target ? internalNameOf(draft, target, self) : '';
  const close = () => {
    if (!busy) onClose();
  };
  const title = step === 1 ? 'Create a new association label' : 'Configure label limit';
  const internalRow = (
    <>
      <div className="dm-al-internal">
        <span>Internal name:</span> <code>{internal}</code>
        <button
          type="button"
          className="dm-icon-btn dm-icon-btn--xs"
          title="Edit internal name"
          aria-label="Edit internal name"
          onClick={() => {
            setEditInternal(true);
            if (!draft.internal) change({ internal });
          }}
        >
          <DmIcon name="pencil" size={12} />
        </button>
      </div>
      {editInternal && (
        <input
          type="text"
          className="dm-input dm-input--sm"
          aria-label="Internal name"
          value={draft.internal}
          onChange={(e) => change({ internal: e.target.value })}
        />
      )}
    </>
  );
  return (
    <Drawer open onClose={close} label={title}>
      <DrawerHead title={title} onClose={close} />
      <div className="dm-drawer__body">
        {step === 1 ? (
          <>
            <p className="dm-drawer__note">
              Association labels describe a relationship between two objects. You can edit a label
              later, but you can&apos;t switch between a single label and a pair of labels.
            </p>
            <div className="dm-field">
              <label className="dm-field__label" htmlFor="dm-al-target">
                Objects you&apos;re associating
              </label>
              {to ? (
                <input
                  id="dm-al-target"
                  type="text"
                  className="dm-input"
                  value={`${from.name}-to-${to.name}`}
                  readOnly
                />
              ) : (
                <select
                  id="dm-al-target"
                  className="dm-input"
                  value={target?.key ?? ''}
                  onChange={(e) => setTarget(targets.find((t) => t.key === e.target.value) ?? null)}
                >
                  {targets.map((t) => (
                    <option key={t.key} value={t.key}>
                      {from.name}-to-{t.name}
                    </option>
                  ))}
                </select>
              )}
            </div>
            <div className="dm-field">
              <span className="dm-field__label">How many labels do you need?</span>
              {(
                [
                  [
                    'single',
                    'A single label',
                    'The objects are related in the same way and can have the same label.',
                  ],
                  [
                    'pair',
                    'A pair of labels',
                    'The objects are related in different ways and need their own labels.',
                  ],
                ] as const
              ).map(([kind, cardTitle, desc]) => (
                <div key={kind} className={cn('dm-al-card', draft.kind === kind && 'is-selected')}>
                  <label className="dm-al-card__header">
                    <input
                      type="radio"
                      name="dm-al-kind"
                      checked={draft.kind === kind}
                      onChange={() => change({ kind, internal: '' })}
                    />
                    <div>
                      <div className="dm-al-card__title">{cardTitle}</div>
                      <div className="dm-al-card__desc">{desc}</div>
                    </div>
                  </label>
                  {draft.kind === kind && kind === 'single' && (
                    <div className="dm-al-card__body">
                      <input
                        type="text"
                        className="dm-input"
                        placeholder="Colleague"
                        aria-label="Label"
                        value={draft.single}
                        onChange={(e) => change({ single: e.target.value })}
                      />
                      {internalRow}
                    </div>
                  )}
                  {draft.kind === kind && kind === 'pair' && (
                    <div className="dm-al-card__body">
                      <div className="dm-al-grid-2">
                        <div>
                          <label className="dm-al-sublabel">{from.name}</label>
                          <input
                            type="text"
                            className="dm-input"
                            placeholder="Manager"
                            aria-label={`${from.name} label`}
                            value={draft.pairFrom}
                            onChange={(e) => change({ pairFrom: e.target.value })}
                          />
                        </div>
                        <div>
                          <label className="dm-al-sublabel">{target?.name}</label>
                          <input
                            type="text"
                            className="dm-input"
                            placeholder={self ? 'Employee' : 'Contractor'}
                            aria-label={`${target?.name ?? 'Other'} label`}
                            value={draft.pairTo}
                            onChange={(e) => change({ pairTo: e.target.value })}
                          />
                        </div>
                      </div>
                      {check.pairError && (
                        <p className="dm-al-error" role="alert">
                          <DmIcon name="alert" size={13} />
                          {check.pairError}
                        </p>
                      )}
                      {internalRow}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </>
        ) : (
          target && (
            <>
              <p className="dm-drawer__note">
                Configure the number of records that can be associated using this label. This
                won&apos;t affect older data.
              </p>
              <LimitStep
                draft={draft}
                from={from}
                to={target}
                self={self}
                onChange={change}
                onProblem={setLimitBad}
              />
            </>
          )
        )}
      </div>
      <div className="dm-drawer__foot">
        {step === 1 ? (
          <button type="button" className="dm-btn dm-btn--ghost" onClick={close}>
            Cancel
          </button>
        ) : (
          <button
            type="button"
            className="dm-btn dm-btn--outline"
            onClick={() => setStep(1)}
            disabled={busy}
          >
            Back
          </button>
        )}
        <span className="dm-grow" />
        <span className="dm-muted">Step {step} of 2</span>
        {step === 1 ? (
          <button
            type="button"
            className="dm-btn dm-btn--primary"
            disabled={!check.valid || !target}
            onClick={() => setStep(2)}
          >
            Next
          </button>
        ) : (
          <button
            type="button"
            className="dm-btn dm-btn--primary"
            disabled={busy || !target || limitBad}
            onClick={async () => {
              if (!target) return;
              setBusy(true);
              let keep: boolean | void = false;
              try {
                keep = await onCreate(createBody(draft, from.key, target.key, internal));
              } finally {
                setBusy(false);
              }
              if (keep !== false) onClose();
            }}
          >
            Create
          </button>
        )}
      </div>
    </Drawer>
  );
}

/**
 * D9 (DMG11): the design's "Configure label limit" for one label (data-model.js:4419-4672), with
 * a limit for each direction (D7). \`fromLimit\` is this object's side.
 */
export function LabelLimitDrawer({
  from,
  to,
  label,
  pairedWith,
  fromLimit,
  toLimit,
  onClose,
  onSave,
}: {
  from: Side & { key: string };
  to: Side & { key: string };
  label: string;
  pairedWith: string | null;
  fromLimit: number | null;
  toLimit: number | null;
  onClose: () => void;
  /** The error to show, or nothing when saved. */
  onSave: (fromLimit: number | null, toLimit: number | null) => Promise<string | null>;
}) {
  const [draft, setDraft] = useState<LabelDraft>({
    ...EMPTY,
    kind: pairedWith ? 'pair' : 'single',
    single: label,
    // As the create drawer: the target's label is this side's name.
    pairFrom: pairedWith ?? '',
    pairTo: label,
    fromLimit,
    toLimit,
  });
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [limitBad, setLimitBad] = useState(false);
  const close = () => {
    if (!busy) onClose();
  };
  return (
    <Drawer open onClose={close} label="Configure label limit">
      <DrawerHead title="Configure label limit" onClose={close} />
      <div className="dm-drawer__body">
        <p className="dm-drawer__note">
          Configure the number of records that can be associated using this label. This won&apos;t
          affect older data.
        </p>
        <LimitStep
          draft={draft}
          from={from}
          to={to}
          self={from.key === to.key}
          onChange={(patch) => setDraft((d) => ({ ...d, ...patch }))}
          onProblem={setLimitBad}
        />
        {/* #559: why a limit is refused, said where it's set. */}
        {error && (
          <p className="dm-al-error" role="alert">
            <DmIcon name="alert" size={13} />
            {error}
          </p>
        )}
      </div>
      <div className="dm-drawer__foot">
        <button type="button" className="dm-btn dm-btn--ghost" onClick={close} disabled={busy}>
          Cancel
        </button>
        <span className="dm-grow" />
        <button
          type="button"
          className="dm-btn dm-btn--primary"
          disabled={busy || limitBad}
          onClick={async () => {
            setBusy(true);
            let problem: string | null = null;
            try {
              problem = await onSave(draft.fromLimit, draft.toLimit);
            } finally {
              setBusy(false);
            }
            if (problem) setError(problem);
            else onClose();
          }}
        >
          Save
        </button>
      </div>
    </Drawer>
  );
}

const HISTORY_ACTION: Record<string, string> = {
  'association_label.created': 'Label created',
  'association_label.renamed': 'Label changed',
  'association_label.archived': 'Label archived',
};

/**
 * D11 (DMG11): the design's label history dialog (data-model.js:5251-5302): Category, Object
 * association, Date created, Created by, and the expandable list of what happened.
 */
export function LabelHistoryModal({
  label,
  shownName,
  from,
  to,
  onClose,
}: {
  label: AssociationLabel;
  shownName: string;
  from: { name: string };
  to: { name: string };
  onClose: () => void;
}) {
  const { timeZone } = useUserPrefs();
  const [entries, setEntries] = useState<AssociationLabelHistoryEntry[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [open, setOpen] = useState(true);
  useEffect(() => {
    let alive = true;
    listAssociationLabelHistory(label.id).then(
      (rows) => alive && setEntries(rows),
      (err: unknown) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [label.id]);
  const created = entries?.find((e) => e.action === 'association_label.created');
  const createdBy =
    label.category === 'system' ? 'CRM' : (created?.actorName ?? (entries ? 'Unknown' : '…'));
  return (
    <Modal
      title={`History: ${shownName}`}
      okLabel="Close"
      noCancel
      onClose={onClose}
      onOk={() => undefined}
    >
      <div className="dm-history-modal-body">
        <ul className="dm-history-meta-list">
          <li className="dm-history-meta-item">
            <strong>Category:</strong>{' '}
            {label.category === 'system' ? 'CRM defined' : 'User defined'}
          </li>
          <li className="dm-history-meta-item">
            <strong>Object association:</strong> {from.name} to {to.name}
          </li>
          <li className="dm-history-meta-item">
            <strong>Date created:</strong>{' '}
            {label.createdAt ? historyTimeText(label.createdAt, timeZone) : '--'}
          </li>
          <li className="dm-history-meta-item">
            <strong>Created by:</strong> {createdBy}
          </li>
        </ul>
        <div className="dm-history-timeline-box">
          <button
            type="button"
            className="dm-history-timeline-btn"
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
          >
            <span className="dm-history-chevron-icon">
              <DmIcon name={open ? 'chevron-down' : 'chevron-right'} size={14} />
            </span>
            History
          </button>
          {open && (
            <div className="dm-history-timeline-content">
              {error ? (
                <p className="dm-error" role="alert">
                  {error}
                </p>
              ) : entries === null ? (
                <p className="dm-muted">Loading…</p>
              ) : entries.length === 0 ? (
                <p className="dm-muted">No changes recorded for this label.</p>
              ) : (
                entries.map((e) => (
                  <p key={e.id} className="dm-history-detail-text">
                    {historyTimeText(e.createdAt, timeZone)} -{' '}
                    {HISTORY_ACTION[e.action] ?? e.action}
                    {e.changes && Object.keys(e.changes).length
                      ? ` (${Object.keys(e.changes).join(', ')})`
                      : ''}
                    {e.actorName ? ` by ${e.actorName}` : ''}
                  </p>
                ))
              )}
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
}
