'use client';

/**
 * The parts of `data-integration.php` (6 Nov design), drawn with the design's markup and classes
 * so its CSS applies as written (`public/crm/assets/css/data-integration.css`). State lives in
 * `DataIntegrationView`; these only render.
 */
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { importErrorsCsvUrl, importFileUrl } from '@/features/imports/api.client';
import {
  IMPORT_ERRORS_NOT_YOURS_TEXT,
  importDetailsHref,
  rowsWithErrorsHref,
} from '../importDetails';
import { cn } from '@/lib/utils/cn';
import {
  DI_COLUMNS,
  DI_COL_CHOICES,
  DI_PAGE_SIZES,
  UNASSIGNED,
  chipValueText,
  menuGroups,
  pageWindow,
  type DiColKey,
  type DiDatePreset,
  type DiImportRow,
  type DiMenuItem,
  type DiPresetOption,
} from '../fileImports';
import { IMPORT_ART, STUDIO_ART, SYNC_ART, TRANSFER_ART, TRANSFORM_ART, type DiArt } from './art';

export type DiTab = 'file' | 'app' | 'studio';

function Art({ art }: { art: DiArt }) {
  return (
    <svg
      width={art.width}
      height={art.height}
      viewBox={art.viewBox}
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={art.className}
      dangerouslySetInnerHTML={{ __html: art.inner }}
    />
  );
}

/** The design's small list-page icons (`lp-i`). */
function Chevron() {
  return (
    <svg
      className="lp-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

function Cross() {
  return (
    <svg
      className="lp-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden="true"
    >
      <path d="M18 6 6 18M6 6l12 12" />
    </svg>
  );
}

function Magnifier() {
  return (
    <svg
      className="lp-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden="true"
    >
      <circle cx="11" cy="11" r="7" />
      <path d="m21 21-4.3-4.3" />
    </svg>
  );
}

/** One of the four top cards (`data-integration.php:211-453`). */
function Card({
  art,
  title,
  sub,
  action,
  badge,
}: {
  art: DiArt;
  title: string;
  sub: React.ReactNode;
  action: React.ReactNode;
  badge?: string;
}) {
  return (
    <div className="crm-col-12 crm-col-sm-6 crm-col-xl-3">
      <div
        className={cn(
          'card',
          badge && 'crm-position-relative',
          'crm-h-100 crm-p-4 crm-d-flex crm-flex-column crm-justify-content-between',
        )}
      >
        {badge ? (
          <span className="badge badge--brand crm-position-absolute crm-top-0 crm-end-0 crm-m-3">
            {badge}
          </span>
        ) : null}
        <div className="crm-d-flex crm-flex-column crm-gap-2 crm-mb-4">
          <Art art={art} />
          <h2 className="card__title crm-fs-5 crm-fw-bold">{title}</h2>
          <p className="card__sub crm-fs-7 crm-text-muted crm-mb-0">{sub}</p>
        </div>
        <div className="crm-mt-auto">{action}</div>
      </div>
    </div>
  );
}

/**
 * `onSoon(label)` shows the design's "<label> is coming soon" (`base.js:284-288`).
 * `onConnectApp`, when given, opens the "Connect an app" flow (`data-integration.js:2944-2952`).
 */
export function IntegrationCards({
  onSoon,
  onConnectApp,
}: {
  onSoon: (label: string) => void;
  onConnectApp?: () => void;
}) {
  return (
    <section className="crm-row crm-g-4 crm-mb-4" aria-label="Integration options">
      <Card
        art={IMPORT_ART}
        title="Import a file"
        sub="One-time import from a file—directly into your CRM."
        action={
          <Link href="/data-integration/import" className="btn-crm btn-crm--outline btn-crm--sm">
            Import data
          </Link>
        }
      />
      <Card
        art={SYNC_ART}
        title="Sync from apps"
        sub="Keep data synced between your CRM and external apps."
        action={
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            id="btnConnectApp"
            onClick={() => (onConnectApp ? onConnectApp() : onSoon('Connect an app'))}
          >
            Connect an app
          </button>
        }
      />
      <Card
        art={TRANSFER_ART}
        title="Transfer your data"
        sub={
          <>
            Seamlessly transfer your data using the Smart Transfer tool.{' '}
            <a
              href="#"
              className="link crm-mt-1"
              onClick={(e) => {
                e.preventDefault();
                onSoon('Smart Transfer documentation');
              }}
            >
              Learn more <CrmIcon name="external" className="iconSize-16" />
            </a>
          </>
        }
        action={
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => onSoon('Transfer your data')}
          >
            Coming soon
          </button>
        }
      />
      <Card
        art={TRANSFORM_ART}
        badge="Beta"
        title="Transform your data"
        sub="Blend data from siloed sources before syncing to your CRM."
        action={
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => onSoon('Transform your data')}
          >
            Coming soon
          </button>
        }
      />
    </section>
  );
}

