'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
import type { StageFieldSpec } from '@/features/pipelines/stageFields';
import { useToast } from '@/components/crm/ToastProvider';
import { DmIcon } from '@/features/data-model/ui/icons';
import {
  archivePipeline,
  archivePipelineStage,
  createPipeline,
  createPipelineStage,
  listPipelines,
  listStageRecordCounts,
  reorderPipelineStages,
  restorePipeline,
  restorePipelineStage,
  updatePipeline,
  updatePipelineStage,
  type Pipeline,
  type PipelineStage,
  type StageType,
} from '@/features/pipelines/api.client';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { updateObjectDefinition } from '@/features/objects/api.client';
import { isSuperAdmin } from '@/features/permission-sets/property-settings';
import { accessOf, accessSummary, canLimitPipelines } from '@/features/pipelines/access';
import { isLeadObject } from '@/features/objects/leads';
import { isTicketObject } from '@/features/pipelines/stageRules';
import type { ObjectDefinition, StageDisplayStyle } from '@/features/objects/types';
import type { StageProperty } from '@/features/pipelines/api.client';
import { dealFieldSpecs, recordFieldSpecs } from '@/features/pipelines/stageFields';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DrawerForm } from '../settings-ui';
import { settingsHref, type OsObject } from './config';
import { PipelineAccessSection } from './PipelineAccessSection';
import { OsDropdown, Soon, StyleCards, SwitchRow, Tip } from './primitives';
import { StageColorCell, StageLogicCell, StageRequiredCell } from './StageRulesCells';
import { TagsPanel } from './TagsPanel';

const STAGE_TYPE_LABELS: Record<StageType, string> = { open: 'Open', won: 'Won', lost: 'Lost' };
/** Tickets (QA 978): a stage is Open or Closed (stored as the closing "won" type). */
const TICKET_STAGE_LABELS: Record<StageType, string> = {
  open: 'Open',
  won: 'Closed',
  lost: 'Closed',
};

const byOrder = (
  a: { displayOrder: number; id: string },
  b: { displayOrder: number; id: string },
) => a.displayOrder - b.displayOrder || a.id.localeCompare(b.id);

/**
 * Pipelines (Overview | <Object> Tags): the object's pipelines (GET /pipelines) with Edit (its
 * stages), Rename, Clone and Delete (archive). Deals use the default object type.
 */
