'use client';

// Pipelines > Configure stages (24 Nov design, pipeline-editor.js): each stage's colour (colorPop),
// the Leads / Tickets "Required to enter" fields (reqDialog) and the Deals "Conditional logic
// rules" (logicPop / logicEditor: the properties shown, and required, when a deal enters the
// stage). One rule per stage: its properties are the stage's `properties`.
import { useEffect, useId, useRef, useState, type CSSProperties } from 'react';
import { createPortal } from 'react-dom';
import { DmIcon } from '@/features/data-model/ui/icons';
import type { PipelineStage, StageProperty } from '@/features/pipelines/api.client';
import type { StageFieldSpec } from '@/features/pipelines/stageFields';
import {
  colorName,
  isHexColor,
  STAGE_PALETTE,
  stageColor,
  stageStyle,
} from '@/features/pipelines/stageRules';
import { cn } from '@/lib/utils/cn';
import { OsDropdown } from './primitives';

const labelOf = (specs: readonly StageFieldSpec[], name: string) =>
  specs.find((s) => s.name === name)?.label ?? name.replace(/^custom\./, '');

/* ------------------------------------------------------------------ colour */

/** The Color cell: the stage's swatch and name; the popover picks a preset or custom colour. */
export function StageColorCell({
  stage,
  lead,
  disabled,
  onSave,
}: {
  stage: PipelineStage;
  lead: boolean;
  disabled: boolean;
  onSave: (color: string) => void;
}) {
  const current = stageColor(stage, { lead });
  const [draft, setDraft] = useState(current);
  return (
    <OsDropdown
      className="pe-scolor"
      menuClassName="os-pop"
      width={260}
      disabled={disabled}
      ariaLabel={`Color for ${stage.name}: ${colorName(current)}`}
      label={
        <>
          <span
            className="pe-scolor__sw"
            style={{ '--sw': current } as CSSProperties}
            aria-hidden="true"
          />
          {colorName(current)}
          <DmIcon name="chevron-down" size={14} />
        </>
      }
    >
      {(close) => (
        <div className="pe-cpop" role="dialog" aria-label={`Color for ${stage.name}`}>
          <p className="pe-label">Stage color</p>
          <div className="pe-cpop__grid" role="radiogroup" aria-label="Preset colors">
            {STAGE_PALETTE.map(([c, name]) => (
              <label
                key={c}
                className="pe-cpop__sw"
                style={{ '--sw': c } as CSSProperties}
                title={name}
              >
                <input
                  type="radio"
                  name={`peStageC-${stage.id}`}
                  value={c}
                  aria-label={name}
                  checked={c.toLowerCase() === draft.toLowerCase()}
                  onChange={() => {
                    setDraft(c);
                    onSave(c);
                    close();
                  }}
                />
              </label>
            ))}
          </div>
          <label className="pe-cpop__custom">
            <input
              type="color"
              aria-label="Custom color"
              value={isHexColor(draft) ? draft : '#667085'}
              onChange={(e) => setDraft(e.target.value)}
              onBlur={(e) => {
                if (e.target.value.toLowerCase() !== current) {
                  onSave(e.target.value.toLowerCase());
                  close();
                }
              }}
            />
            Custom color
          </label>
          <div className="pe-cpop__preview">
            <span className="lpl-stage" style={stageStyle(draft) as CSSProperties}>
              {stage.name}
            </span>
            <span className="pe-help">Board column, cards and stepper</span>
          </div>
        </div>
      )}
    </OsDropdown>
  );
}

/* --------------------------------------------------------- shared layer */

function useEscape(onClose: () => void) {
  const ref = useRef(onClose);
  ref.current = onClose;
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      e.preventDefault();
      ref.current();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);
}