const TABS: { id: DiTab; target: string; label: string }[] = [
  { id: 'file', target: '#pane-file-imports', label: 'File imports' },
  { id: 'app', target: '#pane-app-syncs', label: 'App syncs' },
  { id: 'studio', target: '#pane-data-studio-syncs', label: 'Data studio syncs' },
];

/** The Monitor card's tabs (`data-integration.php:471-477`). */
export function MonitorTabs({
  active,
  onSelect,
}: {
  active: DiTab;
  onSelect: (tab: DiTab) => void;
}) {
  return (
    <div className="os-tabbar crm-mb-4">
      <nav className="os-tabs" aria-label="Monitor Tabs">
        {TABS.map((t) => (
          <button
            key={t.id}
            type="button"
            className={cn('os-tab', active === t.id && 'is-active')}
            data-tab-target={t.target}
            onClick={() => onSelect(t.id)}
          >
            {t.label}
          </button>
        ))}
      </nav>
    </div>
  );
}

function StudioPoint({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="di-studio-feature crm-d-flex crm-align-items-start crm-gap-3">
      <span className="di-studio-arrow" aria-hidden="true">
        <svg
          width="12"
          height="12"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <path d="M5 12h14M13 6l6 6-6 6" />
        </svg>
      </span>
      <p className="di-studio-desc crm-m-0">
        <strong>{title}</strong> {children}
      </p>
    </div>
  );
}

/** Data studio syncs tab (`data-integration.php:1453-1610`). */
export function StudioPane() {
  return (
    <div className="di-studio-hero crm-d-flex crm-align-items-center crm-justify-content-between">
      <div className="di-studio-content">
        <h2 className="di-studio-title">Set up a Data Studio sync</h2>
        <div className="di-studio-features crm-d-flex crm-flex-column crm-gap-4 crm-mb-5">
          <StudioPoint title="Cross-platform data integration:">
            Bring multiple external sources into Data Studio and combine them into a single dataset
            before syncing data into your CRM.
          </StudioPoint>
          <StudioPoint title="Enrich your data with AI:">
            Fill in missing customer information, identify patterns in data, and find deeper
            insights with AI smart recommendations.
          </StudioPoint>
          <StudioPoint title="Sync relevant data:">
            Reduce clutter by selecting the specific columns you want to bring into your CRM.
          </StudioPoint>
        </div>
        {/* QA #386: no "Upgrade to Data Hub" upsell. */}
      </div>
      <div className="di-studio-art" id="diStudioArt" aria-hidden="true">
        <Art art={STUDIO_ART} />
      </div>
    </div>
  );
}

/** A chip's popover search box (`lp-search lp-search--sm`). */
function PopSearch({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <label className="lp-search lp-search--sm crm-mb-2">
      <Magnifier />
      <input
        type="search"
        placeholder="Search"
        aria-label={label}
        value={value}
        onChange={(e) => onChange(e.target.value)}
      />
    </label>
  );
}

function ChipButton({
  label,
  value,
  open,
  onToggle,
  onClear,
}: {
  label: string;
  value: string;
  open: boolean;
  onToggle: () => void;
  onClear: () => void;
}) {
  return (
    <>
      <button type="button" className="lp-chip__btn" aria-expanded={open} onClick={onToggle}>
        <span className="lp-chip__label">{label}</span>
        {value ? <span className="lp-chip__val">{value}</span> : null}
        <Chevron />
      </button>
      {value ? (
        <button type="button" className="lp-chip__x" aria-label="Remove filter" onClick={onClear}>
          <Cross />
        </button>
      ) : null}
    </>
  );
}

