'use client';

/**
 * Create a goal (QA #345, 13 Nov design create-goal.php / goals.js "C) create a goal"): the
 * four-step wizard Define > Setup > Performance > Notifications, started blank, from a built-in
 * template, a saved template or a gallery card. With `mode="template"` it is the Create template
 * page (create-goals-template.php): the Define step with a template name and description.
 */
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { errorText, isApiError } from '@/lib/api/errors';
import { createGoal, createGoalTemplate, getGoalOptions, previewGoal } from '../api.client';
import {
  AGGS,
  EMPTY_OPTIONS,
  TRACK_LABEL,
  countOnly,
  flash,
  fmtD,
  importTargets,
  initials,
  isCurrencyDef,
  money,
  nf,
  objectOf,
  periodCount,
  periods,
  toMonths,
} from '../model';
import type {
  GoalAggregation,
  GoalCadence,
  GoalContributorMode,
  GoalDefinition,
  GoalObject,
  GoalOptions,
  GoalTemplateKey,
  GoalTracking,
} from '../types';
import {
  CopyIcon,
  Dd,
  EmptyArt,
  Fld,
  IBulb,
  ICheck,
  IExt,
  IFile,
  ITarg,
  IWarn,
  NotesList,
  SearchIcon,
  TemplateArt,
  useGlToast,
  useOutside,
  type DdOption,
  type Notes,
} from './parts';

/** Gallery cards that are not one of the built-in template keys (goals-create-template.php). */
export const GALLERY_PRESETS: Record<string, { label: string; definition: GoalDefinition }> = {
  quota: {
    label: 'Quota',
    definition: {
      objectType: 'deal',
      property: 'amount',
      aggregation: 'SUM',
      dateProperty: 'close_date',
      tracking: 'higher',
    },
  },
  tasks_completed: {
    label: 'Tasks completed',
    definition: {
      objectType: 'task',
      property: 'record_id',
      aggregation: 'COUNT',
      dateProperty: 'completed_date',
      tracking: 'higher',
    },
  },
  notes_created: {
    label: 'Notes created',
    definition: {
      objectType: 'note',
      property: 'record_id',
      aggregation: 'COUNT',
      dateProperty: 'create_date',
      tracking: 'higher',
    },
  },
};

const STEPS = ['Define', 'Setup', 'Performance', 'Notifications'];
const CADS: Array<[GoalCadence, string]> = [
  ['monthly', 'Monthly'],
  ['quarterly', 'Quarterly'],
  ['yearly', 'Yearly'],
];

interface WRow {
  k: string;
  id: string;
  n: string;
  team?: boolean;
}

type Sub =
  | { t: 'apply'; val: string; err: string }
  | { t: 'add'; err: string }
  | { t: 'import'; file: { name: string; size: number } | null; text: string | null; err: string }
  | { t: 'template' }
  | { t: 'discard' };

function Av({ n }: { n: string }) {
  return (
    <span className="gl-av gl-av--s" aria-hidden="true">
      {initials(n)}
    </span>
  );
}

