'use client';

/**
 * A goal's page (QA #345, 13 Nov design goal-monthly-meetings.php / goals.js "A) goal page"):
 * Summary (total progress gauge, actual versus team goals, leaderboard, goals in progress /
 * achieved / missed) and Team / User performance tables, with the year range and Actions.
 */
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { errorText } from '@/lib/api/errors';
import { getGoal, getGoalOptions } from '../api.client';
import { AVT_LAYOUT, avtSvg, gvGauge, lbSvg, type AvtPoint } from '../charts';
import {
  DASH,
  EMPTY_OPTIONS,
  MON,
  fmtD,
  isoToDate,
  nf,
  sum,
  takeFlash,
  teamRows,
  toVM,
  userRows,
  type GoalVM,
} from '../model';
import { useCanManageGoals } from '../permissions';
import type { Goal, GoalOptions } from '../types';
import { GoalDefinitionDialog } from './dialogs';
import { membersOfTeam } from './GoalsListView';
import { Caret, EmptyArt, IBack, IExt, IKeb, ISlid, useGlToast, useOutside } from './parts';
import {
  BreakdownMenu,
  CheckMenu,
  FilterButton,
  GoalsTableView,
  YearRange,
  columns,
  sortRows,
  type Breakdown,
  type SortState,
} from './table';

type GTab = 'summary' | 'teams' | 'users';
const GV_FLT = ['Goal ID', 'Status', 'Assignee team ID'];

function Chip({ c, onTip }: { c: string; onTip: (el: HTMLElement | null, c: string) => void }) {
  return (
    <span
      className="gv-chip gv-chip--tip"
      tabIndex={0}
      onMouseEnter={(e) => onTip(e.currentTarget, c)}
      onMouseLeave={() => onTip(null, c)}
      onFocus={(e) => onTip(e.currentTarget, c)}
      onBlur={() => onTip(null, c)}
    >
      {c}
    </span>
  );
}