function PopFoot({ onClear, onDone }: { onClear: () => void; onDone: () => void }) {
  return (
    <div className="lp-pop__foot">
      <button type="button" className="lp-link" onClick={onClear}>
        Clear
      </button>
      <button type="button" className="lp-btn lp-btn--outline lp-btn--sm" onClick={onDone}>
        Done
      </button>
    </div>
  );
}

const SEARCH_LABEL: Record<string, string> = {
  system: 'Search systems',
  source: 'Search sources',
  user: 'Search users',
};

/** A checkbox chip: Import System, Import Source, Created by user ID (`data-integration.php:487-656`). */
export function CheckChip({
  id,
  label,
  options,
  checked,
  selectAll,
  open,
  onToggle,
  onChange,
  onClear,
}: {
  id: 'system' | 'source' | 'user';
  label: string;
  options: readonly string[];
  checked: string[];
  /** Import System's "Select all", checked at first (`data-integration.php:518`). */
  selectAll?: boolean;
  open: boolean;
  onToggle: () => void;
  onChange: (next: string[]) => void;
  onClear: () => void;
}) {
  const [q, setQ] = useState('');
  const [allOn, setAllOn] = useState(true);
  const value = chipValueText(checked);
  const hit = (s: string) => !q.trim() || s.toLowerCase().includes(q.trim().toLowerCase());
  const clear = () => {
    setAllOn(false);
    onClear();
  };
  return (
    <div className={cn('dropdown lp-chip', value && 'is-active')}>
      <ChipButton label={label} value={value} open={open} onToggle={onToggle} onClear={clear} />
      <div className="dropdown__menu lp-pop lp-pop--filter" data-dropdown-menu="" hidden={!open}>
        <div className="lp-pop__arrow" />
        <div className="lp-pop__body">
          <div className="lp-chippop">
            <div className="lp-pop__title">{label}</div>
            <PopSearch label={SEARCH_LABEL[id]!} value={q} onChange={setQ} />
            <div className="lp-optlist" role="listbox">
              {selectAll ? (
                <label className="lp-opt" hidden={!hit('Select all')}>
                  <input
                    type="checkbox"
                    checked={allOn}
                    onChange={(e) => {
                      setAllOn(e.target.checked);
                      onChange(e.target.checked ? [...options] : []);
                    }}
                  />
                  <span className="lp-opt__txt">
                    <span>Select all</span>
                  </span>
                </label>
              ) : null}
              {options.map((o) => {
                const on = checked.includes(o);
                return (
                  <label key={o} className={cn('lp-opt', on && 'is-checked')} hidden={!hit(o)}>
                    <input
                      type="checkbox"
                      value={o}
                      checked={on}
                      onChange={(e) =>
                        onChange(
                          e.target.checked ? [...checked, o] : checked.filter((v) => v !== o),
                        )
                      }
                    />
                    <span className="lp-opt__txt">
                      <span>{o}</span>
                      {id === 'user' && o === UNASSIGNED ? <small>No user assigned</small> : null}
                    </span>
                  </label>
                );
              })}
            </div>
            <PopFoot onClear={clear} onDone={onToggle} />
          </div>
        </div>
      </div>
    </div>
  );
}