/** The design's `layer()` dialog (`.pe-modal`). */
function PeModal({
  title,
  children,
  buttons,
  onClose,
}: {
  title: string;
  children: React.ReactNode;
  buttons: Array<{ label: string; primary?: boolean; disabled?: boolean; run: () => void }>;
  onClose: () => void;
}) {
  const id = useId();
  useEscape(onClose);
  return createPortal(
    <div
      className="pe-modal-ov"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="pe-modal" role="dialog" aria-modal="true" aria-labelledby={id}>
        <header className="pe-layer__head">
          <h2 id={id}>{title}</h2>
          <button type="button" className="pe-x" aria-label="Close" onClick={onClose}>
            <DmIcon name="x" size={16} />
          </button>
        </header>
        <div className="pe-layer__body">{children}</div>
        <footer className="pe-layer__foot">
          {buttons.map((b) => (
            <button
              key={b.label}
              type="button"
              className={cn('pe-btn', b.primary ? 'pe-btn--primary' : 'pe-btn--outline')}
              disabled={b.disabled}
              onClick={b.run}
            >
              {b.label}
            </button>
          ))}
        </footer>
      </div>
    </div>,
    document.body,
  );
}

/* -------------------------------------------------------- required to enter */

/** The "Required to enter" cell (Leads, Tickets and other objects with a pipeline). */
export function StageRequiredCell({
  stage,
  specs,
  singular,
  disabled,
  onSave,
}: {
  stage: PipelineStage;
  specs: readonly StageFieldSpec[];
  /** "lead". */
  singular: string;
  disabled: boolean;
  onSave: (properties: StageProperty[]) => Promise<boolean>;
}) {
  const [open, setOpen] = useState(false);
  const required = (stage.properties ?? []).filter((p) => p.required).map((p) => p.name);
  const text = required.map((n) => labelOf(specs, n)).join(', ');
  return (
    <>
      <button
        type="button"
        className="pe-scolor pe-req-btn"
        aria-haspopup="dialog"
        aria-label={`Required to enter ${stage.name}: ${text || 'None'}. Edit`}
        disabled={disabled}
        onClick={() => setOpen(true)}
      >
        <span>
          {required.length ? (
            `${required.length} field${required.length === 1 ? '' : 's'}: ${text}`
          ) : (
            <span className="pe-muted">None</span>
          )}
        </span>
        <DmIcon name="pencil" size={13} />
      </button>
      {open ? (
        <RequiredDialog
          stage={stage}
          specs={specs}
          singular={singular}
          initial={required}
          onClose={() => setOpen(false)}
          onSave={async (names) => {
            if (await onSave(names.map((name) => ({ name, required: true })))) setOpen(false);
          }}
        />
      ) : null}
    </>
  );
}

function RequiredDialog({
  stage,
  specs,
  singular,
  initial,
  onClose,
  onSave,
}: {
  stage: PipelineStage;
  specs: readonly StageFieldSpec[];
  singular: string;
  initial: string[];
  onClose: () => void;
  onSave: (names: string[]) => void;
}) {
  const [req, setReq] = useState(initial);
  // Fields named by the stage that are no longer live stay listed, so they can be unticked.
  const listed = [
    ...specs,
    ...initial
      .filter((n) => !specs.some((s) => s.name === n))
      .map((n) => ({ name: n, label: labelOf(specs, n), kind: 'text' as const, options: [] })),
  ];
  return (
    <PeModal
      title={`Required to enter ${stage.name}`}
      onClose={onClose}
      buttons={[
        // Kept in the field list's order.
        {
          label: 'Save',
          primary: true,
          run: () => onSave(listed.map((s) => s.name).filter((n) => req.includes(n))),
        },
        { label: 'Cancel', run: onClose },
      ]}
    >
      <p className="pe-p">
        Choose the {singular} fields a rep must fill before a {singular} can move into this stage,
        from the board or the record. {cap(singular)}s that already have these fields move without a
        prompt.
      </p>
      <fieldset className="pe-reqlist">
        <legend className="pe-sr">Required fields</legend>
        {listed.map((s) => (
          <label key={s.name}>
            <input
              type="checkbox"
              value={s.name}
              checked={req.includes(s.name)}
              onChange={(e) =>
                setReq((cur) =>
                  e.target.checked ? [...cur, s.name] : cur.filter((n) => n !== s.name),
                )
              }
            />
            {s.label}
          </label>
        ))}
      </fieldset>
      <p className="pe-reqprev">
        {req.length ? (
          <>
            Moving a {singular} to <strong>{stage.name}</strong> asks for:{' '}
            {req.map((n) => labelOf(listed, n)).join(', ')} when{' '}
            {req.length === 1 ? 'it is' : 'they are'} empty.
          </>
        ) : (
          <>
            {cap(singular)}s can move to <strong>{stage.name}</strong> without filling any fields.
          </>
        )}
      </p>
    </PeModal>
  );
}