export function CreateGoalWizard({ mode = 'goal' }: { mode?: 'goal' | 'template' }) {
  const router = useRouter();
  const params = useSearchParams();
  const { toast, node: toastNode } = useGlToast();
  const tplPage = mode === 'template';
  const [options, setOptions] = useState<GoalOptions | null>(null);
  const [step, setStep] = useState(1);
  const [obj, setObj] = useState<GoalObject | ''>('');
  const [prop, setProp] = useState('');
  const [agg, setAgg] = useState<GoalAggregation | ''>('');
  const [date, setDate] = useState('');
  const [track, setTrack] = useState<GoalTracking | ''>('');
  const [templateKey, setTemplateKey] = useState<GoalTemplateKey>('custom');
  const [goalTemplateId, setGoalTemplateId] = useState<string | null>(null);
  const [name, setName] = useState('');
  const [nameErr, setNameErr] = useState('');
  const [who, setWho] = useState<GoalContributorMode>('users');
  const [users, setUsers] = useState<string[]>([]);
  const [teams, setTeams] = useState<string[]>([]);
  const [cad, setCad] = useState<GoalCadence>('monthly');
  const [fiscal, setFiscal] = useState(true);
  const [year, setYear] = useState(0);
  const [rows, setRows] = useState<WRow[]>([]);
  const [vals, setVals] = useState<Record<string, string[]>>({});
  const [sel, setSel] = useState<Record<string, boolean>>({});
  const [extra, setExtra] = useState<string[]>([]);
  const [notes, setNotes] = useState<Notes>({
    kick: false,
    exceeded: false,
    achieved: false,
    missed: false,
  });
  const [dirty, setDirty] = useState(false);
  const [dd, setDd] = useState<string | null>(null);
  const [ddq, setDdq] = useState('');
  const [ms, setMs] = useState<string | null>(null);
  const [msq, setMsq] = useState('');
  const [sub, setSub] = useState<Sub | null>(null);
  const [addSel, setAddSel] = useState<string[]>([]);
  const [tplName, setTplName] = useState('');
  const [tplDesc, setTplDesc] = useState('');
  const [tplErr, setTplErr] = useState('');
  const [preview, setPreview] = useState<{
    value: number;
    unit: string;
    currency: string | null;
  } | null>(null);
  const [busy, setBusy] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  useOutside(dd !== null || ms !== null, '.gx-dd', () => {
    setDd(null);
    setMs(null);
  });

  const applyDef = (d: GoalDefinition) => {
    setObj(d.objectType);
    setProp(d.property);
    setAgg(d.aggregation);
    setDate(d.dateProperty);
    setTrack(d.tracking);
  };

  useEffect(() => {
    const ac = new AbortController();
    getGoalOptions({ signal: ac.signal })
      .then((o) => {
        setOptions(o);
        setYear(o.year);
        const key = params.get('template');
        const tid = params.get('templateId') ?? params.get('copy');
        const preset = params.get('preset');
        const builtIn = o.templates.find((t) => t.key === key);
        const saved = o.savedTemplates.find((t) => t.id === tid);
        if (builtIn) {
          setTemplateKey(builtIn.key);
          if (builtIn.definition) applyDef(builtIn.definition);
          if (builtIn.key !== 'custom') setName(builtIn.label);
        } else if (saved) {
          applyDef(saved.definition);
          if (tplPage) {
            setTplName(saved.name + ' (Copy)');
            setTplDesc(saved.description ?? '');
          } else {
            setGoalTemplateId(saved.id);
            setName(saved.name);
          }
        } else if (preset && GALLERY_PRESETS[preset]) {
          applyDef(GALLERY_PRESETS[preset].definition);
          setName(GALLERY_PRESETS[preset].label);
        }
      })
      .catch((e: unknown) => {
        if (!ac.signal.aborted) toast(errorText(e));
      });
    return () => ac.abort();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const opts = options ?? EMPTY_OPTIONS;
  const cat = opts.catalogue;
  const ready = Boolean(obj && prop && agg);

  useEffect(() => {
    if (!obj || !prop || !agg) {
      setPreview(null);
      return;
    }
    const o = objectOf(cat, obj);
    const d = date || o?.dates.find((x) => x.supported)?.key;
    if (!d) return;
    const ac = new AbortController();
    previewGoal(
      { objectType: obj, property: prop, aggregation: agg, dateProperty: d },
      // DL12 (QA #477): the users or teams picked so far, as the goal will count.
      who === 'users'
        ? { signal: ac.signal, userIds: users }
        : { signal: ac.signal, teamIds: teams },
    )
      .then((p) => setPreview({ value: p.value, unit: p.unit, currency: p.currency }))
      .catch(() => {
        if (!ac.signal.aborted) setPreview(null);
      });
    return () => ac.abort();
  }, [obj, prop, agg, date, cat, who, users, teams]);

  const P = periodCount(cad);
  const ok1 = Boolean(obj && prop && agg && date && track);
  const ok2 = Boolean(name.trim() && (who === 'users' ? users.length : teams.length) && cad);
  const sums = () => {
    const out = Array.from({ length: P }, () => 0);
    let all = 0;
    for (const r of rows) {
      (vals[r.k] ?? []).forEach((v, k) => {
        const n = parseFloat(v) || 0;
        out[k]! += n;
        all += n;
      });
    }
    return { ms: out, all };
  };
  const ok3 = rows.length > 0 && sums().all > 0;
  const tplOk = Boolean(tplName.trim() && ok1);
  const userName = (id: string) => opts.users.find((u) => u.id === id)?.name ?? '';
  const teamName = (id: string) => opts.teams.find((t) => t.id === id)?.name ?? '';

  const buildRows = (nextExtra = extra) => {
    const keys: WRow[] = [];
    if (who !== 'users')
      for (const t of teams) keys.push({ k: 't:' + t, id: t, n: teamName(t), team: true });
    if (who === 'users') for (const u of users) keys.push({ k: 'u:' + u, id: u, n: userName(u) });
    if (who === 'both') {
      for (const u of opts.users) {
        if (teams.some((t) => opts.teams.find((x) => x.id === t)?.memberIds.includes(u.id)))
          keys.push({ k: 'u:' + u.id, id: u.id, n: u.name });
      }
    }
    for (const u of nextExtra)
      if (!keys.some((x) => x.k === 'u:' + u)) keys.push({ k: 'u:' + u, id: u, n: userName(u) });
    setVals((v) => {
      const next = { ...v };
      for (const r of keys)
        if (!next[r.k] || next[r.k]!.length !== P) next[r.k] = Array.from({ length: P }, () => '0');
      return next;
    });
    setRows(keys);
    setSel({});
  };

  const close = () => router.push(tplPage ? '/goals/templates' : '/goals');
  const ask = () => {
    if (!dirty) {
      close();
      return;
    }
    setSub({ t: 'discard' });
    setDd(null);
    setMs(null);
  };

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape') return;
      if (dd || ms) {
        setDd(null);
        setMs(null);
      } else if (sub) setSub(null);
      else ask();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  });

  const pick = (key: string, v: string) => {
    if (key === 'obj') {
      if (v !== obj) {
        setProp('');
        setAgg('');
        setDate('');
      }
      setObj(v as GoalObject);
    } else if (key === 'prop') {
      setProp(v);
      if (agg && agg !== 'COUNT' && countOnly(cat, obj, v)) setAgg('COUNT');
    } else if (key === 'agg') setAgg(v as GoalAggregation);
    else if (key === 'date') setDate(v);
    else if (key === 'track') setTrack(v as GoalTracking);
    else if (key === 'cad') setCad(v as GoalCadence);
    setDd(null);
    setDdq('');
    setDirty(true);
  };
  const toggleDd = (k: string) => {
    setDd(dd === k ? null : k);
    setDdq('');
    setMs(null);
  };

  const o = obj ? objectOf(cat, obj) : undefined;
  const isCur =
    Boolean(obj && prop && agg) &&
    isCurrencyDef(cat, { objectType: obj, property: prop, aggregation: agg });
  const objOpts: DdOption[] = cat.map((x) => [x.key, x.label, '', !x.supported]);
  const propOpts: DdOption[] = (o?.properties ?? []).map((p) => [
    p.key,
    p.label,
    undefined,
    !p.supported,
  ]);
  const aggOpts: DdOption[] = AGGS.map((a) => [
    a[0],
    a[0],
    a[1],
    a[0] !== 'COUNT' && Boolean(prop) && countOnly(cat, obj, prop),
  ]);
  const dateOpts: DdOption[] = (o?.dates ?? []).map((d) => [
    d.key,
    d.label,
    undefined,
    !d.supported,
  ]);
  const trackOpts: DdOption[] = (['higher', 'lower'] as const).map((t) => [t, TRACK_LABEL[t]]);

  const previewBox = (
    <div className="cw-prev">
      {ready ? (
        <>
          <span className="gv-chip">
            From {fmtD(new Date(opts.year - 1, 11, 31))} to {fmtD(new Date(opts.year, 11, 31))}
          </span>
          <span className="ge-prev__l">SAMPLE PROGRESS</span>
          <span className="ge-prev__v">
            {preview
              ? preview.unit === 'currency'
                ? money(preview.value, preview.currency)
                : nf(preview.value) + ' units'
              : '…'}
          </span>
        </>
      ) : (
        <>
          <EmptyArt />
          <p>Enter aggregation type and property on the left to generate a preview</p>
        </>
      )}
    </div>
  );

  const defineFields = (
    <>
      <Fld label="Object" req>
        <Dd
          id="obj"
          value={obj}
          placeholder="Select object type"
          options={objOpts}
          open={dd === 'obj'}
          onToggle={toggleDd}
          onPick={pick}
          search
          query={ddq}
          onQuery={setDdq}
        />
      </Fld>
      <Fld label="Property" req>
        <Dd
          id="prop"
          value={prop}
          placeholder="Select property"
          options={propOpts}
          open={dd === 'prop'}
          onToggle={toggleDd}
          onPick={pick}
          search
          query={ddq}
          onQuery={setDdq}
          dis={!obj}
        />
      </Fld>
      <Fld label="Aggregation" req>
        <Dd
          id="agg"
          value={agg}
          placeholder="Select aggregation type"
          options={aggOpts}
          open={dd === 'agg'}
          onToggle={toggleDd}
          onPick={pick}
          desc
          dis={!prop}
        />
      </Fld>
      <Fld label="Unit of measurement" info>
        <Dd
          id="unit"
          value={agg ? 'u' : ''}
          placeholder="Unit of measurement"
          options={agg ? [['u', isCur ? 'Currency' : 'Number of units']] : []}
          open={false}
          onToggle={() => {}}
          onPick={() => {}}
          dis
        />
      </Fld>
      <Fld label="Preferred goal currency" info>
        <Dd
          id="cur"
          value={isCur ? 'c' : ''}
          placeholder="Select goal currency"
          options={isCur ? [['c', opts.currency]] : []}
          open={false}
          onToggle={() => {}}
          onPick={() => {}}
          dis
        />
      </Fld>
      <Fld label="Date property" req>
        <Dd
          id="date"
          value={date}
          placeholder="Select date property"
          options={dateOpts}
          open={dd === 'date'}
          onToggle={toggleDd}
          onPick={pick}
          dis={!obj}
        />
      </Fld>
      <Fld label="Tracking method" req info>
        <Dd
          id="track"
          value={track}
          placeholder="Select tracking method"
          options={trackOpts}
          open={dd === 'track'}
          onToggle={toggleDd}
          onPick={pick}
          up
        />
      </Fld>
    </>
  );

  const hintLinks = (
    <>
      <p className="ge-hint">
        Try the different options from property and aggregation type to compare data in this
        preview. Use this info to see which option best fits your goal.
      </p>
      {tplPage ? null : (
        <p>
          <button
            type="button"
            className="link"
            onClick={() => toast('Custom goals guide is coming soon')}
          >
            Learn more about custom goals <IExt />
          </button>
        </p>
      )}
      <p>
        <button
          type="button"
          className="link"
          onClick={() => toast('Goal objectives guide is coming soon')}
        >
          Learn how to write great goal objectives <IExt />
        </button>
      </p>
    </>
  );

  /** Multi-select with chips and search (`cwMs()`). */
  /** A picker option matches the search by name or email. */
  const matches = (x: [string, string, string?], ql: string) =>
    !ql || x[1].toLowerCase().includes(ql) || Boolean(x[2]?.toLowerCase().includes(ql));
  const multi = (
    key: 'users' | 'teams' | 'add',
    ph: string,
    /** [id, name, secondary text: a user's email (QA #584)] */
    list: Array<[string, string, string?]>,
    selected: string[],
    onChange: (next: string[]) => void,
  ) => {
    const open = ms === key;
    const ql = msq.toLowerCase();
    const label = (v: string) =>
      list.find((x) => x[0] === v)?.[1] ?? (key === 'teams' ? teamName(v) : userName(v));
    return (
      <div className="gx-dd">
        <div
          role="button"
          className="gx-ddb cw-msb"
          aria-haspopup="listbox"
          aria-expanded={open}
          tabIndex={0}
          onClick={(e) => {
            if ((e.target as Element).closest('[data-cw-rm]')) return;
            setMs(open ? null : key);
            setMsq('');
            setDd(null);
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              setMs(open ? null : key);
              setMsq('');
            }
          }}
        >
          <span className="cw-msv">
            {selected.length ? (
              selected.map((v) => (
                <span className="cw-chip" key={v}>
                  {key !== 'teams' ? <Av n={label(v)} /> : null}
                  <span>{label(v)}</span>
                  <button
                    type="button"
                    data-cw-rm
                    aria-label={'Remove ' + label(v)}
                    onClick={() => {
                      onChange(selected.filter((x) => x !== v));
                      setDirty(true);
                    }}
                  >
                    {'×'}
                  </button>
                </span>
              ))
            ) : (
              <span className="gx-ph">{ph}</span>
            )}
          </span>
          <span className="gl-caret" />
        </div>
        {open ? (
          <div className="gx-ddp">
            <label className="gx-ddq">
              <input
                type="search"
                placeholder="Search"
                value={msq}
                autoComplete="off"
                aria-label="Search"
                autoFocus
                onChange={(e) => setMsq(e.target.value)}
              />
              <SearchIcon />
            </label>
            <div className="gx-ddl" role="listbox" aria-multiselectable="true">
              {list.filter((x) => matches(x, ql)).length ? (
                list
                  .filter((x) => matches(x, ql))
                  .map((x) => (
                    <label className="check gx-opt" key={x[0]}>
                      <input
                        type="checkbox"
                        checked={selected.includes(x[0])}
                        onChange={(e) => {
                          onChange(
                            e.target.checked
                              ? [...selected, x[0]]
                              : selected.filter((y) => y !== x[0]),
                          );
                          setDirty(true);
                        }}
                      />
                      <span className="check__box" />
                      {key === 'teams' ? null : <Av n={x[1]} />}
                      <span className="gl-ot">
                        {x[1]}
                        {x[2] ? <small>{x[2]}</small> : null}
                      </span>
                    </label>
                  ))
              ) : (
                <p className="gx-none">No results</p>
              )}
            </div>
          </div>
        ) : null}
      </div>
    );
  };

  const radio = (v: GoalContributorMode, label: string, inner: React.ReactNode) => (
    <div className="cw-rd" key={v}>
      <label className="check cw-radio">
        <input
          type="radio"
          name="cwWho"
          value={v}
          checked={who === v}
          onChange={() => {
            setWho(v);
            setMs(null);
            setDirty(true);
          }}
        />
        <span className="check__box cw-rb" />
        <span>{label}</span>
      </label>
      {who === v && inner ? <div className="cw-ind">{inner}</div> : null}
    </div>
  );

  const uOpts: Array<[string, string, string?]> = opts.users.map((u) => [u.id, u.name, u.email]);
  const tOpts: Array<[string, string]> = opts.teams.map((t) => [t.id, t.name]);

  const step1 = (
    <div className="cw-c cw-c--w">
      <h2 className="cw-h2">How do you want to define this goal?</h2>
      <div className="cw-two">
        <div className="cw-form">
          <div className="ge-defh">
            <h2 className="ge-h2">Define goal</h2>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              disabled={!obj}
              onClick={() => toast('Goal filters is coming soon')}
            >
              Add filters (0)
            </button>
          </div>
          {defineFields}
        </div>
        <div className="cw-side">
          <h2 className="ge-h2">Data preview</h2>
          {previewBox}
          {hintLinks}
        </div>
      </div>
    </div>
  );

  const step2 = (
    <div className="cw-c">
      <h2 className="cw-h2">How do you want to set up this goal?</h2>
      <Fld label="Goal name" req id="cwN">
        <input
          className="input"
          id="cwN"
          type="text"
          maxLength={120}
          placeholder="Enter goal name"
          value={name}
          autoComplete="off"
          autoFocus
          onChange={(e) => {
            setName(e.target.value);
            setNameErr('');
            setDirty(true);
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && ok2) {
              e.preventDefault();
              buildRows();
              setStep(3);
            }
          }}
        />
        {nameErr ? (
          <p className="gx-err" role="alert">
            {nameErr}
          </p>
        ) : null}
      </Fld>
      <div className="gx-f" role="radiogroup" aria-labelledby="cwCo">
        <div className="gx-lbl" id="cwCo">
          Contributors <span className="gx-req">*</span>
        </div>
        {radio(
          'users',
          'Individual users',
          <>
            {multi('users', 'Select users within selected teams', uOpts, users, setUsers)}
            <p className="cw-hint">
              Users need a paid seat. You can update user settings{' '}
              <a className="link" href="/settings/users" target="_blank" rel="noreferrer">
                here <IExt />
              </a>
              .
            </p>
          </>,
        )}
        {radio('teams', 'Team goals only', multi('teams', 'Select teams', tOpts, teams, setTeams))}
        {radio(
          'both',
          'Team goal with individual user targets',
          multi('teams', 'Select teams', tOpts, teams, setTeams),
        )}
      </div>
      <Fld label="Cadence" req info>
        <Dd
          id="cad"
          value={cad}
          placeholder="Select cadence"
          options={CADS}
          open={dd === 'cad'}
          onToggle={toggleDd}
          onPick={pick}
        />
      </Fld>
      <label className="check cw-fy">
        <input
          type="checkbox"
          checked={fiscal}
          onChange={(e) => {
            setFiscal(e.target.checked);
            setDirty(true);
          }}
        />
        <span className="check__box" />
        <span>
          Align with your fiscal year settings?{' '}
          <a className="link" href="/settings/account-defaults" target="_blank" rel="noreferrer">
            View Settings <IExt />
          </a>
        </span>
      </label>
    </div>
  );

  const s = sums();
  const ns = rows.filter((r) => sel[r.k]).length;
  const allOn = rows.length > 0 && ns === rows.length;
  const word = who === 'users' ? 'reps' : who === 'teams' ? 'teams' : 'teams and reps';
  const hd = who === 'users' ? 'Rep' : who === 'teams' ? 'Team' : 'Team / Rep';
  const unitText = isCur ? 'Amount in ' + opts.currency : 'Number of units';
  const fmtUnit = (v: number) => (isCur ? money(v, opts.currency) : nf(v) + ' units');
  const step3 = (
    <div className="cw-c cw-c--t">
      <h2 className="cw-h2">What are your FY {year} targets?</h2>
      <div className="ge-tools">
        <p className="gx-tip">
          <IBulb />
          To bulk apply targets or pipelines, select the checkboxes for the rows you want to bulk
          apply values for.
        </p>
        <div className="ge-tools__r">
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => {
              setAddSel([]);
              setSub({ t: 'add', err: '' });
              setMs(null);
            }}
          >
            Add {who === 'teams' ? 'team' : 'user'}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setSub({ t: 'import', file: null, text: null, err: '' })}
          >
            Import {who === 'teams' ? 'team' : 'user'} targets
          </button>
          <span className="gl-range gl-range--q">
            <button
              type="button"
              aria-label="Previous year"
              disabled={year <= opts.year - 1}
              onClick={() => setYear(year - 1)}
            >
              {'‹'}
            </button>
            <span aria-live="polite">FY {year}</span>
            <button
              type="button"
              aria-label="Next year"
              disabled={year >= opts.year + 1}
              onClick={() => setYear(year + 1)}
            >
              {'›'}
            </button>
          </span>
        </div>
      </div>
      {ns ? (
        <div className="gl-sel gx-sel">
          <b>{ns} selected</b>
          <button
            type="button"
            className="link gl-sel__a"
            onClick={() => setSub({ t: 'apply', val: '0', err: '' })}
          >
            <ITarg />
            Apply targets
          </button>
          <button
            type="button"
            className="gl-sel__x"
            aria-label="Clear selection"
            onClick={() => setSel({})}
          >
            {'×'}
          </button>
        </div>
      ) : null}
      <div className="gl-tw gx-tw" tabIndex={0} aria-label="Targets table">
        <table className="gl-t gx-t">
          <caption className="gl-sr">Targets by {word}</caption>
          <thead>
            <tr>
              <th scope="col" className="gl-c1">
                <label className="check">
                  <input
                    type="checkbox"
                    checked={allOn}
                    ref={(el) => {
                      if (el) el.indeterminate = ns > 0 && !allOn;
                    }}
                    onChange={(e) =>
                      setSel(Object.fromEntries(rows.map((r) => [r.k, e.target.checked])))
                    }
                  />
                  <span className="check__box" />
                  <span className="gl-sr">Select all</span>
                </label>
              </th>
              <th scope="col" className="gx-c2">
                {hd}
              </th>
              <th scope="col">Unit of measurem{'…'}</th>
              {periods(cad, year).map((p) => (
                <th scope="col" className="gx-per" key={p[0]}>
                  <span>{p[0]}</span>
                  {p[1] ? <span>{p[1]}</span> : null}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.k}>
                <td className="gl-c1">
                  <label className="check">
                    <input
                      type="checkbox"
                      checked={Boolean(sel[r.k])}
                      onChange={(e) => setSel({ ...sel, [r.k]: e.target.checked })}
                    />
                    <span className="check__box" />
                    <span className="gl-sr">Select {r.n}</span>
                  </label>
                </td>
                <th scope="row" className="gx-c2">
                  <span className="cw-rn">
                    {r.team ? (
                      <span className="gl-av gl-av--s">
                        <CopyIcon />
                      </span>
                    ) : (
                      <Av n={r.n} />
                    )}
                    <span className="gx-ell" title={r.n}>
                      {r.n}
                    </span>
                  </span>
                </th>
                <td className="gx-u">{unitText}</td>
                {(vals[r.k] ?? []).map((v, i) => (
                  <td key={i}>
                    <input
                      className="input gx-n"
                      type="number"
                      min="0"
                      step="any"
                      value={v}
                      aria-label={r.n + ' target ' + (i + 1)}
                      onChange={(e) => {
                        const arr = (vals[r.k] ?? []).slice();
                        arr[i] = e.target.value;
                        setVals({ ...vals, [r.k]: arr });
                        setDirty(true);
                      }}
                    />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr>
              <td className="gl-c1" />
              <th scope="row" className="gx-c2">
                All {word}
              </th>
              <td />
              {s.ms.map((v, i) => (
                <td key={i}>{fmtUnit(v)}</td>
              ))}
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );

  const n = rows.length;
  const step4 = (
    <div className="cw-c cw-c--n">
      <h2 className="cw-h2">What notifications would you like to add?</h2>
      <div className="cw-tpl">
        <TemplateArt />
        <div>
          <h3>Create a goal template</h3>
          <p>
            Turning this goal into a template allows you to reuse it. Give it a name and a
            description and it will live in My templates. Templates save the goal definition, not
            the contributors, duration, targets, or settings.
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => {
              setTplName('');
              setTplDesc('');
              setTplErr('');
              setSub({ t: 'template' });
            }}
          >
            Create template
          </button>
        </div>
      </div>
      <h3 className="gx-h3 cw-sn">Set notifications</h3>
      <p className="cw-nt">
        Select the notifications to send to the goal contributors (
        <b>
          {n} contributor{n === 1 ? '' : 's'}
        </b>
        )
      </p>
      <hr className="cw-hr" />
      <NotesList
        notes={notes}
        onChange={(k, on) => {
          setNotes({ ...notes, [k]: on });
          setDirty(true);
        }}
      />
    </div>
  );

  const definition = (): GoalDefinition => ({
    objectType: obj as GoalObject,
    property: prop,
    aggregation: agg as GoalAggregation,
    dateProperty: date,
    tracking: track as GoalTracking,
  });

  /** QA #572: the first negative target, as the goal editor words it (null when all are 0+). */
  const negativeTarget = (): string | null => {
    const labels = periods(cad, year);
    for (const r of rows) {
      const vs = vals[r.k] ?? [];
      for (let i = 0; i < vs.length; i++) {
        if (parseFloat(vs[i]!) < 0)
          return 'Enter a target of 0 or more for ' + r.n + ' ' + (labels[i]?.[0] ?? '');
      }
    }
    return null;
  };

  const save = async () => {
    const negative = negativeTarget();
    if (negative) {
      setStep(3);
      toast(negative);
      return;
    }
    setBusy(true);
    try {
      await createGoal({
        name: name.trim(),
        templateKey,
        goalTemplateId,
        definition: definition(),
        cadence: cad,
        contributorMode: who,
        userIds: who === 'users' ? users : extra,
        teamIds: who === 'users' ? [] : teams,
        alignFiscalYear: fiscal,
        year,
        targets: rows.map((r) => ({
          type: r.team ? ('team' as const) : ('user' as const),
          id: r.id,
          months: toMonths(
            (vals[r.k] ?? []).map((v) => parseFloat(v) || 0),
            cad,
          ),
        })),
        notifications: {
          kickoff: notes.kick,
          exceeded: notes.exceeded,
          achieved: notes.achieved,
          missed: notes.missed,
        },
      });
      flash('Goal created');
      router.push('/goals');
    } catch (e) {
      setBusy(false);
      if (isApiError(e) && e.status === 409) {
        setStep(2);
        setNameErr(e.message);
      } else toast(errorText(e));
    }
  };

  const saveTemplate = async (then: 'exit' | 'goal' | 'stay') => {
    const nm = tplName.trim();
    if (!nm || !ok1) return;
    setBusy(true);
    try {
      const t = await createGoalTemplate({
        name: nm,
        description: tplDesc.trim() || null,
        definition: definition(),
      });
      setBusy(false);
      if (then === 'goal') router.push('/goals/new?templateId=' + encodeURIComponent(t.id));
      else if (then === 'exit') {
        flash('Template saved to My templates');
        router.push('/goals');
      } else {
        setSub(null);
        toast('Template saved to My templates');
      }
    } catch (e) {
      setBusy(false);
      const msg =
        isApiError(e) && e.status === 409
          ? 'A template with this name already exists. Enter a different name.'
          : errorText(e);
      if (then === 'stay') toast(msg);
      else setTplErr(msg);
    }
  };

  const importNow = () => {
    if (sub?.t !== 'import' || sub.text == null) return;
    const res = importTargets(
      sub.text,
      rows.map((r) => r.n),
      P,
    );
    if ('error' in res) {
      setSub({ ...sub, err: res.error });
      return;
    }
    const next = { ...vals };
    for (const r of rows) {
      const v = res.values.get(r.n);
      if (v) next[r.k] = v.map(String);
    }
    setVals(next);
    setDirty(true);
    setSub(null);
    toast(
      'Imported targets for ' +
        res.done +
        (res.done === 1 ? ' row' : ' rows') +
        (res.skip ? ' (' + res.skip + ' skipped)' : ''),
    );
  };
  const readFile = (f: File | undefined) => {
    if (!f) return;
    if (!/\.csv$/i.test(f.name)) {
      setSub({ t: 'import', file: null, text: null, err: 'Only .csv files are supported.' });
      return;
    }
    if (f.size > 2 * 1024 * 1024) {
      setSub({ t: 'import', file: null, text: null, err: 'The file is larger than 2 MB.' });
      return;
    }
    const meta = { name: f.name, size: f.size };
    setSub({ t: 'import', file: meta, text: null, err: '' });
    const rd = new FileReader();
    rd.onload = () => setSub({ t: 'import', file: meta, text: String(rd.result), err: '' });
    rd.onerror = () =>
      setSub({ t: 'import', file: null, text: null, err: 'The file could not be read.' });
    rd.readAsText(f);
  };

  const subHead = (t: string, big?: boolean) => (
    <div className={'gl-mh' + (big ? ' gx-mh--big' : '')}>
      <span>{t}</span>
      <button type="button" className="gl-x" aria-label="Close" onClick={() => setSub(null)}>
        {'×'}
      </button>
    </div>
  );
  const whoWord = who === 'teams' ? 'team' : 'user';
  let subNode: React.ReactNode = null;
  if (sub) {
    let cls = 'gl-dlg gx-dlg gx-dlg--s';
    let body: React.ReactNode;
    if (sub.t === 'apply') {
      body = (
        <>
          {subHead('Apply targets', true)}
          <div className="gl-mb gx-mb">
            <label className="gx-lbl" htmlFor="cwAp">
              Amount
            </label>
            <div className="gx-amt">
              <span>{unitText}</span>
              <input
                className="input"
                id="cwAp"
                type="number"
                min="0"
                step="any"
                value={sub.val}
                autoFocus
                onChange={(e) => setSub({ ...sub, val: e.target.value, err: '' })}
              />
            </div>
            {sub.err ? (
              <p className="gx-err" role="alert">
                {sub.err}
              </p>
            ) : null}
          </div>
          <div className="gl-mf">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => {
                const av = parseFloat(sub.val);
                if (!isFinite(av) || av < 0) {
                  setSub({ ...sub, err: 'Enter an amount of 0 or more.' });
                  return;
                }
                const next = { ...vals };
                for (const r of rows)
                  if (sel[r.k]) next[r.k] = (next[r.k] ?? []).map(() => String(av));
                setVals(next);
                setSub(null);
                setDirty(true);
                toast('Targets applied');
              }}
            >
              Apply
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={() => setSub(null)}>
              Cancel
            </button>
          </div>
        </>
      );
    } else if (sub.t === 'add') {
      const have = rows.map((r) => r.id);
      const addOpts: Array<[string, string, string?]> = opts.users
        .filter((u) => !have.includes(u.id))
        .map((u) => [u.id, u.name, u.email]);
      body = (
        <>
          {subHead('Add ' + whoWord)}
          <div className="gl-mb gx-mb">
            <div className="gx-lbl">{whoWord === 'team' ? 'Team' : 'User'}</div>
            {multi('add', 'Select users to add', addOpts, addSel, setAddSel)}
            {sub.err ? (
              <p className="gx-err" role="alert">
                {sub.err}
              </p>
            ) : null}
          </div>
          <div className="gl-mf">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => {
                if (!addSel.length) {
                  setSub({ ...sub, err: 'Select at least one user.' });
                  return;
                }
                const nextExtra = [...extra, ...addSel.filter((u) => !extra.includes(u))];
                setExtra(nextExtra);
                setAddSel([]);
                setSub(null);
                setMs(null);
                setDirty(true);
                buildRows(nextExtra);
              }}
            >
              Confirm
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={() => setSub(null)}>
              Cancel
            </button>
          </div>
        </>
      );
    } else if (sub.t === 'import') {
      cls = 'gl-dlg gx-dlg gx-dlg--l';
      body = (
        <>
          {subHead('Import ' + whoWord + ' targets')}
          <div className="gl-mb gx-mb">
            <h3 className="gx-h3 crm-mt-0">What to know before importing your goal targets</h3>
            <p className="gx-warn">
              <IWarn />
              This is a bulk action. If you{'’'}re editing a goal for an existing team or rep, you
              must include all new and existing targets for that team or rep.
            </p>
            <h3 className="gx-h3">Setting up the csv</h3>
            <p>The .csv must have columns for:</p>
            <ul className="gx-ul">
              <li>primary team or user, and</li>
              <li>
                each goal target start date; for example, a monthly goal needs 12 columns, one for
                each month.
              </li>
            </ul>
            <h3 className="gx-h3">Goal target file</h3>
            <div
              className={'gx-dz' + (sub.file ? ' has-file' : '')}
              onDragOver={(e) => e.preventDefault()}
              onDrop={(e) => {
                e.preventDefault();
                readFile(e.dataTransfer.files?.[0]);
              }}
            >
              {sub.file ? (
                <>
                  <b>{sub.file.name}</b>
                  <span>{(sub.file.size / 1024).toFixed(1)}KB</span>
                </>
              ) : null}
              <p>
                <IFile />
                Drag and drop or{' '}
                <button type="button" className="link" onClick={() => fileRef.current?.click()}>
                  choose a file
                </button>{' '}
                to upload your goal targets
              </p>
              <small>All .csv file types are supported.</small>
            </div>
            <input
              ref={fileRef}
              type="file"
              accept=".csv,text/csv"
              hidden
              onChange={(e) => readFile(e.target.files?.[0])}
            />
            {sub.err ? (
              <p className="gx-err" role="alert">
                {sub.err}
              </p>
            ) : null}
          </div>
          <div className="gl-mf">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!(sub.file && sub.text != null)}
              onClick={importNow}
            >
              Import
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={() => setSub(null)}>
              Cancel
            </button>
          </div>
        </>
      );
    } else if (sub.t === 'template') {
      cls = 'gl-dlg gx-dlg gx-dlg--l gx-template-dlg';
      body = (
        <>
          {subHead('Create template')}
          <div className="gl-mb gx-mb gx-template-body">
            <div className="gl-fld">
              <label className="gx-lbl" htmlFor="cwTplName">
                Template name{' '}
                <span className="gx-info" title="Name used to identify this template">
                  {'ⓘ'}
                </span>
              </label>
              <input
                className="input"
                id="cwTplName"
                type="text"
                maxLength={100}
                value={tplName}
                autoFocus
                onChange={(e) => setTplName(e.target.value)}
              />
            </div>
            <div className="gl-fld">
              <label className="gx-lbl" htmlFor="cwTplDesc">
                Template description{' '}
                <span className="gx-info" title="Briefly describe this template">
                  {'ⓘ'}
                </span>
              </label>
              <textarea
                className="input"
                id="cwTplDesc"
                rows={3}
                value={tplDesc}
                onChange={(e) => setTplDesc(e.target.value)}
              />
            </div>
          </div>
          <div className="gl-mf gx-template-foot">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!tplName.trim() || busy}
              onClick={() => void saveTemplate('stay')}
            >
              Save template
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={() => setSub(null)}>
              Cancel
            </button>
          </div>
        </>
      );
    } else {
      body = (
        <>
          {subHead('Discard this ' + (tplPage ? 'template' : 'goal') + '?', true)}
          <div className="gl-mb gx-mb">
            <p>Your changes will be lost if you leave now.</p>
          </div>
          <div className="gl-mf">
            <button type="button" className="btn-crm gx-btn--danger" onClick={close}>
              Discard
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline gx-btn--blue"
              onClick={() => setSub(null)}
            >
              Keep editing
            </button>
          </div>
        </>
      );
    }
    subNode = (
      <div
        className="gl-ov"
        data-cw-ov
        onClick={(e) => {
          if (e.target === e.currentTarget) setSub(null);
        }}
      >
        <div className={cls} role="dialog" aria-modal="true">
          {body}
        </div>
      </div>
    );
  }

  if (tplPage) {
    return (
      <div className="gl gl--bare" data-gl>
        <div data-gl-layer>
          <div data-gx-lay="wiz">
            <div
              className="cw cw--tpl"
              role="dialog"
              aria-modal="true"
              aria-label="Create template"
            >
              <div className="cw-top cw-top--tpl create-template-h1">
                <h1 className="cw-pt">Create template</h1>
              </div>
              <div className="cw-b">
                <div className="cw-c cw-c--w">
                  <div className="cw-two tp-two">
                    <div className="cw-form">
                      <div className="ge-defh">
                        <h2 className="ge-h2">Define</h2>
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          disabled={!obj}
                          onClick={() => toast('Goal filters is coming soon')}
                        >
                          Add filters (0)
                        </button>
                      </div>
                      <Fld label="Template name" info id="cwTplName">
                        <input
                          className="input"
                          id="cwTplName"
                          type="text"
                          maxLength={100}
                          value={tplName}
                          autoComplete="off"
                          autoFocus
                          aria-invalid={tplErr ? true : undefined}
                          aria-describedby={tplErr ? 'cwTplErr' : undefined}
                          onChange={(e) => {
                            setTplName(e.target.value);
                            setTplErr('');
                            setDirty(true);
                          }}
                        />
                        {tplErr ? (
                          <p className="gx-err" id="cwTplErr" role="alert">
                            {tplErr}
                          </p>
                        ) : null}
                      </Fld>
                      {defineFields}
                      <Fld label="Template description" info id="cwTplDesc">
                        <textarea
                          className="input"
                          id="cwTplDesc"
                          rows={5}
                          maxLength={500}
                          value={tplDesc}
                          onChange={(e) => {
                            setTplDesc(e.target.value);
                            setDirty(true);
                          }}
                        />
                      </Fld>
                    </div>
                    <div className="cw-side">
                      <h2 className="ge-h2">Data preview</h2>
                      {previewBox}
                      {hintLinks}
                    </div>
                  </div>
                </div>
              </div>
              <div className="cw-ft">
                <div className="cw-fl">
                  <button type="button" className="link cw-cn" onClick={ask}>
                    Cancel
                  </button>
                </div>
                <div className="cw-fr">
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline"
                    disabled={!tplOk || busy}
                    onClick={() => void saveTemplate('exit')}
                  >
                    Save template and exit
                  </button>
                  <button
                    type="button"
                    className="btn-crm btn-crm--primary"
                    disabled={!tplOk || busy}
                    onClick={() => void saveTemplate('goal')}
                  >
                    Save and set goal using this template
                  </button>
                </div>
              </div>
              {subNode}
            </div>
          </div>
        </div>
        {toastNode}
      </div>
    );
  }

  const ok = step === 1 ? ok1 : step === 2 ? ok2 : step === 3 ? ok3 : true;
  const next = () => {
    if (step === 1) {
      if (!ok1) return;
      setStep(2);
      setDd(null);
    } else if (step === 2) {
      if (!ok2) return;
      buildRows();
      setStep(3);
      setDd(null);
      setMs(null);
    } else if (step === 3) {
      if (!ok3) return;
      const negative = negativeTarget();
      if (negative) {
        toast(negative);
        return;
      }
      setStep(4);
    } else void save();
  };

  return (
    <div className="gl gl--bare" data-gl>
      <div data-gl-layer>
        <div data-gx-lay="wiz">
          <div className="cw" role="dialog" aria-modal="true" aria-label="Create a goal">
            <div className="cw-top">
              <span className="cw-ttl">Create a goal</span>
              <ol className="cw-steps">
                {STEPS.map((label, i) => {
                  const done = step > i + 1;
                  const on = step === i + 1;
                  return (
                    <li
                      key={label}
                      className={'cw-s' + (done ? ' is-done' : on ? ' is-on' : '')}
                      aria-current={on ? 'step' : undefined}
                    >
                      <span className="cw-dot">{done ? <ICheck /> : null}</span>
                      <span className="cw-sl">{label}</span>
                    </li>
                  );
                })}
              </ol>
              <span className="cw-cnt">Step {step} of 4</span>
            </div>
            <div className="cw-b">
              {step === 1 ? step1 : step === 2 ? step2 : step === 3 ? step3 : step4}
            </div>
            <div className="cw-ft">
              <div className="cw-fl">
                {step > 1 ? (
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline"
                    onClick={() => {
                      setStep(step - 1);
                      setDd(null);
                      setMs(null);
                    }}
                  >
                    {'‹ Back'}
                  </button>
                ) : null}
                <button type="button" className="link cw-cn" onClick={ask}>
                  Cancel
                </button>
              </div>
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                disabled={!ok || busy}
                onClick={next}
              >
                {step === 4 ? 'Done' : 'Next ›'}
              </button>
            </div>
            {subNode}
          </div>
        </div>
      </div>
      {toastNode}
    </div>
  );
}