/** The Create date chip (`data-integration.php:658-737`). */
export function DateChip({
  presets,
  value,
  open,
  onToggle,
  onPick,
  onClear,
}: {
  presets: DiPresetOption[];
  value: DiDatePreset | null;
  open: boolean;
  onToggle: () => void;
  onPick: (id: DiDatePreset) => void;
  onClear: () => void;
}) {
  const [q, setQ] = useState('');
  const picked = presets.find((p) => p.id === value);
  const hit = (p: DiPresetOption) =>
    !q.trim() || `${p.label} ${p.sub}`.toLowerCase().includes(q.trim().toLowerCase());
  return (
    <div className={cn('dropdown lp-chip', picked && 'is-active')}>
      <ChipButton
        label="Create date"
        value={picked?.label ?? ''}
        open={open}
        onToggle={onToggle}
        onClear={onClear}
      />
      <div className="dropdown__menu lp-pop lp-pop--filter" data-dropdown-menu="" hidden={!open}>
        <div className="lp-pop__arrow" />
        <div className="lp-pop__body">
          <div className="lp-chippop">
            <div className="lp-pop__title">Create date</div>
            <PopSearch label="Search date ranges" value={q} onChange={setQ} />
            <div className="lp-presets" role="radiogroup" aria-label="Date range">
              {presets.map((p) => (
                <label
                  key={p.id}
                  className={cn('lp-preset', p.id === value && 'is-checked')}
                  hidden={!hit(p)}
                >
                  <input
                    type="radio"
                    name="diDatePreset"
                    value={p.id}
                    checked={p.id === value}
                    onChange={() => onPick(p.id)}
                  />
                  <span className="lp-preset__txt">
                    <span>{p.label}</span>
                    <small>{p.sub}</small>
                  </span>
                </label>
              ))}
            </div>
            <PopFoot onClear={onClear} onDone={onToggle} />
          </div>
        </div>
      </div>
    </div>
  );
}

function SortArrow() {
  return (
    <span className="lp-th__arrow" aria-hidden="true">
      <span className="sort-icon-default">
        <CrmIcon name="sort" className="iconSize-14" />
      </span>
      <span className="sort-icon-asc">
        <CrmIcon name="arrow-up" className="iconSize-14" />
      </span>
      <span className="sort-icon-desc">
        <CrmIcon name="arrow-down" className="iconSize-14" />
      </span>
    </span>
  );
}

const none = <span className="crm-text-subtle">--</span>;

function Cell({ row, col }: { row: DiImportRow; col: DiColKey }) {
  switch (col) {
    case 'state':
      return (
        <td className="lp-td lp-td--state" data-col="state">
          <span className="di-status">
            <span className="di-status-dot" aria-hidden="true" />
            <span>{row.state}</span>
          </span>
        </td>
      );
    case 'new':
    case 'updated':
    case 'assoc':
      return (
        <td className="lp-td lp-td--num lp-td--end" data-col={col}>
          {col === 'new' ? row.newText : col === 'updated' ? row.updatedText : row.assocText}
        </td>
      );
    case 'errors':
      return (
        <td className="lp-td lp-td--num lp-td--end" data-col="errors">
          {row.errors > 0 && row.canManage === false ? (
            // BL1: someone else's import: the count, not a link to rows they can't see.
            <span className="crm-fw-bold" title={IMPORT_ERRORS_NOT_YOURS_TEXT}>
              {row.errorsText}
            </span>
          ) : row.errors > 0 ? (
            // The design's link to import-details.php's error rows, in a new tab
            // (`data-integration.php:994-998`).
            <a
              href={rowsWithErrorsHref(row.id)}
              target="_blank"
              className="link crm-text-brand crm-fw-bold crm-text-decoration-none"
              title="View rows with errors"
            >
              {row.errorsText}
            </a>
          ) : (
            none
          )}
        </td>
      );
    case 'user':
      return (
        <td className="lp-td lp-td--user" data-col="user">
          {row.user ? (
            <div className="lp-owner">
              <span className="avatar avatar--sm" aria-hidden="true">
                {row.initials}
              </span>
              <span className="crm-fs-8 crm-fw-medium">{row.user}</span>
            </div>
          ) : (
            none
          )}
        </td>
      );
    case 'date':
      return (
        <td className="lp-td lp-td--date crm-text-muted crm-fs-8" data-col="date">
          {row.dateText}
        </td>
      );
    case 'enriched':
    case 'events':
    case 'marketable':
      return (
        <td className="lp-td lp-td--opt" data-col={col}>
          {none}
        </td>
      );
    case 'source':
    case 'system':
      return (
        <td className="lp-td lp-td--opt" data-col={col}>
          {col === 'source' ? row.sourceText : row.systemText}
        </td>
      );
    case 'total_rows':
      return (
        <td className="lp-td lp-td--opt lp-td--num lp-td--end" data-col="total_rows">
          {row.totalText}
        </td>
      );
    case 'name':
      return null;
  }
}

