'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import {
  listWorkflowIssues,
  listWorkflows,
  reviewWorkflowIssues,
} from '@/features/workflows/api.client';
import type {
  WorkflowIssue,
  WorkflowIssuePriority,
  WorkflowSummary,
} from '@/features/workflows/types';
import { issueGroupKey } from '@/features/workflows/useWorkflowStats';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { NoWorkflowAccess, OBJECT_LABELS, actionLabel, useWorkflowAccess } from './shared';

/**
 * Review automation issues (HUB-299, design workflow-issues.php). The API (HUB-297) lists one
 * issue per workflow, step and cause; this page groups them by action and cause, as the design
 * does: an issue "needs review" while any workflow it affected does, and moves to "Already
 * reviewed" once every one of them is marked reviewed.
 */

const PRIORITY_ORDER: Record<WorkflowIssuePriority, number> = { high: 0, medium: 1, low: 2 };
const PRIORITY_LABEL: Record<WorkflowIssuePriority, string> = {
  high: 'High',
  medium: 'Medium',
  low: 'Low',
};
const PAGE_SIZES = [10, 25, 50];
/** Every issue here comes from the workflows tool (the design's other tools don't exist yet). */
const SOURCE = 'Workflows tool';

interface Automation extends WorkflowIssue {
  /** Marked reviewed (and nothing happened since). */
  reviewed: boolean;
}

interface IssueGroup {
  key: string;
  title: string;
  message: string;
  kind: WorkflowIssue['kind'];
  actionType: string | null;
  automations: Automation[];
  needsReview: boolean;
  priority: WorkflowIssuePriority;
  last: Automation | null;
}

function groupTitle(issue: WorkflowIssue): string {
  if (issue.actionType) return actionLabel(issue.actionType);
  return issue.kind === 'config' ? 'Workflow setup' : 'Workflow step';
}

function explanation(group: IssueGroup): string {
  return group.kind === 'config'
    ? 'The workflow is on but uses something that was deleted, changed or disconnected. Open it, fix the action and publish it again.'
    : 'Records failed at this action. Fix the cause, then retry or skip the failed records in the workflow’s errors.';
}

function toGroups(fresh: WorkflowIssue[], reviewed: WorkflowIssue[]): IssueGroup[] {
  const byKey = new Map<string, IssueGroup>();
  const add = (issue: WorkflowIssue, isReviewed: boolean) => {
    const key = issueGroupKey(issue);
    let g = byKey.get(key);
    if (!g) {
      g = {
        key,
        title: groupTitle(issue),
        message: issue.message,
        kind: issue.kind,
        actionType: issue.actionType,
        automations: [],
        needsReview: false,
        priority: 'low',
        last: null,
      };
      byKey.set(key, g);
    }
    g.automations.push({ ...issue, reviewed: isReviewed });
  };
  fresh.forEach((i) => add(i, false));
  reviewed.forEach((i) => add(i, true));
  for (const g of byKey.values()) {
    g.needsReview = g.automations.some((a) => !a.reviewed);
    g.priority = g.automations.reduce<WorkflowIssuePriority>(
      (p, a) => (PRIORITY_ORDER[a.priority] < PRIORITY_ORDER[p] ? a.priority : p),
      'low',
    );
    g.last =
      [...g.automations].sort((a, b) => (b.lastAt ?? '').localeCompare(a.lastAt ?? ''))[0] ?? null;
  }
  return [...byKey.values()];
}

function formatWhenLong(iso: string | null, timeZone: string): string {
  if (!iso) return 'Found now';
  try {
    return new Date(iso).toLocaleString('en-US', {
      timeZone,
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
      second: '2-digit',
    });
  } catch {
    return iso;
  }
}

function PriorityTag({ priority }: { priority: WorkflowIssuePriority }) {
  return (
    <span className={cn('wfi-priority', `is-${priority}`)}>
      <span className="wfi-ring" aria-hidden />
      {PRIORITY_LABEL[priority]}
    </span>
  );
}