export function PipelinesTab({
  object: o,
  sub,
  canManage,
  onSaved,
}: {
  object: OsObject;
  sub: string | null;
  canManage: boolean;
  /** LP5: the object definition after "Set pipeline display colors" saved (the page keeps it). */
  onSaved?: (definition: ObjectDefinition) => void;
}) {
  const toast = useToast();
  // DL15a: admins limit Deals, Leads and Tickets pipelines (HubSpot's super admins).
  const isAdmin = isSuperAdmin(useCurrentUser());
  const limitable = canLimitPipelines(o.key);
  const objectType = o.kind === 'builtIn' ? undefined : o.key;
  const one = o.singular;
  const lc = one.toLowerCase();
  // LP5: a custom object's "Set pipeline display colors" (Deals keep Coming soon).
  const definition = o.definition;
  const [displayStyle, setDisplayStyle] = useState<StageDisplayStyle>(
    definition?.stageDisplayStyle ?? 'none',
  );
  const [savingStyle, setSavingStyle] = useState(false);
  const saveDisplayStyle = async (next: StageDisplayStyle) => {
    if (!definition) return;
    const before = displayStyle;
    setDisplayStyle(next);
    setSavingStyle(true);
    try {
      const saved = await updateObjectDefinition(definition.id, { stageDisplayStyle: next });
      // The page keeps the definitions: a tab opened again shows what was saved.
      onSaved?.(saved);
      toast('Display colors updated', 'success');
    } catch (err) {
      setDisplayStyle(before);
      toast(errorText(err), 'danger');
    } finally {
      setSavingStyle(false);
    }
  };

  const [pipelines, setPipelines] = useState<Pipeline[] | null>(null);
  const [counts, setCounts] = useState<Record<string, number>>({});
  const [error, setError] = useState<string | null>(null);
  const [q, setQ] = useState('');
  const [showArchived, setShowArchived] = useState(false);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);

  const [creating, setCreating] = useState(false);
  const [renaming, setRenaming] = useState<Pipeline | null>(null);
  const [addingStageTo, setAddingStageTo] = useState<string | null>(null);
  const [editingStage, setEditingStage] = useState<{
    pipelineId: string;
    stage: PipelineStage;
  } | null>(null);

  const load = useCallback(async () => {
    setError(null);
    const [list, stageCounts] = await Promise.allSettled([
      listPipelines({ includeArchived: true, ...(objectType ? { objectType } : {}) }),
      listStageRecordCounts({ objectType: o.key }),
    ]);
    if (list.status === 'fulfilled') {
      setPipelines([...list.value].sort(byOrder));
    } else {
      setPipelines([]);
      setError(errorText(list.reason));
    }
    if (stageCounts.status === 'fulfilled') {
      setCounts(Object.fromEntries(stageCounts.value.map((c) => [c.stageId, c.records])));
    }
  }, [o.key, objectType]);

  useEffect(() => {
    setPipelines(null);
    setEditingId(null);
    void load();
  }, [load]);

  // 24 Nov: the fields a stage can require (Required to enter, Deals' conditional logic).
  const [fieldDefs, setFieldDefs] = useState<CustomPropertyDefinition[]>([]);
  useEffect(() => {
    let alive = true;
    listCustomProperties({ objectType: o.key })
      .then((defs) => alive && setFieldDefs(defs))
      .catch(() => alive && setFieldDefs([]));
    return () => {
      alive = false;
    };
  }, [o.key]);
  const isDeal = o.key === 'deal';
  const lead = o.definition ? isLeadObject(o.definition) : false;
  const ticket = o.definition ? isTicketObject(o.definition) : false;
  const fieldSpecs = useMemo(
    () =>
      isDeal
        ? dealFieldSpecs({ defs: fieldDefs, owners: [], dealTypes: [] })
        : recordFieldSpecs({ singular: one, defs: fieldDefs, owners: [] }),
    [isDeal, fieldDefs, one],
  );

  /** Saves a stage's colour or entry properties; false when the API refused (toast shown). */
  const patchStage = async (
    pipelineId: string,
    stage: PipelineStage,
    body: { color?: string | null; properties?: StageProperty[] },
    message: string,
  ): Promise<boolean> => {
    if (!canManage) return false;
    try {
      const saved = await updatePipelineStage(pipelineId, stage.id, body);
      setPipelines((cur) =>
        (cur ?? []).map((p) =>
          p.id === pipelineId
            ? { ...p, stages: p.stages.map((s) => (s.id === saved.id ? { ...s, ...saved } : s)) }
            : p,
        ),
      );
      toast(message, 'success');
      return true;
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const replace = (saved: Pipeline) =>
    setPipelines((cur) => (cur ?? []).map((p) => (p.id === saved.id ? saved : p)).sort(byOrder));

  const run = async (id: string, action: () => Promise<void>) => {
    if (!canManage || busyId) return;
    setBusyId(id);
    try {
      await action();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusyId(null);
    }
  };

  const onClone = (p: Pipeline) =>
    run(p.id, async () => {
      const stages = p.stages.filter((s) => !s.archived).sort(byOrder);
      const created = await createPipeline({
        name: `${p.name} (copy)`,
        ...(objectType ? { objectType } : {}),
        stages: stages.map((s) => ({
          name: s.name,
          stageType: s.stageType,
          probability: s.probability,
          ...(s.color ? { color: s.color } : {}),
          ...(s.properties?.length ? { properties: s.properties } : {}),
        })),
      });
      setPipelines((cur) => [...(cur ?? []), created].sort(byOrder));
      toast('Pipeline cloned.', 'success');
    });

  const onArchive = (p: Pipeline, archive: boolean) => {
    if (
      !window.confirm(
        `${archive ? 'Delete' : 'Restore'} pipeline "${p.name}"?${archive ? ' It is archived: its records are kept and it can be restored.' : ''}`,
      )
    )
      return;
    void run(p.id, async () => {
      replace(archive ? await archivePipeline(p.id) : await restorePipeline(p.id));
      if (archive && editingId === p.id) setEditingId(null);
      toast(`Pipeline ${archive ? 'deleted' : 'restored'}.`, 'success');
    });
  };

  const visible = useMemo(() => {
    const query = q.trim().toLowerCase();
    return (pipelines ?? []).filter(
      (p) => (showArchived || !p.archived) && (!query || p.name.toLowerCase().includes(query)),
    );
  }, [pipelines, q, showArchived]);
  const live = (pipelines ?? []).filter((p) => !p.archived).length;
  const editing = (pipelines ?? []).find((p) => p.id === editingId) ?? null;
  const isTags = sub === 'tags';

  return (
    <section className="os-panel" aria-label="Pipelines">
      <nav className="os-subtabs os-subtabs--flat" aria-label="Pipelines">
        <Link
          className={cn('os-subtab', !isTags && 'is-active')}
          href={settingsHref(o.key, 'pipelines')}
          aria-current={!isTags ? 'page' : undefined}
        >
          Overview
        </Link>
        <Link
          className={cn('os-subtab', isTags && 'is-active')}
          href={settingsHref(o.key, 'pipelines', { sub: 'tags' })}
          aria-current={isTags ? 'page' : undefined}
        >
          {one} Tags
        </Link>
      </nav>

      {isTags ? (
        <TagsPanel object={o} canManage={canManage} />
      ) : (
        <>
          <p className="os-field-label">
            Set pipeline display colors{' '}
            {definition ? (
              <Tip text="How stage names look on this object's list and board." />
            ) : (
              <>
                <Tip text="How stage names look on boards, records and filters." /> <Soon />
              </>
            )}
          </p>
          {definition ? (
            <StyleCards
              value={displayStyle}
              disabled={!canManage || savingStyle}
              onChange={(next) => void saveDisplayStyle(next)}
            />
          ) : (
            <StyleCards disabled />
          )}

          <div className="os-pl-bar">
            <label className="os-search">
              <input
                type="search"
                placeholder="Search pipelines"
                aria-label="Search pipelines"
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
              <DmIcon name="search" size={16} />
            </label>
            <label className="os-check-inline">
              <span className="check">
                <input
                  type="checkbox"
                  checked={showArchived}
                  onChange={(e) => setShowArchived(e.target.checked)}
                />
                <span className="check__box" aria-hidden />
              </span>
              Show deleted
            </label>
            <span className="os-grow" />
            <span className="os-pl-count">
              {live} {lc} pipeline{live === 1 ? '' : 's'}
            </span>
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={!canManage}
              onClick={() => setCreating(true)}
            >
              Create pipeline
            </button>
          </div>

          {error ? <p className="os-num-field__err">{error}</p> : null}
          <div className="os-table-wrap">
            <table className="os-table os-pl-table">
              <thead>
                <tr>
                  <th>Pipeline</th>
                  <th>Pipeline description</th>
                  <th>{one} tags</th>
                  <th>
                    Pipeline rules{' '}
                    <Tip text="Rules that limit how records move between stages, such as not moving backwards." />
                  </th>
                  <th>Number of stages</th>
                  <th>Internal ID</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {visible.map((p) => (
                  <tr key={p.id}>
                    <td>
                      <span className="os-pl-name">
                        <button
                          type="button"
                          className="os-link"
                          onClick={() => setEditingId(p.id)}
                        >
                          {p.name}
                        </button>
                        {p.archived ? <span className="os-tag">Deleted</span> : null}
                        {limitable && accessOf(p).restricted ? (
                          <span className="os-tag" title={accessSummary(accessOf(p))}>
                            Limited access
                          </span>
                        ) : null}
                      </span>
                    </td>
                    <td>--</td>
                    <td>--</td>
                    <td>{p.allowBackwardMoves ? 0 : 1}</td>
                    <td>{p.stages.filter((s) => !s.archived).length}</td>
                    <td>
                      <code className="os-code">{p.id}</code>
                    </td>
                    <td>
                      <OsDropdown
                        className="os-actions os-actions--sm"
                        align="end"
                        width={180}
                        disabled={busyId === p.id}
                        label={
                          <>
                            Actions
                            <DmIcon name="caret" size={14} />
                          </>
                        }
                      >
                        {(close) => (
                          <div role="menu">
                            <button
                              type="button"
                              className="os-menu__item"
                              role="menuitem"
                              onClick={() => {
                                close();
                                setEditingId(p.id);
                              }}
                            >
                              Edit pipeline
                            </button>
                            <button
                              type="button"
                              className="os-menu__item"
                              role="menuitem"
                              disabled={!canManage}
                              onClick={() => {
                                close();
                                setRenaming(p);
                              }}
                            >
                              Rename
                            </button>
                            <button
                              type="button"
                              className="os-menu__item"
                              role="menuitem"
                              disabled={!canManage}
                              onClick={() => {
                                close();
                                void onClone(p);
                              }}
                            >
                              Clone
                            </button>
                            <button
                              type="button"
                              className={cn(
                                'os-menu__item',
                                !p.archived && 'os-menu__item--danger',
                              )}
                              role="menuitem"
                              disabled={!canManage}
                              onClick={() => {
                                close();
                                onArchive(p, !p.archived);
                              }}
                            >
                              {p.archived ? 'Restore' : 'Delete'}
                            </button>
                          </div>
                        )}
                      </OsDropdown>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {pipelines === null ? (
              <p className="os-noresults">Loading pipelines…</p>
            ) : visible.length === 0 ? (
              <p className="os-noresults">
                {live || q
                  ? 'No pipelines match your search.'
                  : `No ${o.plural.toLowerCase()} pipelines yet. Create your first pipeline to get started.`}
              </p>
            ) : null}
          </div>

          {editing ? (
            <StageEditor
              pipeline={editing}
              noun={o.plural.toLowerCase()}
              singular={lc}
              isDeal={isDeal}
              lead={lead}
              ticket={ticket}
              fieldSpecs={fieldSpecs}
              onPatchStage={(stage, body, message) => patchStage(editing.id, stage, body, message)}
              counts={counts}
              canManage={canManage && !editing.archived}
              busyId={busyId}
              onClose={() => setEditingId(null)}
              onAddStage={() => setAddingStageTo(editing.id)}
              onEditStage={(stage) => setEditingStage({ pipelineId: editing.id, stage })}
              onBackwardMoves={(allow) =>
                void run(editing.id, async () => {
                  replace(await updatePipeline(editing.id, { allowBackwardMoves: allow }));
                  toast('Pipeline rule saved.', 'success');
                })
              }
              onLostReasonRequired={(required) =>
                void run(editing.id, async () => {
                  replace(await updatePipeline(editing.id, { lostReasonRequired: required }));
                  toast('Pipeline rule saved.', 'success');
                })
              }
              onWonReasonRequired={(required) =>
                void run(editing.id, async () => {
                  replace(await updatePipeline(editing.id, { wonReasonRequired: required }));
                  toast('Pipeline rule saved.', 'success');
                })
              }
              accessSection={
                limitable ? (
                  <PipelineAccessSection
                    pipeline={editing}
                    noun={o.plural.toLowerCase()}
                    isAdmin={isAdmin && !editing.archived}
                    busy={busyId === editing.id}
                    onSave={(access) =>
                      void run(editing.id, async () => {
                        replace(await updatePipeline(editing.id, { access }));
                        toast('Pipeline access saved.', 'success');
                      })
                    }
                  />
                ) : null
              }
              onMove={(stage, step) =>
                void run(stage.id, async () => {
                  const shown = editing.stages.filter((s) => !s.archived).sort(byOrder);
                  const neighbor = shown[shown.findIndex((s) => s.id === stage.id) + step];
                  if (!neighbor) return;
                  const ordered = [...editing.stages].sort(byOrder);
                  const from = ordered.findIndex((s) => s.id === stage.id);
                  const to = ordered.findIndex((s) => s.id === neighbor.id);
                  ordered[from] = neighbor;
                  ordered[to] = stage;
                  replace(
                    await reorderPipelineStages(
                      editing.id,
                      ordered.map((s) => s.id),
                    ),
                  );
                })
              }
              onArchiveStage={(stage, archive) => {
                if (!window.confirm(`${archive ? 'Delete' : 'Restore'} stage "${stage.name}"?`))
                  return;
                void run(stage.id, async () => {
                  const saved = archive
                    ? await archivePipelineStage(editing.id, stage.id)
                    : await restorePipelineStage(editing.id, stage.id);
                  replace({
                    ...editing,
                    stages: editing.stages.map((s) => (s.id === stage.id ? { ...s, ...saved } : s)),
                  });
                  toast(
                    archive && saved.openDeals > 0
                      ? `Stage deleted (${saved.openDeals} open ${o.plural.toLowerCase()} remain in that stage).`
                      : `Stage ${archive ? 'deleted' : 'restored'}.`,
                    archive && saved.openDeals > 0 ? 'info' : 'success',
                  );
                });
              }}
            />
          ) : null}
        </>
      )}

      <DrawerForm
        id="os-create-pipeline"
        title="Create pipeline"
        open={creating}
        onClose={() => setCreating(false)}
        submitLabel="Create"
        onSave={async (data) => {
          const name = String(data.get('name') ?? '').trim();
          const firstStage = String(data.get('firstStage') ?? '').trim();
          const probability = Number(data.get('probability') ?? 10);
          if (!name || !firstStage) return false;
          try {
            const created = await createPipeline({
              name,
              ...(objectType ? { objectType } : {}),
              stages: [{ name: firstStage, stageType: 'open', probability }],
            });
            setPipelines((cur) => [...(cur ?? []), created].sort(byOrder));
            setEditingId(created.id);
            return 'Pipeline created';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      >
        <div className="field field--full">
          <label className="field__label" htmlFor="os-cp-name">
            Pipeline name
          </label>
          <input className="input" id="os-cp-name" name="name" required maxLength={191} />
        </div>
        <div className="field field--full">
          <label className="field__label" htmlFor="os-cp-stage">
            First stage name
          </label>
          <input className="input" id="os-cp-stage" name="firstStage" required maxLength={191} />
        </div>
        <div className="field field--full">
          <label className="field__label" htmlFor="os-cp-prob">
            First stage probability (%)
          </label>
          <input
            className="input"
            id="os-cp-prob"
            type="number"
            name="probability"
            min={0}
            max={100}
            step="0.01"
            defaultValue={10}
            required
          />
        </div>
      </DrawerForm>

      <DrawerForm
        key={renaming?.id ?? 'no-rename'}
        id="os-rename-pipeline"
        title="Rename pipeline"
        drawer={false}
        keep
        open={Boolean(renaming)}
        onClose={() => setRenaming(null)}
        onSave={async (data) => {
          if (!renaming) return false;
          const name = String(data.get('name') ?? '').trim();
          if (!name) return false;
          try {
            replace(await updatePipeline(renaming.id, { name }));
            return 'Pipeline renamed';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      >
        <div className="field field--full">
          <label className="field__label" htmlFor="os-rp-name">
            Pipeline name
          </label>
          <input
            className="input"
            id="os-rp-name"
            name="name"
            required
            maxLength={191}
            defaultValue={renaming?.name ?? ''}
          />
        </div>
      </DrawerForm>

      <StageForm
        key={addingStageTo ?? 'no-add'}
        id="os-add-pl-stage"
        ticket={ticket}
        title="Add stage"
        open={Boolean(addingStageTo)}
        onClose={() => setAddingStageTo(null)}
        onSave={async (body) => {
          if (!addingStageTo) return false;
          try {
            await createPipelineStage(addingStageTo, body);
            // The server shifts the other stages when one is added in the middle: reload them.
            await load();
            return 'Stage added';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      />

      <StageForm
        key={editingStage?.stage.id ?? 'no-edit'}
        id="os-edit-stage"
        ticket={ticket}
        title={editingStage ? `Edit ${editingStage.stage.name}` : 'Edit stage'}
        stage={editingStage?.stage}
        open={Boolean(editingStage)}
        onClose={() => setEditingStage(null)}
        onSave={async ({ name, stageType, probability }) => {
          if (!editingStage) return false;
          try {
            const saved = await updatePipelineStage(
              editingStage.pipelineId,
              editingStage.stage.id,
              {
                name,
                stageType,
                probability,
              },
            );
            setPipelines((cur) =>
              (cur ?? []).map((p) =>
                p.id === editingStage.pipelineId
                  ? {
                      ...p,
                      stages: p.stages.map((s) => (s.id === saved.id ? { ...s, ...saved } : s)),
                    }
                  : p,
              ),
            );
            return 'Stage saved';
          } catch (err) {
            toast(errorText(err), 'danger');
            return false;
          }
        }}
      />
    </section>
  );
}

/** "Edit pipeline": its stages (the design's stage table), order and backward-move rule. */
function StageEditor({
  pipeline: p,
  noun,
  singular,
  isDeal,
  lead,
  ticket,
  fieldSpecs,
  onPatchStage,
  counts,
  canManage,
  busyId,
  onClose,
  onAddStage,
  onEditStage,
  onBackwardMoves,
  onLostReasonRequired,
  onWonReasonRequired,
  accessSection,
  onMove,
  onArchiveStage,
}: {
  pipeline: Pipeline;
  noun: string;
  /** "lead": the Required to enter texts. */
  singular: string;
  /** Deals: conditional logic rules; other objects: Required to enter. */
  isDeal: boolean;
  /** Leads: the design's default stage colours. */
  lead: boolean;
  /** Tickets: stages are Open or Closed and carry no probability. */
  ticket: boolean;
  fieldSpecs: StageFieldSpec[];
  onPatchStage: (
    stage: PipelineStage,
    body: { color?: string | null; properties?: StageProperty[] },
    message: string,
  ) => Promise<boolean>;
  counts: Record<string, number>;
  canManage: boolean;
  busyId: string | null;
  onClose: () => void;
  onAddStage: () => void;
  onEditStage: (stage: PipelineStage) => void;
  onBackwardMoves: (allow: boolean) => void;
  /** DL3 (deals): "Require a closed lost reason". */
  onLostReasonRequired: (required: boolean) => void;
  onWonReasonRequired: (required: boolean) => void;
  /** DL15a: who can access the pipeline (Deals, Leads, Tickets). */
  accessSection?: ReactNode;
  onMove: (stage: PipelineStage, step: -1 | 1) => void;
  onArchiveStage: (stage: PipelineStage, archive: boolean) => void;
}) {
  const [showDeleted, setShowDeleted] = useState(false);
  const stages = [...p.stages].sort(byOrder).filter((s) => showDeleted || !s.archived);
  return (
    <div className="os-card os-gap-lg">
      <div className="os-tpl-head">
        <h2 className="os-h2">{p.name}</h2>
        <button type="button" className="os-x" aria-label="Close pipeline" onClick={onClose}>
          <DmIcon name="x" size={18} />
        </button>
      </div>
      <SwitchRow
        label="Limit ability to move backwards"
        help={`${noun.charAt(0).toUpperCase()}${noun.slice(1)} can only move forward to later stages.`}
        checked={!p.allowBackwardMoves}
        disabled={!canManage || busyId === p.id}
        onChange={(on) => onBackwardMoves(!on)}
      />
      {isDeal ? (
        // DL3 (user, 25 Nov 2026; beyond the design): HUB-392 asks why a deal was lost; off lets
        // the dialog be skipped. On for every pipeline until changed.
        <SwitchRow
          label="Require a closed lost reason"
          help="Moving or creating a deal in a closed lost stage asks for a Closed Lost Reason. Off: the reason can be skipped. Edit the reasons in Settings > Properties (Closed Lost Reason)."
          checked={p.lostReasonRequired !== false}
          disabled={!canManage || busyId === p.id}
          onChange={(on) => onLostReasonRequired(on)}
        />
      ) : null}
      {isDeal ? (
        // HUB-707 #752 (Sales audit): the Closed Won stage gate. Off for every pipeline (HubSpot's
        // default) until an admin turns it on.
        <SwitchRow
          label="Require a closed won reason"
          help="Moving or creating a deal in a closed won stage asks for a Closed Won Reason. Off: the reason can be skipped. Edit the reasons in Settings > Properties (Closed Won Reason)."
          checked={p.wonReasonRequired === true}
          disabled={!canManage || busyId === p.id}
          onChange={(on) => onWonReasonRequired(on)}
        />
      ) : null}
      {accessSection}
      <div className="os-tpl-head">
        <p className="os-field-label">Configure pipeline stages</p>
        <label className="os-check-inline">
          <span className="check">
            <input
              type="checkbox"
              checked={showDeleted}
              onChange={(e) => setShowDeleted(e.target.checked)}
            />
            <span className="check__box" aria-hidden />
          </span>
          Show deleted stages
        </label>
      </div>
      <div className="os-table-wrap">
        <table className="os-table">
          <thead>
            <tr>
              <th>Stage name</th>
              <th>{ticket ? 'Status' : 'Type'}</th>
              <th>
                Color{' '}
                <Tip
                  text={`Shown on the ${noun} board column, board cards and the stage stepper.`}
                />
              </th>
              {isDeal ? null : (
                <th>
                  Required to enter <span className="pe-new">New</span>{' '}
                  <Tip
                    text={`Reps must fill these fields before a ${singular} can move into this stage.`}
                  />
                </th>
              )}
              {ticket ? null : <th>Probability</th>}
              <th>Used in</th>
              {isDeal ? (
                <th>
                  Conditional logic rules <span className="pe-new">New</span>
                </th>
              ) : null}
              <th>Stage ID</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {stages.map((s, i) => (
              <tr key={s.id}>
                <td>
                  {s.name} {s.archived ? <span className="os-tag">Deleted</span> : null}
                </td>
                <td>{(ticket ? TICKET_STAGE_LABELS : STAGE_TYPE_LABELS)[s.stageType]}</td>
                <td>
                  <StageColorCell
                    stage={s}
                    lead={lead}
                    disabled={!canManage || s.archived}
                    onSave={(color) =>
                      void onPatchStage(s, { color }, `Color for ${s.name} saved.`)
                    }
                  />
                </td>
                {isDeal ? null : (
                  <td>
                    <StageRequiredCell
                      stage={s}
                      specs={fieldSpecs}
                      singular={singular}
                      disabled={!canManage || s.archived}
                      onSave={(properties) =>
                        onPatchStage(s, { properties }, `Required fields for ${s.name} saved.`)
                      }
                    />
                  </td>
                )}
                {ticket ? null : <td>{s.probability}%</td>}
                <td>{counts[s.id] ?? '--'}</td>
                {isDeal ? (
                  <td>
                    <StageLogicCell
                      stage={s}
                      pipelineName={p.name}
                      stages={stages.filter((x) => !x.archived)}
                      specs={fieldSpecs}
                      disabled={!canManage || s.archived}
                      onSave={(properties) =>
                        onPatchStage(
                          s,
                          { properties },
                          properties.length ? 'Conditional logic saved.' : 'Logic rule deleted.',
                        )
                      }
                    />
                  </td>
                ) : null}
                <td>
                  <code className="os-code">{s.id}</code>
                </td>
                <td>
                  <span className="os-inline-fields">
                    <button
                      type="button"
                      className="os-icon-btn"
                      aria-label={`Move ${s.name} up`}
                      disabled={!canManage || busyId !== null || s.archived || i === 0}
                      onClick={() => onMove(s, -1)}
                    >
                      <DmIcon name="arrow-up" size={16} />
                    </button>
                    <button
                      type="button"
                      className="os-icon-btn"
                      aria-label={`Move ${s.name} down`}
                      disabled={
                        !canManage || busyId !== null || s.archived || i === stages.length - 1
                      }
                      onClick={() => onMove(s, 1)}
                    >
                      <DmIcon name="arrow-down" size={16} />
                    </button>
                    <button
                      type="button"
                      className="os-link os-link--sm"
                      disabled={!canManage}
                      onClick={() => onEditStage(s)}
                    >
                      Edit
                    </button>
                    {s.archived ? (
                      <button
                        type="button"
                        className="os-link os-link--sm"
                        disabled={!canManage || busyId === s.id}
                        onClick={() => onArchiveStage(s, false)}
                      >
                        Restore
                      </button>
                    ) : (
                      <button
                        type="button"
                        className="os-icon-btn"
                        aria-label={`Delete ${s.name}`}
                        disabled={!canManage || busyId === s.id}
                        onClick={() => onArchiveStage(s, true)}
                      >
                        <DmIcon name="trash" size={16} />
                      </button>
                    )}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {stages.length === 0 ? <p className="os-noresults">No stages in this pipeline.</p> : null}
      </div>
      <button type="button" className="os-link os-gap" disabled={!canManage} onClick={onAddStage}>
        <DmIcon name="plus" size={14} /> Add stage
      </button>
    </div>
  );
}

/** Add or edit one stage: name, type and probability. */
function StageForm({
  id,
  title,
  stage,
  ticket,
  open,
  onClose,
  onSave,
}: {
  id: string;
  title: string;
  stage?: PipelineStage;
  /** Tickets: Open or Closed, and no probability. */
  ticket: boolean;
  open: boolean;
  onClose: () => void;
  onSave: (body: {
    name: string;
    stageType: StageType;
    probability: number;
  }) => Promise<string | false>;
}) {
  return (
    <DrawerForm
      id={id}
      title={title}
      open={open}
      onClose={onClose}
      keep={Boolean(stage)}
      submitLabel={stage ? 'Save' : 'Add'}
      onSave={async (data) => {
        const name = String(data.get('name') ?? '').trim();
        if (!name) return false;
        return onSave({
          name,
          stageType: String(data.get('stageType') ?? 'open') as StageType,
          probability: ticket ? (stage?.probability ?? 0) : Number(data.get('probability') ?? 0),
        });
      }}
    >
      <div className="field field--full">
        <label className="field__label" htmlFor={`${id}-name`}>
          Stage name
        </label>
        <input
          className="input"
          id={`${id}-name`}
          name="name"
          required
          maxLength={191}
          defaultValue={stage?.name ?? ''}
        />
      </div>
      <div className="field field--full">
        <label className="field__label" htmlFor={`${id}-type`}>
          {ticket ? 'Stage status' : 'Stage type'}
        </label>
        <select
          className="input"
          id={`${id}-type`}
          name="stageType"
          defaultValue={
            ticket && stage?.stageType === 'lost' ? 'won' : (stage?.stageType ?? 'open')
          }
        >
          {Object.entries(ticket ? { open: 'Open', won: 'Closed' } : STAGE_TYPE_LABELS).map(
            ([value, label]) => (
              <option key={value} value={value}>
                {label}
              </option>
            ),
          )}
        </select>
      </div>
      {ticket ? null : (
        <div className="field field--full">
          <label className="field__label" htmlFor={`${id}-prob`}>
            Probability (%)
          </label>
          <input
            className="input"
            id={`${id}-prob`}
            type="number"
            name="probability"
            min={0}
            max={100}
            step="0.01"
            defaultValue={stage?.probability ?? 10}
            required
          />
        </div>
      )}
    </DrawerForm>
  );
}
