'use client';

/**
 * The goals table (`.gl-t`) of the Goals overview / Team performance / User performance tabs and
 * of a goal page's performance tabs (goals.js `columns()` / `renderMain()`), with its filter
 * buttons (`.gl-fb`), menus, selection bar and pager.
 */
import {
  DASH,
  MON,
  initials,
  monthPct,
  nf,
  pageList,
  quarterPct,
  rangeLabel,
  statusOf,
  val,
  weeks,
  type Row,
  type Tab,
} from '../model';
import { cn } from '@/lib/utils/cn';
import { Caret, CopyIcon, SearchIcon, SortIcon, TrashIcon } from './parts';

export type Breakdown = 'total' | 'quarter' | 'month' | 'weekly';
export interface SortState {
  k: string;
  d: 1 | -1;
}

export interface Col {
  id: string;
  l: string;
  s?: boolean;
  cls?: string;
  c: (r: Row) => React.ReactNode;
}

export const PER = [10, 25, 50, 100];

function Bar({ pct, bot }: { pct: number; bot?: React.ReactNode }) {
  const w = Math.max(0, Math.min(100, pct));
  return (
    <div className="gl-pr">
      <div className="gl-pr__t">
        <span
          className="gl-track"
          role="progressbar"
          aria-valuemin={0}
          aria-valuemax={100}
          aria-valuenow={Math.round(w)}
          aria-label="Progress"
        >
          <span
            className={'gl-fill' + (pct < 30 ? ' is-low' : '')}
            style={{ width: w.toFixed(1) + '%' }}
          />
        </span>
        <span className="gl-pct">{nf(Math.round(pct))}%</span>
      </div>
      {bot}
    </div>
  );
}

export function Users4({ names }: { names: string[] }) {
  if (!names.length) return <span className="gl-dash">{DASH}</span>;
  return (
    <div className="gl-us">
      {names.slice(0, 4).map((n, i) => (
        <span key={n + i} className="gl-av" title={n} role="img" aria-label={n}>
          {initials(n)}
        </span>
      ))}
      {names.length > 4 ? <span className="gl-more">+{names.length - 4}</span> : null}
    </div>
  );
}

export interface ColumnOptions {
  tab: Tab;
  /** On a goal page (one goal): no goal name / template columns. */
  det: boolean;
  cols: { tpl: boolean; teams: boolean; users: boolean; goal: boolean; prog: boolean };
  bd: Breakdown;
  status: boolean;
  year: number;
  today: { year: number; month: number };
  membersOf: (team: string) => string[];
  onOpen: (r: Row) => void;
  onEdit: (r: Row) => void;
  /** Without "Manage targets" there is no Edit button (QA #583). Default: shown. */
  canEdit?: boolean;
  onActions: (r: Row, btn: HTMLButtonElement) => void;
  openMenuKey: string | null;
}

