'use client';

/**
 * Goal editor (QA #345, 13 Nov design edit-goal.php / goals.js "B) goal editor"): Edit goal
 * (name and definition with a data preview), Edit targets (monthly targets per team / user and
 * year, apply, add, import) and Edit notifications, with the unsaved-changes bar.
 */
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useRef, useState } from 'react';
import { errorText, isApiError } from '@/lib/api/errors';
import { deleteGoal, getGoal, getGoalOptions, previewGoal, updateGoal } from '../api.client';
import { downloadCsv } from '../export';
import {
  AGGS,
  EMPTY_OPTIONS,
  MON,
  TRACK_LABEL,
  countOnly,
  flash,
  fmtD,
  importTargets,
  isCurrencyDef,
  isoToDate,
  nf,
  objectOf,
  templateLabel,
  val,
} from '../model';
import type { Goal, GoalAggregation, GoalOptions, GoalTracking } from '../types';
import {
  Caret,
  Dd,
  Fld,
  IBulb,
  IExt,
  IFile,
  ITarg,
  IWarn,
  NotesList,
  Ovl,
  useGlToast,
  useLockScroll,
  useOutside,
  type DdOption,
  type Notes,
} from './parts';

interface EdRow {
  key: string;
  type: 'user' | 'team';
  id: string;
  name: string;
}

type Dialog =
  | { kind: 'apply'; val: string; err: boolean }
  | { kind: 'delete' }
  | { kind: 'discard' }
  | { kind: 'add'; picked: string[] }
  | {
      kind: 'import';
      file: { name: string; size: number } | null;
      text: string | null;
      err: string;
    };

const zeros = () => Array.from({ length: 12 }, () => '0');

