'use client';

import Link from 'next/link';
import { Fragment, useEffect, useState } from 'react';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { listRecordTags } from '@/features/objects/tags';
import { listHighLabelUsage, type HighLabelUsage } from '../api.client';
import { LIMIT_HEADS, LIMIT_PAGES, labelPairUsed, pickDmTab, type LimitPage } from '../limits';
import {
  byText,
  canHavePipelines,
  canHaveTags,
  canLink,
  customPropertyRows,
  fmt,
  labelsBetween,
  labelsSeenBy,
  livePipelines,
  type DmObject,
} from '../model';
import { useDm } from './DataModelView';
import { DmIcon } from './icons';
import { CustomObjectDefinition, LimitBar } from './LimitBar';
import { CheckFilter, DataTable, SearchBox, SelectMenu, Tip } from './primitives';

type Status = 'activated' | 'deactivated';

/** Objects with a "Merge duplicates" page. */
const MERGE_PAGES: Record<string, string> = {
  contact: '/contacts/duplicates',
  company: '/companies/duplicates',
};

function StatusFilter({ value, onChange }: { value: Status[]; onChange: (v: Status[]) => void }) {
  return (
    <CheckFilter
      label={value.length ? `(${value.length}) Object status` : 'Object status'}
      options={[
        { value: 'activated', label: 'Activated objects' },
        { value: 'deactivated', label: 'Deactivated objects' },
      ]}
      selected={value}
      onChange={(v) => onChange(v as Status[])}
      clear
      chip
    />
  );
}
const statusOk = (s: Status[], o: DmObject | undefined) =>
  !o || !s.length || s.length === 2 || (s[0] === 'activated') === o.active;

function Head({
  title,
  desc,
  tip,
  right,
}: {
  title: string;
  desc: React.ReactNode;
  tip?: string;
  right?: React.ReactNode;
}) {
  return (
    <div className="dm-lhead">
      <div>
        <h2>
          {title} {tip && <Tip text={tip} />}
        </h2>
        <p>{desc}</p>
      </div>
      {right}
    </div>
  );
}

/**
 * Limits (the prototype's Limits tab): how many records and definitions each object has, each
 * against its limit as the design's bar(used, max) (HUB-717). The limits come from GET
 * /data-model, which enforces the definition ones; without them (an older API, or they failed to
 * load) the pages show plain counts, as no limit is then known.
 */