export function columns(o: ColumnOptions): Col[] {
  const yr = ' (' + rangeLabel(o.year) + ')';
  const c: Col[] = [];
  const none = <span className="gl-dash">{DASH}</span>;
  const gl = o.tab === 'goals';
  const det = o.det;
  if (o.tab === 'teams') {
    c.push({
      id: 'team',
      l: 'Primary team',
      s: true,
      cls: 'gl-c2 gl-c2--n' + (det ? ' gl-sep' : ''),
      c: (r) => r.team,
    });
  }
  if (o.tab === 'users') {
    c.push({
      id: 'user',
      l: 'User',
      s: true,
      cls: 'gl-c2 gl-c2--n' + (det ? ' gl-sep' : ''),
      c: (r) => (
        <span className="gl-us">
          <span className="gl-av" aria-hidden="true">
            {initials(r.user)}
          </span>
          {r.user}
        </span>
      ),
    });
  }
  if (!det) {
    c.push({
      id: 'name',
      l: 'Goal Name',
      s: true,
      cls: gl ? 'gl-c2' : 'gl-c3',
      c: (r) => (
        <div className="gl-gnw">
          <div className="gl-gn">
            <button type="button" className="link" onClick={() => o.onOpen(r)}>
              {r.g.name}
            </button>
            {r.g.sub ? <small title={r.g.sub}>{r.g.sub}</small> : null}
          </div>
          <div className={'gl-ra' + (o.openMenuKey === r.key ? ' is-open' : '')}>
            {o.canEdit !== false ? (
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                aria-label={'Edit ' + r.g.name}
                onClick={() => o.onEdit(r)}
              >
                Edit
              </button>
            ) : null}
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              data-gl-ract={r.key}
              aria-haspopup="menu"
              aria-expanded={o.openMenuKey === r.key}
              aria-label={'Actions for ' + r.g.name}
              onClick={(e) => o.onActions(r, e.currentTarget)}
            >
              Actions
              <Caret />
            </button>
          </div>
        </div>
      ),
    });
  }
  if (o.tab === 'users')
    c.push({ id: 'team', l: 'Primary team', s: true, c: (r) => (r.team ? r.team : none) });
  if (o.tab === 'teams') {
    c.push({
      id: 'users',
      l: 'Users',
      c: (r) => <Users4 names={r.g.users.length ? r.g.users : o.membersOf(r.team)} />,
    });
  }
  if (o.cols.tpl && !det) c.push({ id: 'tpl', l: 'Template', s: true, c: (r) => r.tpl });
  if (gl && o.cols.teams)
    c.push({ id: 'teams', l: 'Teams', s: true, c: (r) => (r.teams ? r.teams : none) });
  if (gl && o.cols.users)
    c.push({ id: 'users', l: 'Users', c: (r) => <Users4 names={r.g.users} /> });
  if (o.cols.goal)
    c.push({ id: 'goal', l: 'Total Goal' + yr, s: true, c: (r) => val(r.g, r.goal) });
  if (o.bd === 'total') {
    if (o.cols.prog) {
      c.push({
        id: 'pct',
        l: 'Total Progress' + yr,
        s: true,
        c: (r) => {
          const b = (
            <Bar
              pct={r.pct}
              bot={
                <div className="gl-pr__b">
                  <span>{val(r.g, r.prog)}</span>
                  <span>of {val(r.g, r.goal)}</span>
                </div>
              }
            />
          );
          return det ? (
            b
          ) : (
            <button
              type="button"
              className="gl-barbtn"
              aria-label={'Open ' + r.g.name + ' goal page'}
              onClick={() => o.onOpen(r)}
            >
              {b}
            </button>
          );
        },
      });
    }
  } else if (o.bd === 'month') {
    MON.forEach((m, i) =>
      c.push({
        id: 'm' + i,
        l: m + ' ' + o.year,
        c: (r) => <span className="gl-mpct">{nf(Math.round(monthPct(r, i)))}%</span>,
      }),
    );
  } else if (o.bd === 'weekly') {
    weeks(o.year).forEach((w, k) =>
      c.push({
        id: 'w' + k,
        l: w.label,
        c: (r) => <span className="gl-mpct">{nf(Math.round(monthPct(r, w.month)))}%</span>,
      }),
    );
  } else {
    [0, 1, 2, 3].forEach((q) =>
      c.push({
        id: 'q' + q,
        l: 'Q' + (q + 1) + ' ' + o.year,
        c: (r) => <span className="gl-mpct">{nf(Math.round(quarterPct(r, q)))}%</span>,
      }),
    );
  }
  if (o.status) {
    c.push({
      id: 'status',
      l: 'Status',
      s: true,
      c: (r) => {
        const s = statusOf(r.pct, o.year, o.today);
        return (
          <span className={'gl-st gl-st--' + s.k}>
            <i aria-hidden="true" />
            {s.label}
          </span>
        );
      },
    });
  }
  return c;
}

export function sortRows(rows: Row[], s: SortState): Row[] {
  return rows
    .map((r, i) => ({ r, i }))
    .sort((a, b) => {
      const x = (a.r as unknown as Record<string, unknown>)[s.k];
      const y = (b.r as unknown as Record<string, unknown>)[s.k];
      if (typeof x === 'string' || typeof y === 'string') {
        const c =
          String(x ?? '')
            .toLowerCase()
            .localeCompare(String(y ?? '').toLowerCase()) * s.d;
        return c || a.i - b.i;
      }
      return ((Number(x) || 0) - (Number(y) || 0)) * s.d || a.i - b.i;
    })
    .map((o) => o.r);
}

export function Pagination({
  total,
  page,
  per,
  menuOpen,
  onPage,
  onToggleMenu,
  onPer,
}: {
  total: number;
  page: number;
  per: number;
  menuOpen: boolean;
  onPage: (p: number) => void;
  onToggleMenu: () => void;
  onPer: (n: number) => void;
}) {
  const pages = Math.max(1, Math.ceil(total / per));
  const cur = Math.min(page, pages);
  return (
    <nav className="gl-pg" aria-label="Pagination">
      <button
        type="button"
        className="gl-pg__a"
        disabled={cur <= 1}
        onClick={() => onPage(cur - 1)}
      >
        {'‹ Prev'}
      </button>
      {pageList(pages, cur).map((p, i) =>
        p === '…' ? (
          <span key={'e' + i} className="gl-pg__e">
            {'…'}
          </span>
        ) : (
          <button
            key={p}
            type="button"
            className={'gl-pg__n' + (p === cur ? ' is-on' : '')}
            aria-current={p === cur ? 'page' : undefined}
            onClick={() => onPage(p)}
          >
            {p}
          </button>
        ),
      )}
      <button
        type="button"
        className="gl-pg__a"
        disabled={cur >= pages}
        onClick={() => onPage(cur + 1)}
      >
        {'Next ›'}
      </button>
      <span className="gl-pos">
        <button
          type="button"
          className="gl-pg__sel"
          aria-haspopup="menu"
          aria-expanded={menuOpen}
          onClick={onToggleMenu}
        >
          {per} per page
          <Caret />
        </button>
        {menuOpen ? (
          <div className="gl-menu gl-menu--up" role="menu">
            {PER.map((n) => (
              <button
                key={n}
                type="button"
                role="menuitem"
                className={'gl-mi' + (n === per ? ' is-on' : '')}
                onClick={() => onPer(n)}
              >
                {n} per page
              </button>
            ))}
          </div>
        ) : null}
      </span>
    </nav>
  );
}