/** The imports table (`data-integration.php:754-1048`). Only the picked columns are drawn. */
export function ImportsTable({
  rows,
  columns,
  sortKey,
  sortDir,
  onSort,
  onMore,
  openMenuId,
  showEmpty,
  onScroll,
}: {
  rows: DiImportRow[];
  columns: DiColKey[];
  sortKey: DiColKey | null;
  sortDir: 'asc' | 'desc';
  onSort: (key: DiColKey) => void;
  onMore: (row: DiImportRow, button: HTMLButtonElement) => void;
  openMenuId: string | null;
  /** The "No imports match" row (`emptyRowShown`). */
  showEmpty: boolean;
  /** The table's own scroll closes the row menu (`data-integration.js:557-560`). */
  onScroll?: () => void;
}) {
  const cols = DI_COLUMNS.filter((c) => columns.includes(c.key));
  return (
    <div className="lp-tablewrap di-tablewrap" onScroll={onScroll}>
      <table className="lp-table di-table" id="diTable" aria-label="Imports history">
        <thead>
          <tr>
            {cols.map((c) => {
              const sorted = sortKey === c.key;
              return (
                <th
                  key={c.key}
                  scope="col"
                  className={cn(
                    'lp-th',
                    c.thClass,
                    c.num && 'lp-th--num lp-th--end',
                    sorted && 'is-sorted',
                  )}
                  data-col={c.key}
                  data-sort-dir={sorted ? sortDir : undefined}
                  data-sortable="true"
                  data-sort-key={c.key}
                  title={c.title}
                  aria-sort={
                    sortKey
                      ? sorted
                        ? sortDir === 'asc'
                          ? 'ascending'
                          : 'descending'
                        : 'none'
                      : undefined
                  }
                >
                  <div className={cn('lp-th__in', c.num && 'lp-th__in--end')}>
                    <button
                      type="button"
                      className={cn('lp-th__sort', c.num && 'lp-th__sort--end')}
                      data-sort-col={c.key}
                      title={`Sort by ${c.title}`}
                      onClick={() => onSort(c.key)}
                    >
                      <span className="lp-th__lbl">{c.label}</span>
                      <SortArrow />
                    </button>
                  </div>
                </th>
              );
            })}
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr
              key={r.id}
              className={cn('lp-tr', openMenuId === r.id && 'is-menu-open')}
              data-row=""
            >
              <td className="lp-td lp-td--name" data-col="name">
                <div className="di-name-cell">
                  {/* The design's link to import-details.php (`data-integration.php:958-959`). */}
                  <Link className="di-name-link" title={r.name} href={importDetailsHref(r.id)}>
                    {r.name}
                  </Link>
                  <div className="di-more-wrap">
                    <button
                      type="button"
                      className="di-more-btn"
                      aria-haspopup="menu"
                      aria-expanded={openMenuId === r.id}
                      title="More actions"
                      onClick={(e) => {
                        e.stopPropagation();
                        onMore(r, e.currentTarget);
                      }}
                    >
                      <span>More</span>
                      <svg
                        className="di-more-caret"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2.5"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        aria-hidden="true"
                      >
                        <path d="m6 9 6 6 6-6" />
                      </svg>
                    </button>
                  </div>
                </div>
              </td>
              {cols
                .filter((c) => c.key !== 'name')
                .map((c) => (
                  <Cell key={c.key} row={r} col={c.key} />
                ))}
            </tr>
          ))}
          {showEmpty ? (
            <tr id="diEmptyRow">
              <td colSpan={14} className="lp-td lp-td--empty">
                <div className="lp-empty">
                  <CrmIcon name="search" className="lp-empty__i" />
                  <strong>No imports match your search or filters</strong>
                  <p>Try resetting filters or changing your search query.</p>
                </div>
              </td>
            </tr>
          ) : null}
        </tbody>
      </table>
    </div>
  );
}