export function UsageTab() {
  const { model, params, href, canOpenSettings } = useDm();
  const page: LimitPage = pickDmTab(params).limit;
  // HUB-717: the design's "X of Y" bars, only with the limits the API enforces.
  const lim = model.limits ?? null;
  const [status, setStatus] = useState<Status[]>(['activated']);
  const [q, setQ] = useState('');
  const [objFilter, setObjFilter] = useState('');
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const [propStatus, setPropStatus] = useState<Status[]>([]);
  // Pipelines and Tags list deactivated objects too until filtered, as in the design.
  const [pipeStatus, setPipeStatus] = useState<Status[]>([]);
  const propsPage = page === 'custom-properties' || page === 'calculated-properties';
  const [propsOpen, setPropsOpen] = useState(propsPage);

  const settingsHref = (key: string, tab?: string) =>
    `/settings/objects?object=${encodeURIComponent(key)}${tab ? `&tab=${tab}` : ''}`;
  const nameCell = (name: React.ReactNode, links: Array<[string, string]>, badge?: string) => (
    <span className="dm-ltable__name">
      <span>
        {name}
        {badge && (
          <>
            {' '}
            <span className="dm-badge">{badge}</span>
          </>
        )}
      </span>
      <span className="dm-row-links">
        {/* Settings links that would bounce this user (their page gate) aren't shown (batch P1). */}
        {links
          .filter(([, target]) => canOpenSettings(target))
          .map(([label, target]) => (
            <Link key={label} href={target}>
              {label}
            </Link>
          ))}
      </span>
    </span>
  );
  const offBadge = (o: DmObject) => (o.active ? undefined : 'Deactivated');

  let main: React.ReactNode;
  if (page === 'objects') {
    // The design's blocks: Contacts, CRM-defined objects, custom objects and app objects.
    const contact = model.objects.find((o) => o.key === 'contact');
    const defined = model.objects.filter(
      (o) =>
        o.group !== 'Custom objects' && !o.activity && o.key !== 'contact' && statusOk(status, o),
    );
    const custom = model.objects.filter((o) => o.group === 'Custom objects' && o.active);
    const customTotal = custom.reduce((n, o) => n + (o.records ?? 0), 0);
    const links = (o: DmObject): Array<[string, string]> => [
      ...(MERGE_PAGES[o.key]
        ? ([['Merge duplicates', MERGE_PAGES[o.key]!]] as Array<[string, string]>)
        : []),
      ...(o.active && o.page ? ([['View all records', o.page]] as Array<[string, string]>) : []),
    ];
    const recordsCol = {
      key: 'records',
      label: 'Number of records',
      sort: true,
      val: (o: DmObject) => o.records ?? -1,
      render: (o: DmObject) =>
        o.records === null ? <span className="dm-muted">--</span> : fmt(o.records),
    };
    // HUB-717: one object's records against its limit, as the design's bar(r.n, r.max) (js:3336).
    const recordsBarCol = lim
      ? {
          ...recordsCol,
          render: (o: DmObject) =>
            o.records === null ? (
              <span className="dm-muted">--</span>
            ) : (
              <LimitBar used={o.records} max={lim.records.perObject} />
            ),
        }
      : recordsCol;
    main = (
      <>
        <Head
          title="Objects"
          desc={
            lim
              ? 'Number of actual records for various object types that your organization can store in CRM.'
              : 'Number of actual records for various object types that your organization stores in CRM.'
          }
        />
        {contact && (
          <>
            <h3 className="dm-lh3">
              {contact.name}{' '}
              <Tip
                text={
                  lim
                    ? `Every ${contact.singular.toLowerCase()} record counts toward this limit.`
                    : `Every ${contact.singular.toLowerCase()} record counts here.`
                }
              />
            </h3>
            <p className="dm-lp">
              {lim
                ? `You have a maximum of total number of ${contact.singular} records.`
                : `The total number of ${contact.singular} records.`}
            </p>
            <DataTable
              rows={[contact]}
              rowKey={(o) => o.key}
              tableCls="dm-ltable"
              pager={false}
              cols={[
                {
                  key: 'name',
                  label: 'Object',
                  width: '45%',
                  render: (o) => nameCell(o.singular, links(o)),
                },
                recordsBarCol,
              ]}
            />
          </>
        )}
        <h3 className="dm-lh3">
          CRM Defined Objects{' '}
          <Tip
            text={
              lim
                ? 'Each kind of object has its own record limit.'
                : 'Each kind of object counts its own records.'
            }
          />
        </h3>
        <p className="dm-lp">
          {lim
            ? 'You have a maximum total number of records for each kind of object.'
            : 'The total number of records for each kind of object.'}
        </p>
        <div className="dm-chipbar">
          <StatusFilter value={status} onChange={setStatus} />
        </div>
        <DataTable
          rows={defined}
          rowKey={(o) => o.key}
          sortKey={null}
          tableCls="dm-ltable"
          pager={false}
          cols={[
            {
              key: 'name',
              label: 'Object',
              width: '45%',
              render: (o) => nameCell(o.singular, links(o), offBadge(o)),
            },
            recordsBarCol,
          ]}
        />
        <h3 className="dm-lh3">Custom objects</h3>
        <p className="dm-lp">
          {lim
            ? 'You have a maximum total number of records across all your custom objects.'
            : 'The total number of records across all your custom objects.'}
        </p>
        {lim ? (
          <LimitBar used={customTotal} max={lim.records.customObjects} wide />
        ) : (
          <div className="dm-defcard dm-defcard--plain">
            <div className="dm-usage__top">
              <span>All custom objects</span>
              <b>{fmt(customTotal)} records</b>
            </div>
          </div>
        )}
        <DataTable
          rows={custom}
          rowKey={(o) => o.key}
          tableCls="dm-ltable"
          empty="No custom objects yet."
          cols={[
            {
              key: 'name',
              label: 'Object',
              width: '45%',
              render: (o) => nameCell(o.singular, links(o)),
            },
            recordsCol,
          ]}
        />
        <h3 className="dm-lh3">App objects</h3>
        <p className="dm-lp">
          {lim
            ? 'You have a maximum total number of records across all your app objects.'
            : 'The total number of records across all your app objects.'}
        </p>
        {/* This CRM has no app objects, so none of their records count. */}
        {lim && <LimitBar used={0} max={lim.records.appObjects} wide />}
        <div className="dm-empty dm-empty--sm">
          <p>There are no app object records to show.</p>
        </div>
      </>
    );
  } else if (page === 'associations') {
    main = <AssociationUsage />;
  } else if (propsPage) {
    const calc = page === 'calculated-properties';
    // #243: the same rows the Intro's custom properties total adds up.
    const rows = customPropertyRows(model, calc).filter(
      ({ o }) =>
        statusOk(propStatus, o) &&
        (!objFilter || o.key === objFilter) &&
        (!q || o.name.toLowerCase().includes(q.toLowerCase())),
    );
    const total = rows.reduce((n, r) => n + r.n, 0);
    // HUB-717: the business-wide limit (js:3389) and, for custom properties, each object's (:3405).
    const totalLimit = lim && (calc ? lim.calculatedProperties : lim.customProperties);
    const objectUsed = (key: string) => lim?.customProperties.byObject[key] ?? 0;
    main = (
      <>
        <Head
          title={calc ? 'Calculated properties' : 'Custom properties'}
          desc={
            calc ? (
              <>
                Calculated properties include rollup, calculation, and sync types. They let you
                create properties that auto-calculate values based on your CRM data.
                {canOpenSettings('/settings/properties') ? (
                  <>
                    {' '}
                    <Link className="dm-link-strong" href="/settings/properties">
                      Learn more
                    </Link>
                  </>
                ) : null}
              </>
            ) : (
              'Properties created by your organization to store unique data for your business.'
            )
          }
          tip={
            lim
              ? calc
                ? 'Rollup, calculation and sync properties count toward this limit.'
                : 'Custom properties count toward both the account limit and the per-object limit.'
              : calc
                ? 'Rollup, calculation and CRM-calculated properties.'
                : 'Archived properties keep their values and can be restored in Property settings.'
          }
        />
        {totalLimit ? (
          <div className="dm-defcard dm-defcard--plain">
            <LimitBar used={totalLimit.used} max={totalLimit.max} wide />
            <p className="dm-lp">
              {calc
                ? 'You have a maximum number of calculated properties across all objects.'
                : 'You have a total maximum number of custom properties that can be created in the UI across all objects. Separately, per object, there is also a maximum number of custom properties that can be created either via UI or API.'}
            </p>
          </div>
        ) : (
          <div className="dm-defcard dm-defcard--plain">
            <div className="dm-usage__top">
              <span>Across {rows.length} objects</span>
              <b>
                {fmt(total)} {calc ? 'calculated ' : ''}properties
              </b>
            </div>
          </div>
        )}
        <div className="dm-chipbar dm-chipbar--tight">
          <SearchBox value={q} onChange={setQ} placeholder="Search" className="dm-search--sm" />
          <span className="dm-muted">Filter by</span>
          <StatusFilter value={propStatus} onChange={setPropStatus} />
          <SelectMenu
            className="dm-select--inline"
            value={objFilter}
            options={[
              { value: '', label: 'All objects' },
              ...model.objects
                .filter((o) => o.active && !o.catalog)
                .sort((a, b) => byText(a.name, b.name))
                .map((o) => ({ value: o.key, label: o.name })),
            ]}
            onChange={setObjFilter}
            search
            ariaLabel="Object"
          />
        </div>
        <DataTable
          rows={rows}
          rowKey={(r) => r.key}
          sortKey="n"
          sortDir={-1}
          tableCls="dm-ltable"
          empty="No objects match your filters."
          cols={[
            {
              key: 'name',
              label: 'Object',
              sort: true,
              width: '45%',
              render: (r) =>
                nameCell(r.name, [
                  [
                    `View all ${calc ? 'calculated' : 'custom'} properties`,
                    href({ tab: 'manage', object: r.key, sub: 'properties' }),
                  ],
                ]),
            },
            lim && !calc
              ? {
                  key: 'n',
                  label: 'Custom properties/limits',
                  sort: true,
                  val: (r) => objectUsed(r.key),
                  render: (r) => (
                    <LimitBar used={objectUsed(r.key)} max={lim.customProperties.perObjectMax} />
                  ),
                }
              : {
                  key: 'n',
                  label: calc ? 'Number of Calculated properties' : 'Custom properties',
                  sort: true,
                },
          ]}
        />
      </>
    );
  } else if (page === 'association-labels') {
    // One row per direction: "Contacts-to-Companies" lists the labels as contacts read them.
    const directions: Array<{ key: string; a: DmObject; b: DmObject; labels: string[] }> = [];
    const objects = model.objects.filter((o) => !o.catalog);
    for (const a of objects) {
      for (const b of objects) {
        if (!canLink(a, b)) continue;
        const between = labelsBetween(model, a.key, b.key);
        if (!between.length) continue;
        const seen = labelsSeenBy(between, a.key).map((l) => l.text);
        directions.push({
          key: `${a.key}:${b.key}`,
          a,
          b,
          labels: [...new Set(seen)].sort(byText),
        });
      }
    }
    const fromOptions = [...new Map(directions.map((d) => [d.a.key, d.a])).values()].sort((x, y) =>
      byText(x.name, y.name),
    );
    const toOptions = [
      ...new Map(directions.filter((d) => d.a.key === from).map((d) => [d.b.key, d.b])).values(),
    ].sort((x, y) => byText(x.name, y.name));
    const rows = directions
      .filter(
        (d) =>
          (!from || d.a.key === from) &&
          (!to || d.b.key === to) &&
          statusOk(status, d.a) &&
          statusOk(status, d.b),
      )
      .map((d) => ({ ...d, name: `${d.a.name}-to-${d.b.name}`, n: d.labels.length }));
    main = (
      <>
        <Head
          title="Association Labels"
          desc="Label associations to specify the relationship between associated objects."
          tip={
            lim
              ? `Each pair of objects can have up to ${fmt(lim.labels.perPairMax)} custom association labels.`
              : undefined
          }
        />
        <div className="dm-chipbar">
          <span className="dm-muted">Filter by:</span>
          <StatusFilter value={status} onChange={setStatus} />
          <span className="dm-pair">
            <span className="dm-muted">From object:</span>
            <SelectMenu
              className="dm-select--inline"
              value={from}
              options={[
                { value: '', label: 'All' },
                ...fromOptions.map((o) => ({ value: o.key, label: o.name })),
              ]}
              onChange={(v) => {
                setFrom(v);
                setTo('');
              }}
              ariaLabel="From object"
            />
          </span>
          <span className="dm-pair" title={from ? undefined : 'Choose a From object first'}>
            <span className="dm-muted">To object:</span>
            <SelectMenu
              className="dm-select--inline"
              value={to}
              options={[
                { value: '', label: 'All' },
                ...toOptions.map((o) => ({ value: o.key, label: o.name })),
              ]}
              onChange={setTo}
              ariaLabel="To object"
              disabled={!from}
            />
          </span>
          <Tip text="Choose a From object to filter the To object list." />
        </div>
        <DataTable
          rows={rows}
          rowKey={(r) => r.key}
          sortKey="n"
          sortDir={-1}
          tableCls="dm-ltable dm-ltable--labels"
          empty={
            model.labels.length ? 'No labels match your filters.' : 'No association labels yet.'
          }
          cols={[
            {
              key: 'name',
              label: 'Object Association',
              sort: true,
              width: '30%',
              render: (r) =>
                nameCell(
                  <span className="dm-ellipsis" title={r.name}>
                    {r.name}
                  </span>,
                  r.a.active
                    ? [
                        [
                          'Go to settings',
                          href({
                            tab: 'manage',
                            object: r.a.key,
                            sub: 'associations',
                            view: 'table',
                          }),
                        ],
                      ]
                    : [],
                ),
            },
            {
              key: 'labels',
              label: 'Association labels',
              cls: 'dm-th-caps',
              render: (r) => {
                const objectKey = r.a.active ? r.a.key : r.b.key;
                const other = objectKey === r.a.key ? r.b.key : r.a.key;
                return (
                  <Link
                    className="dm-chiprow"
                    href={href({
                      tab: 'manage',
                      object: objectKey,
                      sub: 'associations',
                      view: 'table',
                      to: other,
                    })}
                    aria-label={`View all ${r.n} labels for ${r.name}`}
                  >
                    {r.labels.map((l) => (
                      <span key={l} className="dm-chip">
                        {l}
                      </span>
                    ))}
                  </Link>
                );
              },
            },
            // HUB-717: the pair's custom labels against its limit (js:3458).
            lim
              ? {
                  key: 'n',
                  label: 'Number of Labels/Limit',
                  sort: true,
                  width: '24%',
                  val: (r) => labelPairUsed(lim, r.a.key, r.b.key),
                  render: (r) => (
                    <LimitBar
                      used={labelPairUsed(lim, r.a.key, r.b.key)}
                      max={lim.labels.perPairMax}
                    />
                  ),
                }
              : { key: 'n', label: 'Number of labels', sort: true, width: '180px' },
          ]}
        />
      </>
    );
  } else if (page === 'pipelines') {
    const rows = model.objects
      .filter((o) => canHavePipelines(o) && statusOk(pipeStatus, o))
      .map((o) => ({
        o,
        key: o.key,
        name: o.name,
        // The CRM's default pipelines aren't counted, as in the design.
        n: livePipelines(model, o.key).filter((p) => !p.crmProvided).length,
      }));
    main = (
      <>
        <Head
          title="Pipelines"
          desc={
            lim
              ? 'You have a maximum total number of pipelines across all objects. This limit does not include CRM-provided pipelines.'
              : "Pipelines your organization created for each object. CRM-provided pipelines aren't counted."
          }
        />
        {lim && (
          <div className="dm-defcard">
            <LimitBar used={lim.pipelines.used} max={lim.pipelines.max} wide />
          </div>
        )}
        <div className="dm-chipbar">
          <StatusFilter value={pipeStatus} onChange={setPipeStatus} />
        </div>
        <DataTable
          rows={rows}
          rowKey={(r) => r.key}
          tableCls="dm-ltable"
          size={20}
          sortKey="name"
          cols={[
            {
              key: 'name',
              label: 'Object',
              sort: true,
              width: '40%',
              render: (r) =>
                nameCell(
                  r.name,
                  r.o.active && r.o.hasPipeline
                    ? [['View pipeline settings', settingsHref(r.key, 'pipelines')]]
                    : [],
                  offBadge(r.o),
                ),
            },
            { key: 'n', label: 'Custom Pipelines', sort: true },
          ]}
        />
      </>
    );
  } else if (page === 'tags') {
    main = (
      <TagUsage
        status={pipeStatus}
        onStatus={setPipeStatus}
        nameCell={nameCell}
        offBadge={offBadge}
      />
    );
  } else {
    // Every custom object, the deactivated ones marked (they don't count as active); only live
    // ones have settings.
    const custom = model.objects.filter((o) => o.group === 'Custom objects');
    main = (
      <>
        <Head
          title="Custom objects"
          desc="Objects created by your organization to map your business needs."
        />
        <CustomObjectDefinition model={model} />
        <DataTable
          rows={custom}
          rowKey={(o) => o.key}
          tableCls="dm-ltable"
          pager={false}
          sortKey="name"
          empty="No custom objects yet."
          cols={[
            {
              key: 'name',
              label: 'Custom object',
              sort: true,
              render: (o) =>
                nameCell(
                  o.name,
                  o.active ? [['Go to settings', settingsHref(o.key)]] : [],
                  offBadge(o),
                ),
            },
          ]}
        />
      </>
    );
  }

  const link = (k: LimitPage, label: string, child = false) => (
    <Link
      key={k}
      className={cn('dm-lnav__link', child && 'dm-lnav__link--child', k === page && 'is-active')}
      href={href({ tab: 'limits', limit: k })}
      aria-current={k === page ? 'page' : undefined}
    >
      {label}
    </Link>
  );
  return (
    <div className="dm-limits">
      <aside className="dm-lnav">
        {/* Headings stay siblings: only the first one drops its top margin (.dm-lnav__head). */}
        {LIMIT_HEADS.map(([g, tip, limitTip]) => (
          <Fragment key={g}>
            <p className="dm-lnav__head">
              {g} <Tip text={lim ? limitTip : tip} />
            </p>
            {g === 'Record Limits' ? (
              LIMIT_PAGES.filter(([, , pg]) => pg === g).map(([k, label]) => link(k, label))
            ) : (
              <>
                <button
                  type="button"
                  className={cn('dm-lnav__link dm-lnav__toggle', propsOpen && 'is-open')}
                  aria-expanded={propsOpen}
                  onClick={() => setPropsOpen((v) => !v)}
                >
                  Properties
                  <DmIcon name="chevron-down" size={16} />
                </button>
                {propsOpen &&
                  LIMIT_PAGES.filter(([, , pg]) => pg === 'Properties').map(([k, label]) =>
                    link(k, label, true),
                  )}
                {LIMIT_PAGES.filter(([, , pg]) => pg === g).map(([k, label]) => link(k, label))}
              </>
            )}
          </Fragment>
        ))}
      </aside>
      <div className="dm-lmain">{main}</div>
    </div>
  );
}