/** [value, label, disabled?, icon?, group?] */
export type MenuOpt = [string, string, boolean?, string?, string?];

/** A filter button (`fbtn()`) with its checkbox menu (`menuHtml()`). */
export function FilterButton({
  id,
  label,
  n,
  always,
  extra,
  open,
  onToggle,
  children,
}: {
  id: string;
  label: string;
  n: number;
  always?: boolean;
  extra?: React.ReactNode;
  open: boolean;
  onToggle: (id: string) => void;
  children?: React.ReactNode;
}) {
  return (
    <span className="gl-pos">
      <button
        type="button"
        className={'gl-fb' + (always || n ? ' is-on' : '')}
        data-gl-menu={id}
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => onToggle(id)}
      >
        {extra}
        {label}
        {n ? (
          <span className="gl-n" aria-label={n + ' selected'}>
            {n}
          </span>
        ) : null}
        <Caret />
      </button>
      {open ? children : null}
    </span>
  );
}

export function CheckMenu({
  id,
  opts,
  selected,
  search,
  query,
  onQuery,
  onToggleOpt,
  onClear,
  wide,
}: {
  id: string;
  opts: MenuOpt[];
  selected: (value: string) => boolean;
  search: boolean;
  query: string;
  onQuery: (q: string) => void;
  onToggleOpt: (value: string, on: boolean) => void;
  onClear?: () => void;
  wide?: 'w' | 't';
}) {
  const q = query.toLowerCase();
  const list = opts.filter((x) => !q || x[1].toLowerCase().includes(q));
  let last = '';
  return (
    // DL12 (QA #576): `cn` keeps `.gl-menu` (position, layer, background) beside the width class.
    // The class read `gl-menugl-menu--t` (Prettier's Tailwind plugin trims the space in a string),
    // so the Pipelines and Teams popovers overlapped.
    <div className={cn('gl-menu', wide && `gl-menu--${wide}`)} role="group" aria-label="Filter">
      {search ? (
        <label className="gl-menu__s">
          <span className="gl-sr">Search</span>
          <input
            type="search"
            className="input"
            placeholder="Search"
            value={query}
            data-gl-mq
            autoComplete="off"
            autoFocus
            onChange={(e) => onQuery(e.target.value)}
          />
          <SearchIcon />
        </label>
      ) : null}
      <div className="gl-menu__l" data-gl-ml>
        {list.length ? (
          list.map((x) => {
            const head = x[4] && x[4] !== last ? x[4] : null;
            if (x[4]) last = x[4];
            return (
              <span key={id + x[0]} style={{ display: 'contents' }}>
                {head ? <p className="gl-menu__g">{head}</p> : null}
                <label className={'check' + (x[2] ? ' is-dis' : '')}>
                  <input
                    type="checkbox"
                    checked={selected(x[0])}
                    disabled={Boolean(x[2])}
                    onChange={(e) => onToggleOpt(x[0], e.target.checked)}
                  />
                  <span className="check__box" />
                  <span className="gl-ot" title={x[1]}>
                    {x[3] ? <span aria-hidden="true">{x[3]} </span> : null}
                    {x[1]}
                  </span>
                </label>
              </span>
            );
          })
        ) : (
          <p className="gl-menu__none">No results</p>
        )}
      </div>
      {onClear ? (
        <div className="gl-menu__f">
          <hr />
          <button type="button" className="link" onClick={onClear}>
            Clear selection
          </button>
        </div>
      ) : null}
    </div>
  );
}

export const BREAKDOWNS: Array<[Breakdown, string]> = [
  ['total', 'Total progress breakdown'],
  ['quarter', 'Quarterly breakdown'],
  ['month', 'Monthly breakdown'],
  ['weekly', 'Weekly breakdown'],
];

export function BreakdownMenu({ bd, onPick }: { bd: Breakdown; onPick: (b: Breakdown) => void }) {
  return (
    <div className="gl-menu" role="menu" style={{ minWidth: 280 }}>
      {BREAKDOWNS.map((x) => (
        <button
          key={x[0]}
          type="button"
          role="menuitem"
          className={'gl-mi' + (bd === x[0] ? ' is-on' : '')}
          onClick={() => onPick(x[0])}
        >
          {x[1]}
        </button>
      ))}
    </div>
  );
}