function MenuEntry({
  item,
  rowId,
  onPick,
}: {
  item: DiMenuItem;
  rowId: string;
  onPick: (item: DiMenuItem) => void;
}) {
  if (item.label === '-') return <div className="di-menu-sep" role="separator" />;
  // BL1: not this person's import: shown, not usable, the reason as its tooltip.
  if (item.disabled) {
    return (
      <button
        type="button"
        className="di-menu-item"
        role="menuitem"
        disabled
        aria-disabled="true"
        title={item.disabled}
      >
        {item.label}
      </button>
    );
  }
  if (item.action === 'use-template' && item.href) {
    return (
      <Link href={item.href} className="di-menu-item" role="menuitem">
        <span>{item.label}</span>
        <span className="crm-text-subtle" title="Learn more">
          <CrmIcon name="info" className="iconSize-14" />
        </span>
      </Link>
    );
  }
  if (item.href) {
    return (
      <Link href={item.href} className="di-menu-item" role="menuitem">
        {item.label}
      </Link>
    );
  }
  if (item.action === 'download-file' && !item.soon && !item.gone) {
    return (
      <a
        href={importFileUrl(rowId)}
        className="di-menu-item"
        role="menuitem"
        onClick={(e) => {
          // The pick fetches it first (`downloadImportFile`), so a gone file shows a message.
          e.preventDefault();
          onPick(item);
        }}
      >
        {item.label}
      </a>
    );
  }
  if (item.action === 'download-error-file') {
    return (
      <a
        href={importErrorsCsvUrl(rowId)}
        className="di-menu-item"
        role="menuitem"
        onClick={(e) => {
          // #712: fetched and saved by the page (onPick), as Download original file.
          e.preventDefault();
          onPick(item);
        }}
      >
        {item.label}
      </a>
    );
  }
  return (
    <button type="button" className="di-menu-item" role="menuitem" onClick={() => onPick(item)}>
      {item.label}
    </button>
  );
}

/** The row's floating More menu (`data-integration.php:1050-1078`). */
export function RowMenu({
  row,
  top,
  left,
  onPick,
  menuRef,
}: {
  row: DiImportRow;
  top: number;
  left: number;
  onPick: (item: DiMenuItem) => void;
  /** For measuring its height (`placeMenu`). */
  menuRef?: React.Ref<HTMLDivElement>;
}) {
  const { main, tail } = menuGroups(
    row.errors,
    row.deletable,
    row.fileAvailable,
    row,
    row.canManage !== false,
  );
  return (
    <div
      ref={menuRef}
      className="di-floating-menu"
      id="diMoreMenu"
      role="menu"
      aria-label="Import row actions"
      style={{ top, left }}
      onClick={(e) => e.stopPropagation()}
    >
      <div className="di-menu-group" data-menu-scope={row.errors > 0 ? 'has-errors' : 'no-errors'}>
        {main.map((item, i) => (
          <MenuEntry key={i} item={item} rowId={row.id} onPick={onPick} />
        ))}
      </div>
      <div className="di-menu-sep" role="separator" />
      {tail.map((item, i) => (
        <MenuEntry key={i} item={item} rowId={row.id} onPick={onPick} />
      ))}
    </div>
  );
}