/**
 * Limits > Associations: up to 200 records of one object using at least 80% of an association
 * label's per-record limit towards another object (GET /association-labels/high-usage).
 */
function AssociationUsage() {
  const { model } = useDm();
  const [status, setStatus] = useState<Status[]>(['activated']);
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const [rows, setRows] = useState<HighLabelUsage[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  const options = model.objects
    .filter((o) => !o.catalog && !o.activity && statusOk(status, o))
    .sort((a, b) => byText(a.name, b.name))
    .map((o) => ({ value: o.key, label: o.name }));
  const fromObject = model.objects.find((o) => o.key === from);
  const toObject = model.objects.find((o) => o.key === to);

  useEffect(() => {
    setRows(null);
    setError(null);
    if (!from || !to) return;
    let alive = true;
    listHighLabelUsage(from, to).then(
      (data) => alive && setRows(data),
      (err: unknown) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [from, to]);

  const restEmpty = (
    <div className="dm-empty">
      <span className="dm-empty__badge">
        <DmIcon name="check-big" size={40} />
      </span>
      <p className="dm-empty__title">
        You don&apos;t have any association at or above 80% usage limits.
      </p>
      <p>Sit and rest.</p>
    </div>
  );
  const canPair = fromObject && toObject && canLink(fromObject, toObject);

  return (
    <>
      <Head
        title="Associations"
        tip="A record can have a label on only a limited number of linked records when the label has a limit."
        desc={
          <>
            Association limits come from the per-record limits of your association labels.
            <br />
            <br />
            Choose the object association to see a maximum of 200 records that used more than 80% of
            a label&apos;s limit.
          </>
        }
        right={
          <span title="Report emails aren't available yet">
            <button type="button" className="dm-btn dm-btn--outline dm-btn--sm" disabled>
              <DmIcon name="cloud" size={14} />
              Request high usage report email
            </button>
          </span>
        }
      />
      <div className="dm-assocpick">
        <StatusFilter value={status} onChange={setStatus} />
        <SelectMenu
          className="dm-select--inline"
          value={from}
          options={options}
          onChange={setFrom}
          placeholder="Choose a primary object"
          search
          ariaLabel="Primary object"
        />
        <span className="dm-muted">to</span>
        <SelectMenu
          className="dm-select--inline"
          value={to}
          options={options}
          onChange={setTo}
          placeholder="Choose an associated object"
          search
          ariaLabel="Associated object"
        />
      </div>
      {error ? (
        <p className="dm-muted">{error}</p>
      ) : from && to && !canPair ? (
        <p className="dm-muted">
          {fromObject?.name} can&apos;t be associated with {toObject?.name}.
        </p>
      ) : rows && rows.length > 0 ? (
        <DataTable
          rows={rows}
          rowKey={(r) => `${r.recordId}:${r.labelId}`}
          sortKey="pct"
          sortDir={-1}
          tableCls="dm-ltable"
          cols={[
            {
              key: 'record',
              label: fromObject?.singular ?? 'Record',
              sort: true,
              val: (r) => r.recordName ?? '',
              render: (r) => r.recordName ?? <span className="dm-muted">(no name)</span>,
            },
            {
              key: 'label',
              label: 'Association label',
              sort: true,
              val: (r) => r.labelName,
              render: (r) => r.labelName,
            },
            {
              key: 'pct',
              label: 'Usage',
              sort: true,
              val: (r) => r.used / r.limit,
              render: (r) =>
                `${fmt(r.used)} of ${fmt(r.limit)} (${Math.round((r.used / r.limit) * 100)}%)`,
            },
          ]}
        />
      ) : from && to && rows === null ? (
        <p className="dm-muted">Loading…</p>
      ) : (
        restEmpty
      )}
    </>
  );
}

/** Limits > Tags: live record tags per object with a pipeline (GET /record-tags). */
function TagUsage({
  status,
  onStatus,
  nameCell,
  offBadge,
}: {
  status: Status[];
  onStatus: (v: Status[]) => void;
  nameCell: (
    name: React.ReactNode,
    links: Array<[string, string]>,
    badge?: string,
  ) => React.ReactNode;
  offBadge: (o: DmObject) => string | undefined;
}) {
  const { model } = useDm();
  const [counts, setCounts] = useState<Record<string, number> | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let alive = true;
    listRecordTags().then(
      (tags) => {
        if (!alive) return;
        const next: Record<string, number> = {};
        for (const t of tags) next[t.objectType] = (next[t.objectType] ?? 0) + 1;
        setCounts(next);
      },
      (err: unknown) => alive && setError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, []);

  const rows = model.objects
    .filter((o) => canHaveTags(o) && statusOk(status, o))
    .map((o) => ({ o, key: o.key, name: o.name, n: counts?.[o.key] ?? 0 }));
  const total = Object.values(counts ?? {}).reduce((n, c) => n + c, 0);
  // HUB-717: all live tags against the limit the API enforces (js:3474).
  const lim = model.limits ?? null;

  return (
    <>
      <Head
        title="Tags"
        desc={
          lim
            ? 'You have a maximum number of tags across all objects.'
            : 'Tags used on the records of each object that supports them.'
        }
        tip="Tags highlight records that meet your conditions on boards and records."
      />
      {lim ? (
        <div className="dm-defcard">
          <LimitBar used={lim.tags.used} max={lim.tags.max} wide />
        </div>
      ) : (
        <div className="dm-defcard dm-defcard--plain">
          <div className="dm-usage__top">
            <span>All objects</span>
            <b>{counts ? `${fmt(total)} tags` : '…'}</b>
          </div>
        </div>
      )}
      <div className="dm-chipbar">
        <StatusFilter value={status} onChange={onStatus} />
      </div>
      {error && <p className="dm-muted">{error}</p>}
      <DataTable
        rows={rows}
        rowKey={(r) => r.key}
        tableCls="dm-ltable"
        size={20}
        sortKey="name"
        cols={[
          {
            key: 'name',
            label: 'Object',
            sort: true,
            width: '50%',
            render: (r) => nameCell(r.name, [], offBadge(r.o)),
          },
          {
            key: 'n',
            label: 'Tags used',
            sort: true,
            render: (r) => (counts ? fmt(r.n) : <span className="dm-muted">--</span>),
          },
        ]}
      />
    </>
  );
}