function Chevron({ open }: { open?: boolean }) {
  return (
    <svg
      viewBox="0 0 24 24"
      width="14"
      height="14"
      aria-hidden
      style={{ transform: open ? 'rotate(180deg)' : undefined }}
    >
      <path d="m6 9 6 6 6-6" fill="none" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}

/** A dropdown that closes on an outside click. */
function useDropdown() {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!open) return;
    const close = (e: MouseEvent) => {
      if (!ref.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);
  return { open, setOpen, ref };
}

function HowTo({ title, items }: { title: string; items: React.ReactNode[] }) {
  const [open, setOpen] = useState(true);
  return (
    <div className="wfi-howto">
      <button
        type="button"
        className="wfi-howto__toggle"
        aria-expanded={open}
        onClick={() => setOpen(!open)}
      >
        <span style={{ transform: open ? undefined : 'rotate(-90deg)', display: 'inline-flex' }}>
          <Chevron />
        </span>
        {title}
      </button>
      {open ? (
        <ul>
          {items.map((it, i) => (
            <li key={i}>{it}</li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}

function Empty({ title, text }: { title: string; text: string }) {
  return (
    <div className="wfi-empty">
      <svg viewBox="0 0 24 24" width="28" height="28" aria-hidden>
        <circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" strokeWidth="1.6" />
        <path d="m8 12 3 3 5-6" fill="none" stroke="currentColor" strokeWidth="1.6" />
      </svg>
      <strong>{title}</strong>
      <span>{text}</span>
    </div>
  );
}

// --- The drawer --------------------------------------------------------------------------------

function ImpactedDrawer({
  group,
  workflows,
  canEdit,
  onClose,
  onChanged,
}: {
  group: IssueGroup | null;
  workflows: Map<string, WorkflowSummary>;
  canEdit: boolean;
  onClose: () => void;
  onChanged: () => Promise<void>;
}) {
  const toast = useToast();
  const [tab, setTab] = useState<'needs' | 'reviewed'>('needs');
  const [objectType, setObjectType] = useState('');
  const [onOff, setOnOff] = useState('');
  const [createdBy, setCreatedBy] = useState('');
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [busy, setBusy] = useState(false);

  const groupKey = group?.key;
  useEffect(() => {
    if (!groupKey) return;
    setTab(group.needsReview ? 'needs' : 'reviewed');
    setObjectType('');
    setOnOff('');
    setCreatedBy('');
    setSelected(new Set());
    // A new group opened: start from its state.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [groupKey]);

  if (!group) return null;

  const needs = group.automations.filter((a) => !a.reviewed);
  const done = group.automations.filter((a) => a.reviewed);
  const creators = [
    ...new Map(
      group.automations
        .map((a) => workflows.get(a.workflowId)?.createdBy)
        .filter((c): c is { id: string; name: string } => Boolean(c))
        .map((c) => [c.id, c]),
    ).values(),
  ];
  const rows = (tab === 'needs' ? needs : done).filter((a) => {
    const wf = workflows.get(a.workflowId);
    if (objectType && wf?.objectType !== objectType) return false;
    if (onOff && (onOff === 'on') !== (a.workflowStatus === 'on')) return false;
    if (createdBy && wf?.createdBy?.id !== createdBy) return false;
    return true;
  });
  const allChecked = rows.length > 0 && rows.every((r) => selected.has(r.key));

  const apply = async (reviewed: boolean) => {
    if (!selected.size || busy) return;
    setBusy(true);
    try {
      await reviewWorkflowIssues([...selected], reviewed);
      toast(
        reviewed
          ? `${selected.size} automation${selected.size === 1 ? '' : 's'} marked as reviewed`
          : `${selected.size} automation${selected.size === 1 ? '' : 's'} moved back to needs review`,
      );
      setSelected(new Set());
      await onChanged();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusy(false);
    }
  };

  const objectTypes = [
    ...new Set(
      group.automations
        .map((a) => workflows.get(a.workflowId)?.objectType)
        .filter((o): o is string => Boolean(o)),
    ),
  ];

  return (
    <CrmModal id="wfiDrawer" open onClose={onClose} drawer size="lg">
      <ModalHeader id="wfiDrawer" title="Automations impacted by this issue" onClose={onClose} />
      <div className="modal__body wfi-drawer">
        <h3 className="wfi-drawer__h">Issue</h3>
        <div className="wfi-eyebrow">{group.title}</div>
        <p className="crm-mb-1">{group.message}</p>
        <p className="crm-text-muted crm-fs-7">{explanation(group)}</p>

        <h3 className="wfi-drawer__h crm-mt-4">Impacted automations</h3>
        <HowTo
          title="How to review automations with this issue"
          items={[
            'Check automations in the table to set their status to reviewed',
            <>
              This issue becomes &quot;already reviewed&quot; after you&apos;ve set the status of{' '}
              <strong>all</strong> automations
            </>,
            'Choose "Troubleshoot" on any row to see which records were impacted',
          ]}
        />

        <div className="wfi-subtabs" role="tablist">
          {(
            [
              ['needs', 'Needs review', needs.length],
              ['reviewed', 'Reviewed', done.length],
            ] as const
          ).map(([key, label, n]) => (
            <button
              key={key}
              type="button"
              role="tab"
              aria-selected={tab === key}
              className={cn('wfi-subtab', tab === key && 'is-active')}
              onClick={() => {
                setTab(key);
                setSelected(new Set());
              }}
            >
              {label} <span className="wfi-count">{n}</span>
            </button>
          ))}
        </div>

        <div className="wfi-drawer__filters">
          <label>
            <span>Object type</span>
            <select
              className="select"
              value={objectType}
              onChange={(e) => setObjectType(e.target.value)}
            >
              <option value="">All</option>
              {objectTypes.map((o) => (
                <option key={o} value={o}>
                  {OBJECT_LABELS[o]?.one ?? o}
                </option>
              ))}
            </select>
          </label>
          <label>
            <span>On or Off</span>
            <select className="select" value={onOff} onChange={(e) => setOnOff(e.target.value)}>
              <option value="">All</option>
              <option value="on">On</option>
              <option value="off">Off</option>
            </select>
          </label>
          <label>
            <span>Created by</span>
            <select
              className="select"
              value={createdBy}
              onChange={(e) => setCreatedBy(e.target.value)}
            >
              <option value="">Anyone</option>
              {creators.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </label>
        </div>

        {selected.size && canEdit ? (
          <div className="wfi-selbar">
            <span>{selected.size} selected</span>
            {tab === 'needs' ? (
              <button
                type="button"
                className={cn('btn-crm btn-crm--primary btn-crm--sm', busy && 'is-loading')}
                disabled={busy}
                onClick={() => void apply(true)}
              >
                ✓ Mark as reviewed
              </button>
            ) : (
              <button
                type="button"
                className={cn('btn-crm btn-crm--outline btn-crm--sm', busy && 'is-loading')}
                disabled={busy}
                onClick={() => void apply(false)}
              >
                Move back to needs review
              </button>
            )}
          </div>
        ) : null}

        {rows.length === 0 ? (
          <Empty
            title={tab === 'needs' ? 'Nothing needs review' : 'Nothing reviewed yet'}
            text={
              tab === 'needs'
                ? 'Every automation with this issue has been reviewed.'
                : 'Check automations in "Needs review" to mark them reviewed.'
            }
          />
        ) : (
          <table className="wfi-table wfi-table--drawer">
            <thead>
              <tr>
                <th scope="col" className="wfi-check">
                  {canEdit ? (
                    <input
                      type="checkbox"
                      aria-label="Select all"
                      checked={allChecked}
                      onChange={(e) =>
                        setSelected(e.target.checked ? new Set(rows.map((r) => r.key)) : new Set())
                      }
                    />
                  ) : null}
                </th>
                <th scope="col">Automation name</th>
                <th scope="col">Issue status</th>
                <th scope="col">Priority</th>
                <th scope="col" aria-label="Troubleshoot" />
              </tr>
            </thead>
            <tbody>
              {rows.map((a) => {
                const wf = workflows.get(a.workflowId);
                const object = wf ? (OBJECT_LABELS[wf.objectType]?.one ?? wf.objectType) : '';
                return (
                  <tr key={a.key} className={cn(selected.has(a.key) && 'is-selected')}>
                    <td className="wfi-check">
                      {canEdit ? (
                        <input
                          type="checkbox"
                          aria-label={`Select ${a.workflowName}`}
                          checked={selected.has(a.key)}
                          onChange={(e) =>
                            setSelected((prev) => {
                              const next = new Set(prev);
                              if (e.target.checked) next.add(a.key);
                              else next.delete(a.key);
                              return next;
                            })
                          }
                        />
                      ) : null}
                    </td>
                    <td>
                      <Link className="wfi-link" href={`/workflows/${a.workflowId}`}>
                        {a.workflowName}
                      </Link>
                      <div className="wfi-meta">
                        <span className={cn('wfi-dot', a.workflowStatus === 'on' && 'is-on')} />
                        {a.workflowStatus === 'on' ? 'On' : 'Off'}
                        {object ? ` · ${object}` : ''}
                        {a.kind === 'failed_step' && a.count
                          ? ` · ${a.count} record${a.count === 1 ? '' : 's'} failed`
                          : ''}
                      </div>
                    </td>
                    <td>
                      <span className={cn('wfi-status', a.reviewed && 'is-done')}>
                        <span className={a.reviewed ? 'wfi-dot is-on' : 'wfi-ring'} aria-hidden />
                        {a.reviewed ? 'Reviewed' : 'Needs review'}
                      </span>
                    </td>
                    <td>
                      <PriorityTag priority={a.priority} />
                    </td>
                    <td className="wfi-end">
                      <Link
                        className="btn-crm btn-crm--outline btn-crm--sm"
                        href={
                          a.kind === 'failed_step'
                            ? `/workflows/${a.workflowId}?tab=errors`
                            : `/workflows/${a.workflowId}`
                        }
                      >
                        Troubleshoot
                      </Link>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
      <div className="modal__footer wfi-drawer-foot">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
      </div>
    </CrmModal>
  );
}

// --- The page ------------------------------------------------------------------------------------

type SortKey = 'automations' | 'last' | 'priority';

export function IssuesView() {
  const access = useWorkflowAccess();
  const [groups, setGroups] = useState<IssueGroup[] | null>(null);
  const [workflows, setWorkflows] = useState<Map<string, WorkflowSummary>>(new Map());
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<'needs' | 'reviewed'>('needs');
  const [priority, setPriority] = useState<WorkflowIssuePriority | null>(null);
  const [actions, setActions] = useState<Set<string>>(new Set());
  const [sources, setSources] = useState<Set<string>>(new Set([SOURCE]));
  const [sort, setSort] = useState<{ key: SortKey; dir: 'asc' | 'desc' }>({
    key: 'priority',
    dir: 'asc',
  });
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [openKey, setOpenKey] = useState<string | null>(null);
  const priorityMenu = useDropdown();
  const actionMenu = useDropdown();
  const sourceMenu = useDropdown();

  const load = useCallback(async () => {
    try {
      const [fresh, reviewed] = await Promise.all([
        listWorkflowIssues('new'),
        listWorkflowIssues('reviewed'),
      ]);
      setGroups(toGroups(fresh.data, reviewed.data));
      setError(null);
    } catch (err) {
      setError(errorText(err));
    }
  }, []);

  useEffect(() => {
    if (!access.canView) return;
    void load();
    listWorkflows({ limit: 500 }).then(
      (res) => setWorkflows(new Map(res.data.map((w) => [w.id, w]))),
      () => setWorkflows(new Map()),
    );
  }, [access.canView, load]);

  const needs = useMemo(() => (groups ?? []).filter((g) => g.needsReview), [groups]);
  const reviewedGroups = useMemo(() => (groups ?? []).filter((g) => !g.needsReview), [groups]);
  const actionOptions = useMemo(
    () =>
      [...new Map((groups ?? []).map((g) => [g.actionType ?? g.kind, g.title])).entries()].sort(
        (a, b) => a[1].localeCompare(b[1]),
      ),
    [groups],
  );

  const rows = useMemo(() => {
    const list = (tab === 'needs' ? needs : reviewedGroups).filter(
      (g) =>
        (!priority || g.priority === priority) &&
        (!actions.size || actions.has(g.actionType ?? g.kind)) &&
        sources.has(SOURCE),
    );
    const dir = sort.dir === 'asc' ? 1 : -1;
    return [...list].sort((a, b) => {
      if (sort.key === 'automations') return (a.automations.length - b.automations.length) * dir;
      if (sort.key === 'last') {
        return (a.last?.lastAt ?? '').localeCompare(b.last?.lastAt ?? '') * dir;
      }
      return (
        (PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority]) * dir ||
        (b.last?.lastAt ?? '').localeCompare(a.last?.lastAt ?? '')
      );
    });
  }, [tab, needs, reviewedGroups, priority, actions, sources, sort]);

  const pages = Math.max(1, Math.ceil(rows.length / pageSize));
  const current = Math.min(page, pages);
  const shown = rows.slice((current - 1) * pageSize, current * pageSize);
  const open = groups?.find((g) => g.key === openKey) ?? null;

  useEffect(() => setPage(1), [tab, priority, actions, sources, pageSize]);

  if (!access.canView) return <NoWorkflowAccess />;

  const toggleSort = (key: SortKey) =>
    setSort((s) => ({ key, dir: s.key === key && s.dir === 'desc' ? 'asc' : 'desc' }));
  const sortIcon = (key: SortKey) => (
    <span className={cn('wfi-sort', sort.key === key && 'is-active')} aria-hidden>
      ↕
    </span>
  );
  const countBy = (p: WorkflowIssuePriority | null) =>
    needs.filter((g) => !p || g.priority === p).length;

  return (
    <div className="wfi-page">
      <Link className="wfi-back" href="/workflows">
        ← Back to workflows
      </Link>
      <h1 className="wfi-title">
        Review automation issues <span className="wfi-beta">Beta</span>
      </h1>

      <div className="wfi-dd" ref={priorityMenu.ref}>
        <button
          type="button"
          className="wfi-total"
          aria-haspopup="menu"
          aria-expanded={priorityMenu.open}
          onClick={() => priorityMenu.setOpen(!priorityMenu.open)}
        >
          <span className="wfi-total__dot" aria-hidden />
          {groups ? countBy(priority) : '…'} Issue{countBy(priority) === 1 ? '' : 's'}
          {priority ? ` · ${PRIORITY_LABEL[priority]}` : ''}
          <Chevron open={priorityMenu.open} />
        </button>
        {priorityMenu.open ? (
          <div className="wfi-menu" role="menu">
            <div className="wfi-menu__title">Issues that need review</div>
            {([null, 'high', 'medium', 'low'] as const).map((p) => (
              <button
                key={p ?? 'all'}
                type="button"
                role="menuitemradio"
                aria-checked={priority === p}
                className={cn('wfi-menu__item', priority === p && 'is-active')}
                onClick={() => {
                  setPriority(p);
                  setTab('needs');
                  priorityMenu.setOpen(false);
                }}
              >
                <span className={cn('wfi-ring', p && `is-${p}`)} aria-hidden />
                <span className="wfi-menu__label">{p ? PRIORITY_LABEL[p] : 'All priorities'}</span>
                <strong>{countBy(p)}</strong>
              </button>
            ))}
          </div>
        ) : null}
      </div>

      <div className="wfi-tabs" role="tablist">
        <button
          type="button"
          role="tab"
          aria-selected={tab === 'needs'}
          className={cn('wfi-tab', tab === 'needs' && 'is-active')}
          onClick={() => setTab('needs')}
        >
          <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden>
            <path
              d="M12 3 2 21h20zM12 10v5M12 18h.01"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            />
          </svg>
          Needs review
        </button>
        <button
          type="button"
          role="tab"
          aria-selected={tab === 'reviewed'}
          className={cn('wfi-tab', tab === 'reviewed' && 'is-active')}
          onClick={() => setTab('reviewed')}
        >
          Already reviewed
        </button>
      </div>

      <HowTo
        title="How to review these issues"
        items={[
          'Choose an issue from the table to review the automations it affected',
          'An issue may affect automations made in several different tools',
          'The issue moves to "Already reviewed" after you review all the automations it affected',
        ]}
      />

      <div className="wfi-filters">
        <div className="wfi-dd" ref={actionMenu.ref}>
          <button
            type="button"
            className={cn('wfi-filter', actions.size > 0 && 'is-active')}
            aria-expanded={actionMenu.open}
            onClick={() => actionMenu.setOpen(!actionMenu.open)}
          >
            Impacted action
            {actions.size ? <span className="wfi-badge">{actions.size}</span> : null}
            <Chevron open={actionMenu.open} />
          </button>
          {actionMenu.open ? (
            <div className="wfi-menu">
              {actionOptions.length === 0 ? (
                <p className="crm-text-muted crm-fs-7 crm-mb-0">No actions have issues.</p>
              ) : (
                actionOptions.map(([key, label]) => (
                  <label key={key} className="wfi-menu__item">
                    <input
                      type="checkbox"
                      checked={actions.has(key)}
                      onChange={(e) =>
                        setActions((prev) => {
                          const next = new Set(prev);
                          if (e.target.checked) next.add(key);
                          else next.delete(key);
                          return next;
                        })
                      }
                    />
                    <span className="wfi-menu__label">{label}</span>
                  </label>
                ))
              )}
              <div className="wfi-menu__foot">
                <button
                  type="button"
                  className="dyn-link-btn"
                  onClick={() => setActions(new Set())}
                >
                  Clear
                </button>
              </div>
            </div>
          ) : null}
        </div>

        <div className="wfi-dd" ref={sourceMenu.ref}>
          <span className="wfi-filter wfi-filter--split">
            <button
              type="button"
              className="wfi-filter__main"
              aria-expanded={sourceMenu.open}
              onClick={() => sourceMenu.setOpen(!sourceMenu.open)}
            >
              Occurred in ({sources.size}) <Chevron open={sourceMenu.open} />
            </button>
            {sources.size !== 1 || !sources.has(SOURCE) ? (
              <button
                type="button"
                className="wfi-filter__clear"
                aria-label="Reset Occurred in"
                onClick={() => setSources(new Set([SOURCE]))}
              >
                ×
              </button>
            ) : null}
          </span>
          {sourceMenu.open ? (
            <div className="wfi-menu">
              <label className="wfi-menu__item">
                <input
                  type="checkbox"
                  checked={sources.has(SOURCE)}
                  onChange={(e) => setSources(e.target.checked ? new Set([SOURCE]) : new Set())}
                />
                <span className="wfi-menu__label">{SOURCE}</span>
              </label>
            </div>
          ) : null}
        </div>
      </div>

      {error ? <Alert tone="danger">{error}</Alert> : null}

      <div className="wfi-table-wrap">
        <table className="wfi-table">
          <thead>
            <tr>
              <th scope="col">Issue</th>
              <th scope="col">Occurred in</th>
              <th scope="col" className="wfi-num">
                <button type="button" onClick={() => toggleSort('automations')}>
                  Automations {sortIcon('automations')}
                </button>
              </th>
              <th scope="col">
                <button type="button" onClick={() => toggleSort('last')}>
                  Last occurrence {sortIcon('last')}
                </button>
              </th>
              <th scope="col">
                <button type="button" onClick={() => toggleSort('priority')}>
                  Priority {sortIcon('priority')}
                </button>
              </th>
            </tr>
          </thead>
          <tbody>
            {groups === null && !error ? (
              <tr>
                <td colSpan={5} className="crm-text-muted">
                  Loading…
                </td>
              </tr>
            ) : null}
            {shown.map((g) => (
              <tr key={g.key} className="wfi-row" onClick={() => setOpenKey(g.key)}>
                <td>
                  <button
                    type="button"
                    className="wfi-link"
                    onClick={(e) => {
                      e.stopPropagation();
                      setOpenKey(g.key);
                    }}
                  >
                    {g.title}
                  </button>
                  <div className="wfi-issue-text">{g.message}</div>
                  <button
                    type="button"
                    className="wfi-view btn-crm btn-crm--outline btn-crm--sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      setOpenKey(g.key);
                    }}
                  >
                    View automations
                  </button>
                </td>
                <td className="wfi-source">{SOURCE}</td>
                <td className="wfi-num">{g.automations.length}</td>
                <td>
                  <div>{formatWhenLong(g.last?.lastAt ?? null, access.timeZone)}</div>
                  {g.last ? (
                    <div className="wfi-issue-text">
                      &quot;{g.last.workflowName}&quot; in {SOURCE}
                    </div>
                  ) : null}
                </td>
                <td>
                  <PriorityTag priority={g.priority} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {groups && rows.length === 0 ? (
          <Empty
            title={tab === 'needs' ? 'No issues need review' : 'No reviewed issues yet'}
            text={
              tab === 'needs'
                ? 'Your automations are running without problems.'
                : "Issues move here once you've reviewed every automation they affected."
            }
          />
        ) : null}
      </div>

      <div className="wfi-pager">
        <button
          type="button"
          className="wfi-pager__btn"
          disabled={current <= 1}
          onClick={() => setPage(current - 1)}
        >
          ‹ Prev
        </button>
        <span className="wfi-pager__num">{current}</span>
        <button
          type="button"
          className="wfi-pager__btn"
          disabled={current >= pages}
          onClick={() => setPage(current + 1)}
        >
          Next ›
        </button>
        <select
          className="wfi-pager__size"
          aria-label="Issues per page"
          value={pageSize}
          onChange={(e) => setPageSize(Number(e.target.value))}
        >
          {PAGE_SIZES.map((n) => (
            <option key={n} value={n}>
              {n} per page
            </option>
          ))}
        </select>
      </div>

      <ImpactedDrawer
        group={open}
        workflows={workflows}
        canEdit={access.canEdit}
        onClose={() => setOpenKey(null)}
        onChanged={load}
      />
    </div>
  );
}