const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

/* ------------------------------------------------------- conditional logic */

/** The Deals "Conditional logic rules" cell: the rule count (with its popover) and Add rule. */
export function StageLogicCell({
  stage,
  pipelineName,
  stages,
  specs,
  disabled,
  onSave,
}: {
  stage: PipelineStage;
  pipelineName: string;
  stages: PipelineStage[];
  specs: readonly StageFieldSpec[];
  disabled: boolean;
  onSave: (properties: StageProperty[]) => Promise<boolean>;
}) {
  const [editing, setEditing] = useState<'edit' | 'new' | null>(null);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const props = stage.properties ?? [];
  const shown = props.map((p) => labelOf(specs, p.name)).join(', ');
  const req = props.filter((p) => p.required).map((p) => labelOf(specs, p.name));
  return (
    <span className="pe-cell-logic">
      {props.length ? (
        <OsDropdown
          className="pe-logic-n"
          menuClassName="os-pop pe-logicpop"
          width={320}
          ariaLabel={`1 logic rule for ${stage.name}`}
          label="1 logic rule"
        >
          {(close) => (
            <div className="pe-logicpop">
              <p className="pe-label">Choosing this stage will trigger these rules:</p>
              <ol>
                <li>
                  <div>
                    <span>is equal to: &quot;{stage.name}&quot;</span>
                    <small>
                      Show: {shown}
                      {req.length ? ` . Required: ${req.join(', ')}` : ''}
                    </small>
                  </div>
                  <span className="pe-logicpop__acts">
                    <button
                      type="button"
                      className="pe-iconbtn"
                      aria-label="Edit rule 1"
                      disabled={disabled}
                      onClick={() => {
                        close();
                        setEditing('edit');
                      }}
                    >
                      <DmIcon name="pencil" size={14} />
                    </button>
                    <button
                      type="button"
                      className="pe-iconbtn pe-iconbtn--danger"
                      aria-label="Delete rule 1"
                      disabled={disabled}
                      onClick={() => {
                        close();
                        setConfirmDelete(true);
                      }}
                    >
                      <DmIcon name="trash" size={14} />
                    </button>
                  </span>
                </li>
              </ol>
            </div>
          )}
        </OsDropdown>
      ) : (
        <span className="pe-muted">--</span>
      )}{' '}
      <button
        type="button"
        className="pe-btn pe-btn--pill pe-btn--xs"
        disabled={disabled}
        onClick={() => setEditing('new')}
      >
        Add rule
      </button>
      {editing ? (
        <LogicEditor
          stage={stage}
          pipelineName={pipelineName}
          stages={stages}
          specs={specs}
          start={editing === 'edit' ? props : []}
          exists={editing === 'new' && props.length > 0}
          onOpenExisting={() => setEditing('edit')}
          onClose={() => setEditing(null)}
          onSave={async (next) => {
            if (await onSave(next)) setEditing(null);
          }}
        />
      ) : null}
      {confirmDelete ? (
        <PeModal
          title="Delete this logic rule?"
          onClose={() => setConfirmDelete(false)}
          buttons={[
            {
              label: 'Delete',
              primary: true,
              run: () => {
                void onSave([]).then((ok) => ok && setConfirmDelete(false));
              },
            },
            { label: 'Cancel', run: () => setConfirmDelete(false) },
          ]}
        >
          <p className="pe-p">
            Dependent properties will always show on deals in {stage.name}, and none is required to
            enter it.
          </p>
        </PeModal>
      ) : null}
    </span>
  );
}