export function GoalEditorView({ id }: { id: string }) {
  const router = useRouter();
  const params = useSearchParams();
  const from = params.get('from') === 'goal' ? 'goal' : 'list';
  const { toast, node: toastNode } = useGlToast();
  const [options, setOptions] = useState<GoalOptions | null>(null);
  const [goal, setGoal] = useState<Goal | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<'goal' | 'targets' | 'notif'>('goal');
  const [name, setName] = useState('');
  const [prop, setProp] = useState('');
  const [agg, setAgg] = useState<GoalAggregation>('COUNT');
  const [date, setDate] = useState('');
  const [track, setTrack] = useState<GoalTracking>('higher');
  const [notif, setNotif] = useState<Notes>({
    kick: false,
    exceeded: false,
    achieved: false,
    missed: false,
  });
  const [year, setYear] = useState(0);
  const [rows, setRows] = useState<EdRow[]>([]);
  const [tg, setTg] = useState<Record<number, Record<string, string[]>>>({});
  const [sel, setSel] = useState<Record<string, boolean>>({});
  const [dirty, setDirty] = useState(false);
  const [dd, setDd] = useState<string | null>(null);
  const [ddq, setDdq] = useState('');
  const [menu, setMenu] = useState(false);
  const [err, setErr] = useState('');
  const [dialog, setDialog] = useState<Dialog | null>(null);
  const [preview, setPreview] = useState<{
    value: number;
    currency: string | null;
    unit: string;
  } | null>(null);
  const [busy, setBusy] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);

  useOutside(dd !== null, '.gx-dd', () => setDd(null));
  useOutside(menu, '.gl-pos', () => setMenu(false));
  useLockScroll(dialog !== null);

  const reset = useCallback((g: Goal) => {
    setGoal(g);
    setName(g.name);
    setProp(g.definition.property);
    setAgg(g.definition.aggregation);
    setDate(g.definition.dateProperty);
    setTrack(g.definition.tracking);
    setNotif({
      kick: g.notifications.kickoff,
      exceeded: g.notifications.exceeded,
      achieved: g.notifications.achieved,
      missed: g.notifications.missed,
    });
    setYear(g.year);
    const stored: EdRow[] = g.targetRows.map((r) => ({
      key: r.type + ':' + r.id,
      type: r.type,
      id: r.id,
      name: r.name,
    }));
    const contributors: EdRow[] =
      g.contributorMode !== 'users' && g.teams.length
        ? g.teams.map((t) => ({
            key: 'team:' + t.id,
            type: 'team' as const,
            id: t.id,
            name: t.name,
          }))
        : g.userProgress.map((u) => ({
            key: 'user:' + u.id,
            type: 'user' as const,
            id: u.id,
            name: u.name,
          }));
    const list = stored.length ? stored : contributors;
    setRows(list);
    setTg({
      [g.year]: Object.fromEntries(
        list.map((r) => [
          r.key,
          g.targetRows.find((x) => x.type === r.type && x.id === r.id)?.months.map(String) ??
            zeros(),
        ]),
      ),
    });
    setSel({});
    setDirty(false);
    setErr('');
  }, []);

  useEffect(() => {
    const ac = new AbortController();
    getGoalOptions({ signal: ac.signal })
      .then(async (o) => {
        const g = await getGoal(id, o.year, { signal: ac.signal });
        setOptions(o);
        reset(g);
      })
      .catch((e: unknown) => {
        if (!ac.signal.aborted) setError(errorText(e));
      });
    return () => ac.abort();
  }, [id, reset]);

  const opts = options ?? EMPTY_OPTIONS;
  const cat = opts.catalogue;
  const obj = goal?.definition.objectType ?? 'meeting';

  // Data preview: the definition measured over this year.
  useEffect(() => {
    if (!goal || !prop || !agg || !date) return;
    const ac = new AbortController();
    previewGoal(
      { objectType: obj, property: prop, aggregation: agg, dateProperty: date },
      // DL12 (QA #477): the goal's users and teams, as its progress counts.
      {
        signal: ac.signal,
        userIds: goal.users.map((u) => u.id),
        teamIds: goal.teams.map((t) => t.id),
      },
    )
      .then((p) => setPreview({ value: p.value, currency: p.currency, unit: p.unit }))
      .catch(() => {
        if (!ac.signal.aborted) setPreview(null);
      });
    return () => ac.abort();
  }, [goal, obj, prop, agg, date]);

  // Targets of another year: loaded once when the year is first shown.
  useEffect(() => {
    if (!goal || !year || tg[year]) return;
    let live = true;
    void getGoal(id, year).then((g) => {
      if (!live) return;
      setTg((s) =>
        s[year]
          ? s
          : {
              ...s,
              [year]: Object.fromEntries(
                rows.map((r) => [
                  r.key,
                  g.targetRows
                    .find((x) => x.type === r.type && x.id === r.id)
                    ?.months.map(String) ?? zeros(),
                ]),
              ),
            },
      );
    });
    return () => {
      live = false;
    };
  }, [goal, year, tg, rows, id]);

  const leave = () => router.push(from === 'goal' ? '/goals/' + id : '/goals');

  if (error && !goal) {
    return (
      <div className="gl gl--bare gl--edit" data-gl>
        <div data-gl-page>
          <div className="ge">
            <div className="ge-b">
              <p>{error}</p>
              <button type="button" className="link" onClick={() => router.push('/goals')}>
                Back to goals
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
  if (!goal) {
    return (
      <div className="gl gl--bare gl--edit" data-gl>
        <div data-gl-page>
          <div className="ge">
            <div className="ge-b">
              <p>Loading goal{'…'}</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const gUnit = {
    unit: (goal.unit === 'currency' ? 'usd' : 'units') as 'usd' | 'units',
    currency: goal.currency,
  };
  const start = isoToDate(goal.startDate);
  const end = isoToDate(goal.endDate);
  const minYear = start.getFullYear();
  const maxYear = end.getFullYear() + 1;
  const mark = () => setDirty(true);
  const m = tg[year];
  const who = goal.contributorMode !== 'users' && goal.teams.length ? 'teams' : 'users';
  const isCur = isCurrencyDef(cat, { objectType: obj, property: prop, aggregation: agg });
  const unitLabel = isCur ? 'Amount in ' + (goal.currency || opts.currency) : 'Number of units';

  const pick = (key: string, v: string) => {
    if (key === 'prop') {
      setProp(v);
      if (countOnly(cat, obj, v) && agg !== 'COUNT') setAgg('COUNT');
    } else if (key === 'agg') setAgg(v as GoalAggregation);
    else if (key === 'date') setDate(v);
    else if (key === 'track') setTrack(v as GoalTracking);
    setDd(null);
    setDdq('');
    mark();
  };
  const toggleDd = (k: string) => {
    setDd(dd === k ? null : k);
    setDdq('');
  };
  const o = objectOf(cat, obj);
  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' && 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 sums = () => {
    const ms = Array.from({ length: 12 }, () => 0);
    const rt: Record<string, number> = {};
    let all = 0;
    for (const r of rows) {
      rt[r.key] = 0;
      (m?.[r.key] ?? zeros()).forEach((v, i) => {
        const n = parseFloat(v) || 0;
        ms[i]! += n;
        all += n;
        rt[r.key]! += n;
      });
    }
    return { ms, all, rt };
  };

  const save = async () => {
    const nm = name.trim();
    if (!nm) {
      setTab('goal');
      setErr('Enter a goal name.');
      return;
    }
    for (const y of Object.keys(tg).map(Number)) {
      for (const r of rows) {
        const vals = tg[y]![r.key] ?? zeros();
        for (let v = 0; v < 12; v++) {
          const n = parseFloat(vals[v]!);
          if (!isFinite(n) || n < 0) {
            setTab('targets');
            setYear(y);
            setErr('');
            toast('Enter a target of 0 or more for ' + r.name + ' ' + MON[v] + ' ' + y);
            return;
          }
        }
      }
    }
    const def = goal.definition;
    const defChanged =
      prop !== def.property ||
      agg !== def.aggregation ||
      date !== def.dateProperty ||
      track !== def.tracking;
    setBusy(true);
    try {
      const saved = await updateGoal(
        id,
        {
          name: nm,
          ...(defChanged
            ? {
                definition: {
                  property: prop,
                  aggregation: agg,
                  dateProperty: date,
                  tracking: track,
                },
              }
            : {}),
          notifications: {
            kickoff: notif.kick,
            exceeded: notif.exceeded,
            achieved: notif.achieved,
            missed: notif.missed,
          },
          targets: Object.keys(tg).map((y) => ({
            year: Number(y),
            rows: rows.map((r) => ({
              type: r.type,
              id: r.id,
              months: (tg[Number(y)]![r.key] ?? zeros()).map((x) => parseFloat(x) || 0),
            })),
          })),
        },
        year,
      );
      const keepTab = tab;
      const keepYear = year;
      reset(saved);
      setTab(keepTab);
      if (keepYear !== saved.year) setYear(keepYear);
      toast('Goal saved');
    } catch (e) {
      if (isApiError(e) && e.status === 409 && /name/i.test(e.message)) {
        setTab('goal');
        setErr(e.message);
      } else toast(errorText(e));
    } finally {
      setBusy(false);
    }
  };

  const setCell = (key: string, i: number, v: string) => {
    setTg((s) => {
      const yearVals = { ...(s[year] ?? {}) };
      const arr = (yearVals[key] ?? zeros()).slice();
      arr[i] = v;
      yearVals[key] = arr;
      return { ...s, [year]: yearVals };
    });
    mark();
  };

  const s = sums();
  const ns = rows.filter((r) => sel[r.key]).length;
  const allOn = rows.length > 0 && ns === rows.length;
  const canAdd =
    who === 'teams'
      ? opts.teams.some((t) => !rows.some((r) => r.type === 'team' && r.id === t.id))
      : opts.users.some((u) => !rows.some((r) => r.type === 'user' && r.id === u.id));

  const edGoal = (
    <div className="ge-two">
      <div className="ge-form">
        <h2 className="ge-h2">Details</h2>
        <Fld label="Goal name" req id="geN">
          <input
            className="input"
            id="geN"
            type="text"
            maxLength={120}
            value={name}
            autoComplete="off"
            onChange={(e) => {
              setName(e.target.value);
              setErr('');
              mark();
            }}
          />
          {err ? (
            <p className="gx-err" role="alert">
              {err}
            </p>
          ) : null}
        </Fld>
        <Fld label="Cadence" req info>
          <Dd
            id="cad"
            value={goal.cadence}
            placeholder=""
            options={[
              [
                goal.cadence,
                { monthly: 'Monthly', quarterly: 'Quarterly', yearly: 'Yearly' }[goal.cadence],
              ],
            ]}
            open={false}
            onToggle={() => {}}
            onPick={() => {}}
            dis
          />
        </Fld>
        <label className="check ge-chk is-dis">
          <input type="checkbox" disabled checked={goal.alignFiscalYear} readOnly />
          <span className="check__box" />
          <span>
            Align with your fiscal year settings?{' '}
            <a href="/settings/account-defaults" target="_blank" rel="noreferrer" className="link">
              View Settings <IExt />
            </a>
          </span>
        </label>
        <div className="ge-defh">
          <h2 className="ge-h2">Define goal</h2>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => toast('Goal filters is coming soon')}
          >
            Add filters (0)
          </button>
        </div>
        <Fld label="Template">
          <Dd
            id="tpl"
            value="t"
            placeholder=""
            options={[['t', templateLabel(goal, opts.savedTemplates)]]}
            open={false}
            onToggle={() => {}}
            onPick={() => {}}
            dis
          />
        </Fld>
        <Fld label="Object" req>
          <Dd
            id="obj"
            value={obj}
            placeholder=""
            options={[[obj, o?.label ?? obj]]}
            open={false}
            onToggle={() => {}}
            onPick={() => {}}
            dis
          />
        </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}
          />
        </Fld>
        <Fld label="Aggregation" req>
          <Dd
            id="agg"
            value={agg}
            placeholder="Select aggregation type"
            options={aggOpts}
            open={dd === 'agg'}
            onToggle={toggleDd}
            onPick={pick}
            desc
          />
        </Fld>
        <Fld label="Unit of measurement" info>
          <Dd
            id="unit"
            value="u"
            placeholder="Unit of measurement"
            options={[['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', goal.currency || 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}
          />
        </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>
      </div>
      <div className="ge-side">
        <h2 className="ge-h2">Data preview</h2>
        <button
          type="button"
          className="ge-prev"
          aria-label="Open report"
          onClick={() => toast('Records report is coming soon')}
        >
          <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'
                ? val({ unit: 'usd', currency: preview.currency }, preview.value)
                : nf(preview.value) + ' units'
              : '…'}
          </span>
        </button>
        <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>
        <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>
      </div>
    </div>
  );

  const edTargets = (
    <div className="ge-tg">
      <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"
            disabled={!canAdd}
            onClick={() => setDialog({ kind: 'add', picked: [] })}
          >
            Add {who === 'teams' ? 'team' : 'user'}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setDialog({ kind: '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 <= minYear}
              onClick={() => {
                setYear(year - 1);
                setSel({});
              }}
            >
              {'‹'}
            </button>
            <span aria-live="polite">{year}</span>
            <button
              type="button"
              aria-label="Next year"
              disabled={year >= maxYear}
              onClick={() => {
                setYear(year + 1);
                setSel({});
              }}
            >
              {'›'}
            </button>
          </span>
        </div>
      </div>
      {ns ? (
        <div className="gl-sel gx-sel">
          <b>{ns} selected</b>
          <button
            type="button"
            className="link gl-sel__a"
            onClick={() => setDialog({ kind: 'apply', val: '0', err: false })}
          >
            <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 {who === 'teams' ? 'team' : 'user'}</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.key, e.target.checked])))
                    }
                  />
                  <span className="check__box" />
                  <span className="gl-sr">Select all</span>
                </label>
              </th>
              <th scope="col" className="gx-c2">
                {who === 'teams' ? 'Team' : 'User'}
              </th>
              <th scope="col">Unit of meas{'…'}</th>
              {MON.map((mm) => (
                <th scope="col" key={mm}>
                  {mm} {year}
                </th>
              ))}
              <th scope="col">Yearly total</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r) => {
              const vals = m?.[r.key] ?? zeros();
              const n = vals.filter((v) => (parseFloat(v) || 0) > 0).length;
              return (
                <tr key={r.key}>
                  <td className="gl-c1">
                    <label className="check">
                      <input
                        type="checkbox"
                        checked={Boolean(sel[r.key])}
                        onChange={(e) => setSel({ ...sel, [r.key]: e.target.checked })}
                      />
                      <span className="check__box" />
                      <span className="gl-sr">Select {r.name}</span>
                    </label>
                  </td>
                  <th scope="row" className="gx-c2">
                    <span className="gx-ell" title={r.name}>
                      {r.name}
                    </span>
                  </th>
                  <td className="gx-u">{unitLabel}</td>
                  {vals.map((v, i) => (
                    <td key={i}>
                      <input
                        className="input gx-n"
                        type="number"
                        min="0"
                        step="any"
                        value={v}
                        disabled={!m}
                        aria-label={r.name + ' ' + MON[i] + ' ' + year + ' target'}
                        onChange={(e) => setCell(r.key, i, e.target.value)}
                      />
                    </td>
                  ))}
                  <td className="gx-yt">
                    <div>
                      {val(gUnit, s.rt[r.key] ?? 0)} (
                      {s.all ? Math.round(((s.rt[r.key] ?? 0) / s.all) * 100) : 0}%)
                    </div>
                    <div className="gx-ym">{n}/12 months</div>
                  </td>
                </tr>
              );
            })}
          </tbody>
          <tfoot>
            <tr>
              <td className="gl-c1" />
              <th scope="row" className="gx-c2">
                All {who}
              </th>
              <td />
              {s.ms.map((v, i) => (
                <td key={i}>{val(gUnit, v)}</td>
              ))}
              <td>{val(gUnit, s.all)}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );

  const edNotif = (
    <div className="ge-nt">
      <h2 className="ge-h2">Set notifications</h2>
      <p className="ge-hint">
        Select which notifications to send to users. Any changes you make to notifications will
        apply to all users.
      </p>
      <hr />
      <NotesList
        notes={notif}
        onChange={(k, on) => {
          setNotif({ ...notif, [k]: on });
          mark();
        }}
      />
    </div>
  );

  const whoWord = who === 'teams' ? 'team' : 'user';
  const runImport = () => {
    if (dialog?.kind !== 'import' || dialog.text == null) return;
    const res = importTargets(
      dialog.text,
      rows.map((r) => r.name),
      12,
    );
    if ('error' in res) {
      setDialog({ ...dialog, err: res.error });
      return;
    }
    setTg((st) => {
      const yv = { ...(st[year] ?? {}) };
      for (const r of rows) {
        const vals = res.values.get(r.name);
        if (vals) yv[r.key] = vals.map(String);
      }
      return { ...st, [year]: yv };
    });
    setDialog(null);
    mark();
    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)) {
      setDialog({ kind: 'import', file: null, text: null, err: 'Only .csv files are supported.' });
      return;
    }
    if (f.size > 2 * 1024 * 1024) {
      setDialog({ kind: 'import', file: null, text: null, err: 'The file is larger than 2 MB.' });
      return;
    }
    const meta = { name: f.name, size: f.size };
    setDialog({ kind: 'import', file: meta, text: null, err: '' });
    const rd = new FileReader();
    rd.onload = () => setDialog({ kind: 'import', file: meta, text: String(rd.result), err: '' });
    rd.onerror = () =>
      setDialog({ kind: 'import', file: null, text: null, err: 'The file could not be read.' });
    rd.readAsText(f);
  };

  let dlg: React.ReactNode = null;
  if (dialog?.kind === 'apply') {
    dlg = (
      <Ovl
        title="Apply targets"
        big
        cls="gx-dlg--s"
        onClose={() => setDialog(null)}
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => {
                const n = parseFloat(dialog.val);
                if (!isFinite(n) || n < 0) {
                  setDialog({ ...dialog, err: true });
                  return;
                }
                setTg((st) => {
                  const yv = { ...(st[year] ?? {}) };
                  for (const r of rows)
                    if (sel[r.key]) yv[r.key] = Array.from({ length: 12 }, () => String(n));
                  return { ...st, [year]: yv };
                });
                setDialog(null);
                mark();
                toast('Targets applied');
              }}
            >
              Apply
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDialog(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <label className="gx-lbl" htmlFor="geAp">
          Amount
        </label>
        <div className="gx-amt">
          <span>{unitLabel}</span>
          <input
            className="input"
            id="geAp"
            type="number"
            min="0"
            step="any"
            value={dialog.val}
            autoFocus
            onChange={(e) => setDialog({ ...dialog, val: e.target.value, err: false })}
          />
        </div>
        <p className="gx-err" role="alert" hidden={!dialog.err}>
          Enter an amount of 0 or more.
        </p>
      </Ovl>
    );
  } else if (dialog?.kind === 'delete') {
    dlg = (
      <Ovl
        title="Delete this goal"
        big
        cls="gx-dlg--s"
        onClose={() => setDialog(null)}
        foot={
          <>
            <button
              type="button"
              className="btn-crm gx-btn--danger"
              disabled={busy}
              onClick={() => {
                setBusy(true);
                deleteGoal(id)
                  .then(() => {
                    flash('Goal deleted');
                    router.push('/goals');
                  })
                  .catch((e: unknown) => {
                    setBusy(false);
                    toast(errorText(e));
                  });
              }}
            >
              Delete goal
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline gx-btn--blue"
              onClick={() => setDialog(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <p>
          You{'’'}re about to delete this goal. This means you{'’'}ll lose all goals for teams and
          users who are working on this goal.
        </p>
        <p>All historical progress data tracked for this goal will also be permanently deleted.</p>
      </Ovl>
    );
  } else if (dialog?.kind === 'discard') {
    dlg = (
      <Ovl
        title="Discard changes?"
        big
        cls="gx-dlg--s"
        onClose={() => setDialog(null)}
        foot={
          <>
            <button type="button" className="btn-crm gx-btn--danger" onClick={leave}>
              Discard changes
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline gx-btn--blue"
              onClick={() => setDialog(null)}
            >
              Keep editing
            </button>
          </>
        }
      >
        <p>You have unsaved changes to this goal. Your changes will be lost if you leave now.</p>
      </Ovl>
    );
  } else if (dialog?.kind === 'add') {
    const avail =
      who === 'teams'
        ? opts.teams
            .filter((t) => !rows.some((r) => r.type === 'team' && r.id === t.id))
            .map((t): { id: string; name: string; email?: string } => ({ id: t.id, name: t.name }))
        : opts.users
            .filter((u) => !rows.some((r) => r.type === 'user' && r.id === u.id))
            .map((u) => ({ id: u.id, name: u.name, email: u.email }));
    dlg = (
      <Ovl
        title={'Add ' + whoWord}
        onClose={() => setDialog(null)}
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              onClick={() => {
                if (!dialog.picked.length) return;
                const added = avail
                  .filter((a) => dialog.picked.includes(a.id))
                  .map((a) => ({
                    key: (who === 'teams' ? 'team:' : 'user:') + a.id,
                    type: (who === 'teams' ? 'team' : 'user') as 'team' | 'user',
                    id: a.id,
                    name: a.name,
                  }));
                setRows([...rows, ...added]);
                setTg((st) => {
                  const next = { ...st };
                  for (const y of Object.keys(next)) {
                    next[Number(y)] = {
                      ...next[Number(y)]!,
                      ...Object.fromEntries(added.map((a) => [a.key, zeros()])),
                    };
                  }
                  return next;
                });
                setDialog(null);
                mark();
              }}
            >
              Confirm
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDialog(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <div className="gx-lbl">{who === 'teams' ? 'Team' : 'User'}</div>
        {avail.map((t) => (
          <label key={t.id} className="check gx-opt">
            <input
              type="checkbox"
              checked={dialog.picked.includes(t.id)}
              onChange={(e) =>
                setDialog({
                  ...dialog,
                  picked: e.target.checked
                    ? [...dialog.picked, t.id]
                    : dialog.picked.filter((x) => x !== t.id),
                })
              }
            />
            <span className="check__box" />
            <span className="gl-ot">
              {t.name}
              {t.email ? <small>{t.email}</small> : null}
            </span>
          </label>
        ))}
      </Ovl>
    );
  } else if (dialog?.kind === 'import') {
    dlg = (
      <Ovl
        title={'Import ' + whoWord + ' targets'}
        cls="gx-dlg--l"
        onClose={() => setDialog(null)}
        foot={
          <>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={!(dialog.file && dialog.text != null)}
              onClick={runImport}
            >
              Import
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDialog(null)}
            >
              Cancel
            </button>
          </>
        }
      >
        <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 {whoWord} or rep, you
          must include all new and existing targets for that {whoWord} 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>
        <button
          type="button"
          className="link gx-tpl"
          onClick={() =>
            downloadCsv(
              [
                ['Name', ...MON.map((m2) => m2 + ' ' + year)],
                ...rows.map((r) => [r.name, ...(m?.[r.key] ?? zeros())]),
              ],
              'goal-targets-' + year,
            )
          }
        >
          Or edit goals by downloading the pre-populated .csv files <IExt />
        </button>
        <h3 className="gx-h3">Goal target file</h3>
        <div
          className={'gx-dz' + (dialog.file ? ' has-file' : '')}
          onDragOver={(e) => e.preventDefault()}
          onDrop={(e) => {
            e.preventDefault();
            readFile(e.dataTransfer.files?.[0]);
          }}
        >
          {dialog.file ? (
            <>
              <b>{dialog.file.name}</b>
              <span>{(dialog.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])}
        />
        {dialog.err ? (
          <p className="gx-err" role="alert">
            {dialog.err}
          </p>
        ) : null}
      </Ovl>
    );
  }

  return (
    <div className="gl gl--bare gl--edit" data-gl>
      <div data-gl-page>
        <div className="ge">
          <div className="ge-hd">
            <header className="ge-h">
              <h1 className="ge-t">{goal.name}</h1>
              <div className="ge-acts">
                <span className="gl-pos">
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline"
                    aria-haspopup="menu"
                    aria-expanded={menu}
                    onClick={() => setMenu(!menu)}
                  >
                    Actions
                    <Caret />
                  </button>
                  {menu ? (
                    <div className="gl-menu gl-menu--r" role="menu">
                      <a
                        href="/settings/account-defaults"
                        target="_blank"
                        rel="noreferrer"
                        className="gl-mi"
                      >
                        Account settings <IExt />
                      </a>
                      <button
                        type="button"
                        role="menuitem"
                        className="gl-mi"
                        onClick={() => {
                          setMenu(false);
                          setDialog({ kind: 'delete' });
                        }}
                      >
                        Delete goal
                      </button>
                    </div>
                  ) : null}
                </span>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  onClick={() => (dirty ? setDialog({ kind: 'discard' }) : leave())}
                >
                  Exit
                </button>
              </div>
            </header>
            <div className="ge-tabs" role="tablist">
              {(
                [
                  ['goal', 'Edit goal'],
                  ['targets', 'Edit targets'],
                  ['notif', 'Edit notifications'],
                ] as const
              ).map((t) => (
                <button
                  key={t[0]}
                  type="button"
                  role="tab"
                  className={'ge-tab' + (tab === t[0] ? ' is-on' : '')}
                  aria-selected={tab === t[0]}
                  onClick={() => {
                    setTab(t[0]);
                    setDd(null);
                    setMenu(false);
                  }}
                >
                  {t[1]}
                </button>
              ))}
            </div>
          </div>
          <div className="ge-b">
            {tab === 'goal' ? edGoal : tab === 'targets' ? edTargets : edNotif}
          </div>
          <div className="ge-bar" hidden={!dirty}>
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={busy}
              onClick={() => void save()}
            >
              Save
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => {
                const keepTab = tab;
                reset(goal);
                setTab(keepTab);
                toast('Changes discarded');
              }}
            >
              Cancel
            </button>
            <span>You have unsaved changes to this goal.</span>
          </div>
        </div>
      </div>
      {dlg}
      {toastNode}
    </div>
  );
}