export function YearRange({
  year,
  min,
  max,
  onStep,
}: {
  year: number;
  min: number;
  max: number;
  onStep: (d: number) => void;
}) {
  return (
    <div className="gl-range">
      <button
        type="button"
        aria-label="Previous year"
        disabled={year <= min}
        onClick={() => onStep(-1)}
      >
        {'‹'}
      </button>
      <span aria-live="polite">{rangeLabel(year)}</span>
      <button type="button" aria-label="Next year" disabled={year >= max} onClick={() => onStep(1)}>
        {'›'}
      </button>
    </div>
  );
}

/** The table with its selection bar and pager (`renderMain()`). */
export function GoalsTableView({
  cols,
  rows,
  sort,
  onSort,
  sel,
  onSel,
  page,
  per,
  perMenu,
  onPage,
  onTogglePer,
  onPer,
  onClone,
  onDelete,
  onClearSel,
  caption,
}: {
  cols: Col[];
  rows: Row[];
  sort: SortState;
  onSort: (k: string) => void;
  sel: Record<string, boolean>;
  onSel: (keys: string[], on: boolean) => void;
  page: number;
  per: number;
  perMenu: boolean;
  onPage: (p: number) => void;
  onTogglePer: () => void;
  onPer: (n: number) => void;
  onClone?: () => void;
  onDelete?: () => void;
  onClearSel: () => void;
  caption: string;
}) {
  const mp = Math.max(1, Math.ceil(rows.length / per));
  const cur = Math.min(page, mp);
  const slice = rows.slice((cur - 1) * per, cur * per);
  const nSel = Object.keys(sel).filter((k) => sel[k]).length;
  const allOn = slice.length > 0 && slice.every((r) => sel[r.key]);
  const some = slice.some((r) => sel[r.key]);
  return (
    <>
      {nSel ? (
        <div className="gl-sel">
          <b>{nSel} selected</b>
          {onClone ? (
            <button type="button" className="link gl-sel__a" onClick={onClone}>
              <CopyIcon />
              Clone
            </button>
          ) : null}
          {onDelete ? (
            <button type="button" className="link gl-sel__a" onClick={onDelete}>
              <TrashIcon />
              Delete
            </button>
          ) : null}
          <button
            type="button"
            className="gl-sel__x"
            aria-label="Clear selection"
            onClick={onClearSel}
          >
            {'×'}
          </button>
        </div>
      ) : null}
      <div className="gl-tw" tabIndex={0} aria-label="Goals table">
        <table className="gl-t">
          <caption className="gl-sr">{caption}</caption>
          <thead>
            <tr>
              <th scope="col" className="gl-c1">
                <label className="check">
                  <input
                    type="checkbox"
                    checked={allOn}
                    ref={(el) => {
                      if (el) el.indeterminate = nSel > 0 && !allOn && some;
                    }}
                    onChange={(e) =>
                      onSel(
                        slice.map((r) => r.key),
                        e.target.checked,
                      )
                    }
                  />
                  <span className="check__box" />
                  <span className="gl-sr">Select all on this page</span>
                </label>
              </th>
              {cols.map((c) => {
                const on = sort.k === c.id;
                return (
                  <th
                    key={c.id}
                    scope="col"
                    className={c.cls || undefined}
                    aria-sort={
                      c.s ? (on ? (sort.d > 0 ? 'ascending' : 'descending') : 'none') : undefined
                    }
                  >
                    {c.s ? (
                      <button type="button" onClick={() => onSort(c.id)}>
                        {c.l}
                        {on ? <SortIcon up={sort.d > 0} /> : null}
                      </button>
                    ) : (
                      c.l
                    )}
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody>
            {slice.map((r) => (
              <tr key={r.key}>
                <td className="gl-c1">
                  <label className="check">
                    <input
                      type="checkbox"
                      checked={Boolean(sel[r.key])}
                      onChange={(e) => onSel([r.key], e.target.checked)}
                    />
                    <span className="check__box" />
                    <span className="gl-sr">Select {r.name}</span>
                  </label>
                </td>
                {cols.map((c, i) =>
                  i === 0 ? (
                    <th key={c.id} scope="row" className={c.cls || undefined}>
                      {c.c(r)}
                    </th>
                  ) : (
                    <td key={c.id} className={c.cls || undefined}>
                      {c.c(r)}
                    </td>
                  ),
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <Pagination
        total={rows.length}
        page={cur}
        per={per}
        menuOpen={perMenu}
        onPage={onPage}
        onToggleMenu={onTogglePer}
        onPer={onPer}
      />
    </>
  );
}