/** "Edit property logic" (design `logicEditor`, `.pe-full`): Deal Stage is <stage>. */
function LogicEditor({
  stage,
  pipelineName,
  stages,
  specs,
  start,
  exists,
  onOpenExisting,
  onClose,
  onSave,
}: {
  stage: PipelineStage;
  pipelineName: string;
  stages: PipelineStage[];
  specs: readonly StageFieldSpec[];
  start: StageProperty[];
  exists: boolean;
  onOpenExisting: () => void;
  onClose: () => void;
  onSave: (properties: StageProperty[]) => void;
}) {
  const [rows, setRows] = useState<StageProperty[]>(start);
  const [preview, setPreview] = useState(stage.id);
  const [asking, setAsking] = useState(false);
  const changed = JSON.stringify(rows) !== JSON.stringify(start);
  const valid = rows.length > 0 && changed;
  const cancel = () => (changed ? setAsking(true) : onClose());
  useEscape(() => {
    if (!asking) cancel();
  });
  useEffect(() => {
    document.body.classList.add('pe-noscroll');
    return () => document.body.classList.remove('pe-noscroll');
  }, []);
  const options = [
    ...specs,
    ...rows
      .filter((r) => !specs.some((s) => s.name === r.name))
      .map((r) => ({
        name: r.name,
        label: labelOf(specs, r.name),
        kind: 'text' as const,
        options: [],
      })),
  ];
  const set = (i: number, patch: Partial<StageProperty>) =>
    setRows((cur) => cur.map((r, j) => (j === i ? { ...r, ...patch } : r)));
  const swap = (i: number, j: number) =>
    setRows((cur) => {
      const next = [...cur];
      [next[i], next[j]] = [next[j]!, next[i]!];
      return next;
    });

  return createPortal(
    <div className="pe-full" role="dialog" aria-modal="true" aria-labelledby="peLgT">
      <header className="pe-full__bar">
        <div>
          <h2 id="peLgT">Edit property logic</h2>
          <span>Object: Deal</span>
        </div>
        <div className="pe-full__acts">
          <button type="button" className="pe-btn pe-btn--onDark" onClick={cancel}>
            Cancel
          </button>
          <button
            type="button"
            className="pe-btn pe-btn--light"
            disabled={!valid}
            onClick={() => onSave(rows)}
          >
            Save logic
          </button>
        </div>
      </header>
      <div className="pe-logic">
        <section className="pe-logic__edit" aria-label="Edit logic">
          <h3 className="pe-h3">Edit logic</h3>
          <p className="pe-p pe-muted">
            Property logic allows you to show and require properties based on the value in another
            property.
          </p>
          <p className="pe-label">Controlling property</p>
          <p className="pe-p">When this is true:</p>
          <input
            className="pe-input"
            value="Deal Stage"
            disabled
            aria-label="Controlling property"
          />
          <select className="pe-input" disabled aria-label="Operator">
            <option>is equal to</option>
          </select>
          <select className="pe-input" disabled aria-label="Option">
            <option>
              {stage.name} ({pipelineName})
            </option>
          </select>
          {exists ? (
            <div className="pe-warn">
              Logic already exists for this configuration.
              <br />
              <button type="button" className="pe-textlink" onClick={onOpenExisting}>
                Open existing logic
              </button>
            </div>
          ) : null}
          <hr className="pe-hr" />
          <p className="pe-label">Dependent properties ({rows.length})</p>
          {rows.length ? (
            <p className="pe-p">Show these properties:</p>
          ) : (
            <p className="pe-p pe-muted">No dependent properties</p>
          )}
          {rows.map((r, i) => {
            const label = labelOf(options, r.name);
            return (
              <div key={`${r.name}-${i}`} className="pe-dep">
                <div className="pe-dep__head">
                  <span className="pe-dep__arrows">
                    <button
                      type="button"
                      className="pe-iconbtn"
                      aria-label={`Move ${label} up`}
                      disabled={i === 0}
                      onClick={() => swap(i, i - 1)}
                    >
                      <DmIcon name="arrow-up" size={14} />
                    </button>
                    <button
                      type="button"
                      className="pe-iconbtn"
                      aria-label={`Move ${label} down`}
                      disabled={i === rows.length - 1}
                      onClick={() => swap(i, i + 1)}
                    >
                      <DmIcon name="arrow-down" size={14} />
                    </button>
                  </span>
                  <span className="pe-label">Property</span>
                  <label className="pe-check pe-check--inline">
                    <input
                      type="checkbox"
                      checked={r.required}
                      onChange={(e) => set(i, { required: e.target.checked })}
                    />
                    <span>Required</span>
                  </label>
                  <button
                    type="button"
                    className="pe-textlink pe-textlink--danger"
                    onClick={() => setRows((cur) => cur.filter((_, j) => j !== i))}
                  >
                    <DmIcon name="trash" size={13} />
                    Remove
                  </button>
                </div>
                <select
                  className="pe-input"
                  aria-label={`Dependent property ${i + 1}`}
                  value={r.name}
                  onChange={(e) => set(i, { name: e.target.value })}
                >
                  {options.map((o) => (
                    <option
                      key={o.name}
                      value={o.name}
                      disabled={o.name !== r.name && rows.some((x) => x.name === o.name)}
                    >
                      {o.label}
                    </option>
                  ))}
                </select>
              </div>
            );
          })}
          <button
            type="button"
            className="pe-btn pe-btn--outline pe-btn--sm"
            disabled={
              rows.length >= 30 || !options.some((o) => !rows.some((r) => r.name === o.name))
            }
            onClick={() => {
              const next = options.find((o) => !rows.some((r) => r.name === o.name));
              if (next) setRows((cur) => [...cur, { name: next.name, required: false }]);
            }}
          >
            <DmIcon name="plus" size={14} />
            Add property
          </button>
        </section>
        <section className="pe-logic__preview" aria-label="Preview logic">
          <h3 className="pe-h3">Preview logic</h3>
          <div className="pe-logic__card">
            <label className="pe-label" htmlFor="peLgPv">
              Deal Stage
            </label>
            <select
              className="pe-input"
              id="peLgPv"
              value={preview}
              onChange={(e) => setPreview(e.target.value)}
            >
              {stages.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name} ({pipelineName})
                </option>
              ))}
            </select>
            <div className="pe-logic__deps">
              {preview === stage.id && rows.length ? (
                rows.map((r) => (
                  <label key={r.name} className="pe-field">
                    <span className="pe-label">
                      {labelOf(options, r.name)}
                      {r.required ? ' *' : ''}
                    </span>
                    <input className="pe-input" disabled />
                  </label>
                ))
              ) : (
                <p>No dependent properties exist for this choice</p>
              )}
            </div>
          </div>
        </section>
      </div>
      {asking ? (
        <PeModal
          title="Are you sure you want to cancel?"
          onClose={() => setAsking(false)}
          buttons={[
            { label: 'Close without saving', primary: true, run: onClose },
            { label: 'Back to editing', run: () => setAsking(false) },
          ]}
        >
          <p className="pe-p">Any changes made to this form will not be saved.</p>
        </PeModal>
      ) : null}
    </div>,
    document.body,
  );
}