/** The pager (`data-integration.php:1080-1110`). */
export function Pager({
  page,
  pages,
  size,
  onPage,
  onSize,
  label = 'Pagination',
}: {
  page: number;
  pages: number;
  size: number;
  onPage: (page: number) => void;
  onSize: (size: number) => void;
  /** The nav's label: "App syncs pagination" on App syncs (`data-integration.php:1421`). */
  label?: string;
}) {
  const [open, setOpen] = useState(false);
  const sizeBox = useRef<HTMLDivElement>(null);
  // As the design's dropdowns (`base.js:16`): an outside click or Escape closes it.
  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (sizeBox.current && !sizeBox.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    document.addEventListener('click', onClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);
  return (
    <nav className="wf-pager crm-mt-4" aria-label={label}>
      <button
        type="button"
        className="wf-pager__btn"
        data-pager-prev=""
        disabled={page <= 1}
        aria-label="Previous page"
        onClick={() => onPage(page - 1)}
      >
        <CrmIcon name="chevron-left" className="iconSize-14" />
        Prev
      </button>
      <span className="wf-pager__nums">
        {pageWindow(page, pages).map((n) => (
          <button
            key={n}
            type="button"
            className={cn('wf-pager__num', n === page && 'is-active')}
            aria-current={n === page ? 'page' : undefined}
            data-page={n}
            onClick={() => n !== page && onPage(n)}
          >
            {n}
          </button>
        ))}
      </span>
      <button
        type="button"
        className="wf-pager__btn"
        data-pager-next=""
        disabled={page >= pages}
        aria-label="Next page"
        onClick={() => onPage(page + 1)}
      >
        Next
        <CrmIcon name="chevron-right" className="iconSize-14" />
      </button>
      <div className="dropdown" ref={sizeBox}>
        <button
          type="button"
          className="wf-pager__btn wf-pager__size"
          aria-expanded={open}
          aria-label="Rows per page"
          onClick={() => setOpen((o) => !o)}
        >
          <span>{size}</span> per page <CrmIcon name="chevron-down" className="iconSize-14" />
        </button>
        <div className="dropdown__menu dropdown__menu--up dropdown__menu--right" hidden={!open}>
          {DI_PAGE_SIZES.map((s) => (
            <button
              key={s}
              type="button"
              className={cn('dropdown__item', s === size && 'is-selected')}
              data-size={s}
              onClick={() => {
                setOpen(false);
                onSize(s);
              }}
            >
              {s} per page
            </button>
          ))}
        </div>
      </div>
    </nav>
  );
}

/** Edit columns (`data-integration.php:1616-1723`). */
export function EditColumnsDialog({
  open,
  draft,
  query,
  onQuery,
  onToggle,
  onClear,
  onRestore,
  onApply,
  onClose,
}: {
  open: boolean;
  draft: DiColKey[];
  query: string;
  onQuery: (q: string) => void;
  onToggle: (key: DiColKey, on: boolean) => void;
  onClear: () => void;
  onRestore: () => void;
  onApply: () => void;
  onClose: () => void;
}) {
  if (!open) return null;
  const q = query.trim().toLowerCase();
  const shown = DI_COL_CHOICES.filter((c) => !q || c.label.toLowerCase().includes(q));
  return (
    <div
      className="modal-backdrop is-open"
      id="diEditColumnsModal"
      aria-hidden="false"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className="modal di-cols-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="diEditColumnsTitle"
      >
        <div className="modal__header">
          <h2 className="modal__title" id="diEditColumnsTitle">
            Edit columns
          </h2>
          <button
            type="button"
            className="modal__close"
            aria-label="Close dialog"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </div>
        <div className="modal__body di-cols-modal__body">
          <div className="input-group crm-mb-2 di-cols-search-wrap crm-rounded-sm">
            <input
              type="search"
              className="input di-cols-search"
              id="diColsSearchInput"
              placeholder="Search columns"
              autoComplete="off"
              aria-label="Search columns"
              value={query}
              autoFocus
              onChange={(e) => onQuery(e.target.value)}
            />
            <span className="input-group__btn" style={{ pointerEvents: 'none' }} aria-hidden="true">
              <CrmIcon name="search" className="iconSize-16" />
            </span>
          </div>
          <div className="crm-d-flex crm-align-items-center crm-gap-4 crm-mb-3 crm-pt-1">
            <button type="button" className="link crm-fs-8" id="diColsClearBtn" onClick={onClear}>
              Clear selection
            </button>
            <button
              type="button"
              className="link crm-fs-8"
              id="diColsRestoreBtn"
              onClick={onRestore}
            >
              Restore defaults
            </button>
          </div>
          <div className="di-cols-list crm-d-flex crm-flex-column crm-gap-3" id="diColsList">
            {shown.map((c) => (
              <label key={c.key} className={cn('check di-col-item', c.locked && 'is-disabled')}>
                <input
                  type="checkbox"
                  checked={c.locked || draft.includes(c.key)}
                  disabled={c.locked}
                  onChange={(e) => onToggle(c.key, e.target.checked)}
                />
                <span className="check__box" />
                <span className="check__label">{c.label}</span>
              </label>
            ))}
            {shown.length === 0 ? (
              <p className="crm-text-muted crm-fs-8 crm-py-2 crm-m-0" id="diColsNoMatch">
                No columns found.
              </p>
            ) : null}
          </div>
        </div>
        <div className="modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="diColsApplyBtn"
            onClick={onApply}
          >
            Apply
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