export function GoalPageView({ id }: { id: string }) {
  const router = useRouter();
  const canManage = useCanManageGoals();
  const { toast, node: toastNode } = useGlToast();
  const [options, setOptions] = useState<GoalOptions | null>(null);
  const [year, setYear] = useState<number | null>(null);
  const [goal, setGoal] = useState<Goal | null>(null);
  const [prev, setPrev] = useState<Goal | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<GTab>('summary');
  const [menu, setMenu] = useState<string | null>(null);
  const [mq, setMq] = useState('');
  const [bd, setBd] = useState<Breakdown>('total');
  const [fTeam, setFTeam] = useState<string[]>([]);
  const [fUser, setFUser] = useState<string[]>([]);
  const [sort, setSort] = useState<Record<'teams' | 'users', SortState>>({
    teams: { k: 'name', d: 1 },
    users: { k: 'name', d: 1 },
  });
  const [page, setPage] = useState(1);
  const [per, setPer] = useState(25);
  const [sel, setSel] = useState<Record<string, boolean>>({});
  const [definition, setDefinition] = useState(false);
  const [tip, setTip] = useState<{ c: string; left: number; top: number } | null>(null);
  const chartRef = useRef<HTMLDivElement>(null);
  const avtRef = useRef<AvtPoint[]>([]);

  useOutside(menu !== null, '.gl-pos', () => setMenu(null));

  useEffect(() => {
    const m = takeFlash();
    if (m) toast(m);
  }, [toast]);

  useEffect(() => {
    const ac = new AbortController();
    getGoalOptions({ signal: ac.signal })
      .then((o) => {
        setOptions(o);
        setYear((y) => y ?? o.year);
      })
      .catch((e: unknown) => {
        if (!ac.signal.aborted) setError(errorText(e));
      });
    return () => ac.abort();
  }, []);

  const load = useCallback(
    async (y: number, signal?: AbortSignal) => {
      try {
        const [cur, before] = await Promise.all([
          getGoal(id, y, { signal }),
          getGoal(id, y - 1, { signal }),
        ]);
        setGoal(cur);
        setPrev(before);
        setError(null);
      } catch (e) {
        if (!signal?.aborted) setError(errorText(e));
      }
    },
    [id],
  );

  useEffect(() => {
    if (year === null) return;
    const ac = new AbortController();
    void load(year, ac.signal);
    return () => ac.abort();
  }, [year, load]);

  const opts = options ?? EMPTY_OPTIONS;
  const today = { year: opts.year, month: opts.month };
  const yr = year ?? opts.year;
  const g: GoalVM | null = useMemo(
    () => (goal ? toVM(goal, opts.savedTemplates) : null),
    [goal, opts.savedTemplates],
  );
  const membersOf = useCallback((team: string) => membersOfTeam(opts, team), [opts]);

  const rows = useMemo(() => {
    if (!g || tab === 'summary') return [];
    const out =
      tab === 'teams'
        ? teamRows(g, yr, today).filter((r) => !fTeam.length || fTeam.includes(r.team))
        : userRows(g, yr, today).filter(
            (r) =>
              (!fUser.length || fUser.includes(r.user)) &&
              (!fTeam.length || fTeam.includes(r.team)),
          );
    return sortRows(out, sort[tab]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [g, tab, fTeam, fUser, sort, yr, today.year, today.month]);

  if (error && !goal) {
    return (
      <div className="gl gl--sub" data-gl>
        <div className="gl-body">
          <div className="gl-tw">
            <div className="gl-empty">
              <p>{error}</p>
              <Link className="link" href="/goals">
                Back to goals
              </Link>
            </div>
          </div>
        </div>
      </div>
    );
  }
  if (!g || !goal) {
    return (
      <div className="gl gl--sub" data-gl>
        <div className="gl-body">
          <div className="gl-tw">
            <div className="gl-empty">
              <p>Loading goal{'…'}</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const start = isoToDate(goal.startDate);
  const end = isoToDate(goal.endDate);
  const minYear = Math.min(start.getFullYear(), opts.year - 1);
  const maxYear = Math.max(end.getFullYear(), opts.year);
  const rng = fmtD(start) + ' to ' + fmtD(end);
  const pct = g.goal ? (g.prog / g.goal) * 100 : 0;
  const noun =
    g.unit === 'usd'
      ? 'Amount'
      : goal.definition.objectType === 'meeting'
        ? 'Meetings'
        : 'Goal progress';
  const ents = (goal.teamProgress.length ? goal.teamProgress : goal.userProgress).map((e) => ({
    n: e.name,
    a: e.actualTotal,
    t: Math.round(sum(e.targets) * 100) / 100,
  }));
  let ach = 0;
  let prg = 0;
  let mis = 0;
  for (const e of ents) {
    const p = e.t ? (e.a / e.t) * 100 : 0;
    if (p >= 100) ach++;
    else if (p > 0) prg++;
    else mis++;
  }
  // 24 months: last year and this year; months still to come have no actual.
  const pts: AvtPoint[] = [];
  for (let i = 0; i < 24; i++) {
    const src = i < 12 ? prev : goal;
    const y = yr - 1 + Math.floor(i / 12);
    const m = i % 12;
    const future = y > today.year || (y === today.year && m >= today.month);
    pts.push({
      l: MON[m] + ' ' + y,
      t: Math.round(src?.targets[m] ?? 0),
      a: future ? null : Math.round(src?.actuals[m] ?? 0),
    });
  }
  avtRef.current = pts;

  const onTip = (el: HTMLElement | null, c: string) => {
    if (!el) {
      setTip(null);
      return;
    }
    const r = el.getBoundingClientRect();
    setTip({ c, left: Math.max(8, Math.min(r.left, window.innerWidth - 268)), top: r.bottom + 8 });
  };
  const tipBody = (c: string) => {
    const m = /^Filters \((\d+)\)$/.exec(c);
    if (m) {
      return (
        <>
          <p className="gv-ctip__h">Active Filters:</p>
          <ul className="gv-ctip__l">
            {GV_FLT.slice(0, Math.max(1, Math.min(+m[1]!, GV_FLT.length))).map((x) => (
              <li key={x}>{x}</li>
            ))}
          </ul>
        </>
      );
    }
    const p = c.split(' | ');
    return (
      <>
        <p className="gv-ctip__h">Date range:</p>
        <p className="gv-ctip__v">{p[0]}</p>
        {p[1] ? (
          <>
            <p className="gv-ctip__h">Frequency:</p>
            <p className="gv-ctip__v">{p[1]}</p>
          </>
        ) : null}
      </>
    );
  };

  const card = (
    key: string,
    title: string,
    chips: string[],
    legend: React.ReactNode,
    inner: React.ReactNode,
    cls?: string,
  ) => {
    const k = 'gvk-' + key;
    return (
      <section className={'gv-card ' + (cls ?? '')} key={key}>
        <header className="gv-card__h">
          <h3>{title}</h3>
          <span className="gv-card__t">
            <button
              type="button"
              className="gv-ib"
              aria-label="Chart settings"
              onClick={() => toast('Chart settings are coming soon')}
            >
              <ISlid />
            </button>
            <span className="gl-pos">
              <button
                type="button"
                className="gv-ib"
                aria-haspopup="menu"
                aria-expanded={menu === k}
                aria-label="More options"
                onClick={() => setMenu(menu === k ? null : k)}
              >
                <IKeb />
              </button>
              {menu === k ? (
                <div className="gl-menu gl-menu--r" role="menu">
                  <button
                    type="button"
                    role="menuitem"
                    className="gl-mi"
                    onClick={() => {
                      setMenu(null);
                      toast('Save report is coming soon');
                    }}
                  >
                    Save report
                  </button>
                </div>
              ) : null}
            </span>
          </span>
        </header>
        <p className="gv-chips">
          {chips.map((c) => (
            <Chip key={c} c={c} onTip={onTip} />
          ))}
        </p>
        {legend}
        {inner}
      </section>
    );
  };

  const stat = (key: string, title: string, n: number) =>
    card(
      key,
      title,
      ['All time', 'Filters (3)'],
      null,
      <>
        <button
          type="button"
          className="gv-cl gv-cl--go"
          aria-haspopup="dialog"
          onClick={() => toast('Goal records report is coming soon')}
        >
          (Count) Goals
        </button>
        <p className="gv-big">{n}</p>
      </>,
      'gv-card--s',
    );

  const onChartMove = (e: React.MouseEvent<HTMLDivElement>) => {
    const c = chartRef.current;
    if (!c) return;
    const P = avtRef.current;
    const { W, L } = AVT_LAYOUT;
    const pw = W - L - AVT_LAYOUT.Rr;
    const n = Math.max(1, P.length - 1);
    const r = c.getBoundingClientRect();
    const sx = ((e.clientX - r.left) / r.width) * W;
    const k = Math.round((sx - L) / (pw / n));
    const tipEl = c.querySelector<HTMLDivElement>('.gv-tip');
    const vl = c.querySelector('[data-gv-vl]');
    if (!tipEl || !vl) return;
    if (k < 0 || k > n) {
      tipEl.hidden = true;
      vl.setAttribute('visibility', 'hidden');
      return;
    }
    const p = P[k]!;
    const px = ((L + (pw * k) / n) / W) * r.width;
    vl.setAttribute('x1', String(L + (pw * k) / n));
    vl.setAttribute('x2', String(L + (pw * k) / n));
    vl.setAttribute('visibility', 'visible');
    const a = p.a ?? 0;
    const tot = a + p.t;
    const pa = tot ? Math.round((a / tot) * 100) : 0;
    const nn = g.unit === 'usd' ? 'Amount' : noun;
    tipEl.innerHTML =
      '<div class="gv-tip__h">' +
      p.l +
      '</div><div class="gv-tip__b"><p>(Count) ' +
      nn +
      '</p><p><i style="background:#2456e6"></i><b>(Count) ' +
      nn +
      '</b> <b>' +
      nf(a) +
      '</b> <span>(' +
      pa +
      '%)</span></p><p class="gv-tip__t"><span>Totals:</span><span>' +
      nf(a) +
      '</span></p><p>(Sum) Goal target</p><p><i style="background:#c7cdd4"></i>(Sum) Goal target <span class="gv-tip__v">' +
      nf(p.t) +
      '</span> <span>(' +
      (100 - pa) +
      '%)</span></p><p class="gv-tip__t"><span>Totals:</span><span>' +
      nf(p.t) +
      '</span></p></div>';
    tipEl.hidden = false;
    const tw = tipEl.offsetWidth;
    let left = px + 14;
    if (left + tw > r.width - 4) left = px - tw - 14;
    tipEl.style.left = Math.max(4, left) + 'px';
    tipEl.style.top = '12px';
  };

  const summary = (
    <div className="gv-grid">
      {card(
        'tp',
        'Total progress',
        ['All time', 'Filters (2)'],
        <p className="gv-leg">
          <i className="gv-leg__l" />
          (Sum) Goal progress amount
        </p>,
        <div
          className="gv-gauge"
          dangerouslySetInnerHTML={{ __html: gvGauge(pct, g.prog, g.goal) }}
        />,
      )}
      {card(
        'avt',
        'Actual versus team goals',
        ['From ' + rng + ' | Monthly', 'Filters (1)'],
        <>
          <p className="gv-leg">
            <i className="gv-leg__d" style={{ background: '#2456e6' }} />
            (Count) {noun} <i className="gv-leg__d" style={{ background: '#c7cdd4' }} />
            (Sum) Goal target
          </p>
          <p className="gv-ytl">(Sum) Goal target</p>
        </>,
        <div
          className="gv-chart"
          data-gv-chart
          ref={chartRef}
          onMouseMove={onChartMove}
          onMouseLeave={() => {
            const c = chartRef.current;
            const t = c?.querySelector<HTMLDivElement>('.gv-tip');
            if (t) t.hidden = true;
            c?.querySelector('[data-gv-vl]')?.setAttribute('visibility', 'hidden');
          }}
          dangerouslySetInnerHTML={{ __html: avtSvg(pts) }}
        />,
      )}
      {card(
        'lb',
        'Team leaderboard',
        ['From ' + rng, 'Filters (1)'],
        <>
          <p className="gv-leg">
            <i className="gv-leg__d" style={{ background: '#ffa889' }} />
            (Count) {noun} <i className="gv-leg__l" style={{ background: '#111' }} />
            (Sum) Goal target
          </p>
          <p className="gv-ytl">{goal.teams[0]?.name ?? 'CRM Team'}</p>
        </>,
        <div className="gv-chart" dangerouslySetInnerHTML={{ __html: lbSvg(ents) }} />,
      )}
      <div className="gv-3">
        {stat('ip', 'Team goals in progress', prg)}
        {stat('ac', 'Team goals achieved', ach)}
        {stat('ms', 'Team goals missed', mis)}
      </div>
    </div>
  );

  const det = tab !== 'summary';
  const cols = det
    ? columns({
        tab: tab,
        det: true,
        cols: { tpl: true, teams: true, users: true, goal: true, prog: true },
        bd,
        status: false,
        year: yr,
        today,
        membersOf,
        onOpen: () => {},
        onEdit: () => {},
        onActions: () => {},
        openMenuKey: null,
      })
    : [];
  const who = tab === 'users' ? 'user' : 'team';
  const other = tab === 'users' ? 'team' : 'user';
  const any = fTeam.length > 0 || fUser.length > 0 || bd !== 'total';

  return (
    <div className="gl gl--sub" data-gl>
      <header className="gl-head">
        <h1 className="gl-h1">Goals</h1>
        <div className="gl-head__acts" data-gl-top />
      </header>
      <div className="gl-body">
        <div className="gl-bar gv-bar" data-gl-bar>
          <div className="gv-top">
            <div>
              <button type="button" className="gv-back" onClick={() => router.push('/goals')}>
                <IBack />
                Back to goals
              </button>
              <h1 className="gv-t">{g.name}</h1>
            </div>
            <div className="gv-acts">
              <button
                type="button"
                className="link refresh-goal-progress-link"
                onClick={() => {
                  void load(yr).then(() => toast('Goal progress refreshed'));
                }}
              >
                Refresh goal progress
              </button>
              <span className="gl-pos">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  aria-haspopup="menu"
                  aria-expanded={menu === 'gvact'}
                  onClick={() => setMenu(menu === 'gvact' ? null : 'gvact')}
                >
                  Actions
                  <Caret />
                </button>
                {menu === 'gvact' ? (
                  <div className="gl-menu gl-menu--r gv-menu" role="menu">
                    <button
                      type="button"
                      role="menuitem"
                      className="gl-mi"
                      onClick={() => {
                        setMenu(null);
                        setDefinition(true);
                      }}
                    >
                      View goal definition
                    </button>
                    <a
                      href="/settings/account-defaults"
                      target="_blank"
                      rel="noreferrer"
                      role="menuitem"
                      className="gl-mi"
                    >
                      Manage account settings <IExt />
                    </a>
                    <a
                      href="/settings/users"
                      target="_blank"
                      rel="noreferrer"
                      role="menuitem"
                      className="gl-mi"
                    >
                      Update goal permissions <IExt />
                    </a>
                  </div>
                ) : null}
              </span>
              {canManage ? (
                <button
                  type="button"
                  className="btn-crm btn-crm--primary"
                  onClick={() => router.push('/goals/' + g.id + '/edit?from=goal')}
                >
                  Edit Goal
                </button>
              ) : null}
            </div>
          </div>
          <dl className="gv-meta">
            <div>
              <dt>Cadence</dt>
              <dd>{g.cad || 'Monthly'}</dd>
            </div>
            <div>
              <dt>Start date</dt>
              <dd>{fmtD(start)}</dd>
            </div>
            <div>
              <dt>End date</dt>
              <dd>{fmtD(end)}</dd>
            </div>
            <div>
              <dt>Created by</dt>
              <dd>{g.by || DASH}</dd>
            </div>
          </dl>
          <div className="gv-tabs" role="tablist">
            {(
              [
                ['summary', 'Summary'],
                ['teams', 'Team performance'],
                ['users', 'User performance'],
              ] as const
            ).map((t) => (
              <button
                key={t[0]}
                type="button"
                role="tab"
                className={'gv-tab' + (tab === t[0] ? ' is-on' : '')}
                aria-selected={tab === t[0]}
                onClick={() => {
                  setTab(t[0]);
                  setPage(1);
                  setMenu(null);
                  setSel({});
                }}
              >
                {t[1]}
              </button>
            ))}
          </div>
        </div>
        <div className="gl-filters" data-gl-filters hidden={!det}>
          {det ? (
            <>
              <FilterButton
                id="bd"
                label="Total progress breakdown"
                n={0}
                always
                open={menu === 'bd'}
                onToggle={(i) => setMenu(menu === i ? null : i)}
              >
                <BreakdownMenu
                  bd={bd}
                  onPick={(b) => {
                    setBd(b);
                    setMenu(null);
                  }}
                />
              </FilterButton>
              <FilterButton
                id="team"
                label="Teams"
                n={fTeam.length}
                open={menu === 'team'}
                onToggle={(i) => setMenu(menu === i ? null : i)}
              >
                <CheckMenu
                  id="team"
                  opts={opts.teams.map((t) => [t.name, t.name, false, ''])}
                  selected={(v) => fTeam.includes(v)}
                  search={false}
                  query=""
                  onQuery={() => {}}
                  wide="t"
                  onToggleOpt={(v, on) =>
                    setFTeam((x) =>
                      on ? [...x.filter((y) => y !== v), v] : x.filter((y) => y !== v),
                    )
                  }
                  onClear={fTeam.length ? () => setFTeam([]) : undefined}
                />
              </FilterButton>
              {tab === 'users' ? (
                <FilterButton
                  id="user"
                  label="Users"
                  n={fUser.length}
                  open={menu === 'user'}
                  onToggle={(i) => {
                    setMenu(menu === i ? null : i);
                    setMq('');
                  }}
                >
                  <CheckMenu
                    id="user"
                    opts={opts.users.map((u) => [u.name, u.name])}
                    selected={(v) => fUser.includes(v)}
                    search
                    query={mq}
                    onQuery={setMq}
                    onToggleOpt={(v, on) =>
                      setFUser((x) =>
                        on ? [...x.filter((y) => y !== v), v] : x.filter((y) => y !== v),
                      )
                    }
                    onClear={fUser.length ? () => setFUser([]) : undefined}
                  />
                </FilterButton>
              ) : null}
              <button
                type="button"
                className="gv-clear"
                disabled={!any}
                onClick={() => {
                  setFTeam([]);
                  setFUser([]);
                  setBd('total');
                  setPage(1);
                }}
              >
                Clear all
              </button>
              <YearRange year={yr} min={minYear} max={maxYear} onStep={(d) => setYear(yr + d)} />
            </>
          ) : null}
        </div>
        <div data-gl-main>
          {!det ? (
            summary
          ) : rows.length ? (
            <GoalsTableView
              cols={cols}
              rows={rows}
              sort={sort[tab]}
              onSort={(k) =>
                setSort((s) => ({
                  ...s,
                  [tab]: s[tab].k === k ? { k, d: s[tab].d === 1 ? -1 : 1 } : { k, d: 1 },
                }))
              }
              sel={sel}
              onSel={(keys, on) =>
                setSel((s) => ({ ...s, ...Object.fromEntries(keys.map((k) => [k, on])) }))
              }
              page={page}
              per={per}
              perMenu={menu === 'per'}
              onPage={setPage}
              onTogglePer={() => setMenu(menu === 'per' ? null : 'per')}
              onPer={(n) => {
                setPer(n);
                setPage(1);
                setMenu(null);
              }}
              onClearSel={() => setSel({})}
              caption={tab === 'teams' ? 'Team performance' : 'User performance'}
            />
          ) : (
            <div className="gl-tw">
              <div className="gl-empty gv-empty">
                <EmptyArt />
                <h2>No {who} goals were found. Try one of the following:</h2>
                <p>
                  If you set a {who} goal, update the filters. If not, create one and it will appear
                  here. To view {other} goals, go to the {other} performance page. Or, try
                  refreshing the page.
                </p>
              </div>
            </div>
          )}
        </div>
      </div>
      {definition ? (
        <GoalDefinitionDialog
          g={g}
          catalogue={opts.catalogue}
          onClose={() => setDefinition(false)}
        />
      ) : null}
      {tip ? (
        <div
          className="gv-ctip"
          id="gvCtip"
          role="tooltip"
          style={{ left: Math.round(tip.left), top: Math.round(tip.top) }}
        >
          {tipBody(tip.c)}
        </div>
      ) : null}
      {toastNode}
    </div>
  );
}
