'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  getEnrichmentSettings,
  listEnrichmentActivity,
  updateEnrichmentSettings,
  type EnrichmentActivity,
} from './api.client';
import {
  ACTIVITY_SOURCES,
  ACTIVITY_USERS,
  CONV_ROWS,
  MAP,
  OVERWRITE_RULES,
  SETTINGS_ROWS,
  ruleLabel,
  type FieldType,
  type OverwriteRule,
  type SeObject,
  type SeTab,
} from './data';

const TABS: { id: SeTab; label: string }[] = [
  { id: 'settings', label: 'Settings' },
  { id: 'conversational', label: 'Conversational Enrichment' },
  { id: 'mapping', label: 'Mapping' },
  { id: 'activity', label: 'Activity' },
];

function parseTab(raw: string | null): SeTab {
  if (raw === 'conversational' || raw === 'mapping' || raw === 'activity') return raw;
  return 'settings';
}

function Icon({ d, className = 'se-i' }: { d: string; className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d={d} />
    </svg>
  );
}

const I = {
  building: (
    <svg
      className="se-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M4 21V5a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v16M14 9h5a1 1 0 0 1 1 1v11M3 21h18M8 8h2M8 12h2M8 16h2" />
    </svg>
  ),
  contact: (
    <svg
      className="se-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <rect x="5" y="3" width="14" height="18" rx="2" />
      <circle cx="12" cy="10" r="2.5" />
      <path d="M8.5 16.5a3.5 3.5 0 0 1 7 0" />
    </svg>
  ),
  info: (
    <svg
      className="se-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <circle cx="12" cy="12" r="9" />
      <path d="M12 11v5M12 8h.01" />
    </svg>
  ),
  arrow: <Icon d="M4 12h15M14 6l6 6-6 6" />,
  reset: (
    <svg
      className="se-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M20 11a8 8 0 0 0-14.6-4.5L4 8" />
      <path d="M4 3v5h5" />
      <path d="M4 13a8 8 0 0 0 14.6 4.5L20 16" />
      <path d="M20 21v-5h-5" />
    </svg>
  ),
  search: (
    <svg
      className="se-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <circle cx="11" cy="11" r="7" />
      <path d="m20 20-3.5-3.5" />
    </svg>
  ),
  down: (
    <svg className="se-i se-i--caret" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
      <path d="M6 9h12l-6 7z" />
    </svg>
  ),
  sortDown: <Icon d="M12 4v16M6 14l6 6 6-6" />,
  sort: <Icon d="M8 4v16M4 16l4 4 4-4M16 20V4M12 8l4-4 4 4" />,
  x: <Icon d="M18 6 6 18M6 6l12 12" />,
};

function FieldTypeIcon({ type }: { type: FieldType }) {
  if (type === 'text')
    return (
      <span className="se-ft" aria-hidden>
        Abc
      </span>
    );
  if (type === 'enum') {
    return (
      <svg
        className="se-i se-ft-i"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden
      >
        <rect x="7" y="4" width="13" height="13" rx="2" />
        <path d="M4 8v11a1 1 0 0 0 1 1h11M10 10.5l2 2 4-4" />
      </svg>
    );
  }
  if (type === 'number') {
    return (
      <svg
        className="se-i se-ft-i"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden
      >
        <path d="M5 9h15M4 15h15M10 4 8 20M16 4l-2 16" />
      </svg>
    );
  }
  if (type === 'bool') {
    return (
      <svg
        className="se-i se-ft-i"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden
      >
        <rect x="4" y="4" width="16" height="16" rx="3" />
        <path d="m8 12 3 3 5-6" />
      </svg>
    );
  }
  return (
    <svg
      className="se-i se-ft-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <rect x="4" y="5" width="16" height="15" rx="2" />
      <path d="M4 10h16M9 3v4M15 3v4" />
    </svg>
  );
}

function Tip({ label, tip }: { label: string; tip: string }) {
  return (
    <span className="se-tip" tabIndex={0} role="img" aria-label={label} data-tip={tip}>
      {I.info}
    </span>
  );
}

function Switch({
  checked,
  label,
  onChange,
}: {
  checked: boolean;
  label: string;
  onChange: (next: boolean) => void;
}) {
  return (
    <label className="se-sw">
      <input
        type="checkbox"
        role="switch"
        checked={checked}
        aria-label={label}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className="se-sw__track" aria-hidden />
      <span className="se-sw__t" aria-hidden>
        {checked ? 'ON' : 'OFF'}
      </span>
    </label>
  );
}

type PopItem = [string, string];

function usePopover() {
  const [open, setOpen] = useState<{
    btn: HTMLElement;
    items: PopItem[];
    cur: string | string[];
    multi?: boolean;
    width?: number;
    onPick: (v: string, on?: boolean) => void;
  } | null>(null);

  const close = useCallback(() => setOpen(null), []);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (open.btn.contains(t)) return;
      const pop = document.querySelector('.se-pop');
      if (pop?.contains(t)) return;
      close();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close();
    };
    document.addEventListener('mousedown', onDown, true);
    window.addEventListener('keydown', onKey);
    window.addEventListener('resize', close);
    return () => {
      document.removeEventListener('mousedown', onDown, true);
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', close);
    };
  }, [open, close]);

  const popEl = open ? (
    <Popover
      btn={open.btn}
      items={open.items}
      cur={open.cur}
      multi={open.multi}
      width={open.width}
      onPick={(v, on) => {
        if (open.multi) {
          open.onPick(v, on);
          setOpen((prev) => {
            if (!prev || !Array.isArray(prev.cur)) return prev;
            const next = on
              ? prev.cur.includes(v)
                ? prev.cur
                : [...prev.cur, v]
              : prev.cur.filter((x) => x !== v);
            return { ...prev, cur: next };
          });
          return;
        }
        open.onPick(v);
        close();
      }}
      onClose={close}
    />
  ) : null;

  return { open, setOpen, close, popEl };
}

function Popover({
  btn,
  items,
  cur,
  multi,
  width,
  onPick,
  onClose,
}: {
  btn: HTMLElement;
  items: PopItem[];
  cur: string | string[];
  multi?: boolean;
  width?: number;
  onPick: (v: string, on?: boolean) => void;
  onClose: () => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const r = btn.getBoundingClientRect();
    const w = Math.max(width || 0, r.width);
    el.style.minWidth = `${w}px`;
    const left = Math.min(r.left, window.innerWidth - el.offsetWidth - 8);
    let top = r.bottom + 4;
    if (top + el.offsetHeight > window.innerHeight - 8) {
      top = Math.max(8, r.top - el.offsetHeight - 4);
    }
    el.style.left = `${Math.max(8, left)}px`;
    el.style.top = `${top}px`;
    (el.querySelector('.is-on') as HTMLElement | null)?.focus() ??
      (el.querySelector('[data-v]') as HTMLElement | null)?.focus();
  }, [btn, width]);

  return (
    <div
      ref={ref}
      className="se-pop"
      role="listbox"
      aria-multiselectable={multi || undefined}
      onKeyDown={(e) => {
        const its = [...e.currentTarget.querySelectorAll<HTMLElement>('[data-v]')];
        const i = its.indexOf(document.activeElement as HTMLElement);
        if (e.key === 'Escape') {
          e.preventDefault();
          onClose();
          btn.focus();
        }
        if (e.key === 'ArrowDown') {
          e.preventDefault();
          its[(i + 1) % its.length]?.focus();
        }
        if (e.key === 'ArrowUp') {
          e.preventDefault();
          its[i <= 0 ? its.length - 1 : i - 1]?.focus();
        }
      }}
    >
      {items.map(([v, label]) => {
        const on = multi ? (cur as string[]).includes(v) : cur === v;
        return (
          <button
            key={v || '__all'}
            type="button"
            className={cn('se-pop__item', on && 'is-on')}
            role="option"
            aria-selected={on}
            data-v={v}
            onClick={() => {
              if (multi) onPick(v, !on);
              else onPick(v);
            }}
          >
            {multi ? <span className="se-pop__chk" aria-hidden /> : null}
            {label}
          </button>
        );
      })}
    </div>
  );
}

function fmtWhen(iso: string): [string, string] {
  const d = new Date(iso);
  return [
    d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
    d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' }).toLowerCase(),
  ];
}

export function DataEnrichmentSettingsView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const toast = useToast();
  const tab = parseTab(searchParams.get('tab'));
  const objectType: SeObject = searchParams.get('objectType') === 'company' ? 'company' : 'contact';

  const [switches, setSwitches] = useState<Record<string, boolean>>({});
  const [rules, setRules] = useState<Record<string, OverwriteRule>>({});
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [mapQ, setMapQ] = useState('');
  const [actSrc, setActSrc] = useState<string[]>([]);
  const [actDays, setActDays] = useState(60);
  const [actUser, setActUser] = useState('');
  const [actObj, setActObj] = useState<'all' | 'contact' | 'company'>('all');
  const [actPage, setActPage] = useState(1);
  const [actPer, setActPer] = useState(25);
  const [actDir, setActDir] = useState<'asc' | 'desc'>('desc');
  const [activityRows, setActivityRows] = useState<EnrichmentActivity[]>([]);
  const [activityTotal, setActivityTotal] = useState(0);
  const [activityLoading, setActivityLoading] = useState(false);
  const [detail, setDetail] = useState<EnrichmentActivity | null>(null);
  const { setOpen, close: closePop, popEl } = usePopover();

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    getEnrichmentSettings()
      .then((settings) => {
        if (cancelled) return;
        setSwitches(settings.switches);
        setRules(settings.rules);
        setLoadError(null);
      })
      .catch((err) => {
        if (cancelled) return;
        setLoadError(errorText(err));
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const reloadActivity = useCallback(async () => {
    setActivityLoading(true);
    try {
      const result = await listEnrichmentActivity({
        days: actDays,
        sources: actSrc,
        user: actUser || undefined,
        objectType: actObj,
        sort: actDir,
        limit: actPer,
        page: actPage,
      });
      setActivityRows(result.data);
      setActivityTotal(result.total ?? result.data.length);
    } catch (err) {
      toast(errorText(err), 'danger');
      setActivityRows([]);
      setActivityTotal(0);
    } finally {
      setActivityLoading(false);
    }
  }, [actDays, actSrc, actUser, actObj, actDir, actPer, actPage, toast]);

  useEffect(() => {
    if (tab !== 'activity') return;
    void reloadActivity();
  }, [tab, reloadActivity]);

  const setTab = (next: SeTab, obj?: SeObject) => {
    const params = new URLSearchParams();
    if (next !== 'settings') params.set('tab', next);
    if (next === 'mapping') params.set('objectType', obj ?? objectType);
    const q = params.toString();
    router.replace(q ? `/settings/data-enrichment?${q}` : '/settings/data-enrichment');
  };

  const swOn = (key: string, def: boolean) => (switches[key] != null ? switches[key] : def);

  const setSw = async (key: string, on: boolean) => {
    if (saving) return;
    const prev = switches;
    setSwitches({ ...switches, [key]: on });
    setSaving(true);
    try {
      const saved = await updateEnrichmentSettings({ switches: { [key]: on } });
      setSwitches(saved.switches);
      setRules(saved.rules);
      toast('Enrichment settings saved', 'success');
    } catch (err) {
      setSwitches(prev);
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const setRule = async (key: string, value: OverwriteRule | null, def: OverwriteRule) => {
    if (saving) return;
    const prev = rules;
    const next = { ...rules };
    if (value === null || value === def) delete next[key];
    else next[key] = value;
    setRules(next);
    setSaving(true);
    try {
      const saved = await updateEnrichmentSettings({
        rules: { [key]: value === def ? null : value },
      });
      setSwitches(saved.switches);
      setRules(saved.rules);
      toast(
        value === null || value === def
          ? `${key.split('|')[1]} reset to the default rule`
          : 'Overwrite rule updated',
        'success',
      );
    } catch (err) {
      setRules(prev);
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const mapRows = MAP[objectType];
  const visibleMap = useMemo(() => {
    const q = mapQ.trim().toLowerCase();
    return mapRows.filter((m) => !q || m[0].toLowerCase().includes(q));
  }, [mapRows, mapQ]);

  const actPages = Math.max(1, Math.ceil(activityTotal / actPer));
  const page = Math.min(actPage, actPages);
  const pageRows = activityRows;

  const srcLbl = !actSrc.length
    ? 'Sources'
    : actSrc.length === 1
      ? actSrc[0]
      : `${actSrc.length} sources`;

  if (loading) {
    return (
      <div className="se">
        <header className="se-head">
          <h1 className="se-head__title">Data Enrichment</h1>
          <p className="se-head__sub">These settings will apply to all users in your account.</p>
        </header>
      </div>
    );
  }

  if (loadError) {
    return (
      <div className="se">
        <header className="se-head">
          <h1 className="se-head__title">Data Enrichment</h1>
          <p className="se-head__sub">{loadError}</p>
        </header>
      </div>
    );
  }

  return (
    <div className="se" data-se>
      <header className="se-head">
        <h1 className="se-head__title">Data Enrichment</h1>
        <p className="se-head__sub">These settings will apply to all users in your account.</p>
      </header>

      <nav className="se-tabs" role="tablist" aria-label="Data Enrichment">
        {TABS.map((t) => {
          const on = tab === t.id;
          const href =
            t.id === 'settings'
              ? '/settings/data-enrichment'
              : t.id === 'mapping'
                ? `/settings/data-enrichment?tab=mapping&objectType=${objectType}`
                : `/settings/data-enrichment?tab=${t.id}`;
          return (
            <Link
              key={t.id}
              className={cn('se-tab', on && 'is-on')}
              role="tab"
              aria-selected={on}
              href={href}
              onClick={(e) => {
                e.preventDefault();
                setTab(t.id);
              }}
            >
              {t.label}
            </Link>
          );
        })}
      </nav>

      {tab === 'settings' ? (
        <section role="tabpanel" aria-label="Settings">
          <div className="se-intro">
            <div>
              <h2 className="se-h2">Enrichment settings</h2>
              <p className="se-p">Choose how the CRM updates records with enriched data.</p>
              <p className="se-p se-p--muted">
                Enrichment runs when you use Enrich from a bulk action on Companies or Contacts. It
                does not run automatically when a record is created.
              </p>
              <p className="se-p se-p--muted">
                By using enrichment tools in the CRM (Enrichment, Data Tests, and similar features),
                you confirm that you understand the &quot;Enrichment Products&quot; terms in your
                Agreement apply.
              </p>
            </div>
            <div className="se-colh">
              <span>{I.building}Companies</span>
              <span>{I.contact}Contacts</span>
            </div>
          </div>
          <div className="se-card">
            {SETTINGS_ROWS.map((r, i) => {
              const sep = i > 0 && !r[5];
              const cell = (def: boolean | null, which: 'companies' | 'contacts') => (
                <div className="se-cell" data-l={which === 'companies' ? 'Companies' : 'Contacts'}>
                  {def == null ? null : (
                    <Switch
                      checked={swOn(`${r[0]}.${which}`, def)}
                      label={`${r[1]} for ${which}`}
                      onChange={(on) => void setSw(`${r[0]}.${which}`, on)}
                    />
                  )}
                </div>
              );
              return (
                <div key={r[0]}>
                  {sep ? <hr className="se-sep" /> : null}
                  <div className={cn('se-row', r[5] && 'se-row--sub')}>
                    <div className="se-row__txt">
                      <strong>{r[1]}</strong>
                      <p>{r[2]}</p>
                    </div>
                    {cell(r[3], 'companies')}
                    {cell(r[4], 'contacts')}
                  </div>
                </div>
              );
            })}
          </div>
        </section>
      ) : null}

      {tab === 'conversational' ? (
        <section role="tabpanel" aria-label="Conversational Enrichment">
          <h2 className="se-h2">Conversational Enrichment</h2>
          <p className="se-p">
            Leverage AI to process conversation data to find insights and automatically update
            associated records.
          </p>
          <div className="se-card se-card--conv">
            {CONV_ROWS.map((r, i) => (
              <div key={r[0]}>
                {i ? <hr className="se-sep" /> : null}
                <div className="se-row se-row--one">
                  <div className="se-row__txt">
                    <strong>
                      {r[1]} <Tip label={r[2]} tip={r[2]} />
                    </strong>
                    <p>{r[2]}</p>
                  </div>
                  <div className="se-cell">
                    <Switch
                      checked={swOn(`conv.${r[0]}`, r[3])}
                      label={r[1]}
                      onChange={(on) => void setSw(`conv.${r[0]}`, on)}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </section>
      ) : null}

      {tab === 'mapping' ? (
        <section role="tabpanel" aria-label="Mapping">
          <h2 className="se-h2">Mapping</h2>
          <p className="se-p">Configure how enrichment properties map to your CRM properties.</p>
          <div className="se-mapbar">
            <label className="se-search">
              <span className="crm-visually-hidden">Search properties</span>
              <input
                type="search"
                placeholder="Search"
                value={mapQ}
                autoComplete="off"
                onChange={(e) => setMapQ(e.target.value)}
              />
              {I.search}
            </label>
            <span className="se-chip">{mapRows.length} standard properties</span>
            <span className="se-chip se-chip--dark">0 custom properties</span>
            <span className="se-spacer" />
            <div className="se-seg" role="radiogroup" aria-label="Object">
              <button
                type="button"
                role="radio"
                aria-checked={objectType === 'contact'}
                onClick={() => {
                  setMapQ('');
                  setTab('mapping', 'contact');
                }}
              >
                Contacts
              </button>
              <button
                type="button"
                role="radio"
                aria-checked={objectType === 'company'}
                onClick={() => {
                  setMapQ('');
                  setTab('mapping', 'company');
                }}
              >
                Companies
              </button>
            </div>
          </div>
          <div className="se-tablewrap">
            <table className="se-table se-maptable">
              <thead>
                <tr>
                  <th scope="col">Enrichment Property</th>
                  <th scope="col">
                    <span className="crm-visually-hidden">maps to</span>
                  </th>
                  <th scope="col">CRM Property</th>
                  <th scope="col" className="se-sticky">
                    Overwrite Rule
                  </th>
                </tr>
              </thead>
              <tbody>
                {visibleMap.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="se-empty">
                      No properties match your search.
                    </td>
                  </tr>
                ) : (
                  visibleMap.map(([label, ft, def]) => {
                    const key = `${objectType}|${label}`;
                    const v = rules[key] ?? def;
                    const changed = v !== def;
                    return (
                      <tr key={key}>
                        <td>
                          <span className="se-prop">
                            <FieldTypeIcon type={ft} />
                            {label}
                          </span>
                        </td>
                        <td className="se-arrowc">{I.arrow}</td>
                        <td>
                          <span className="se-crmprop" title={label}>
                            <FieldTypeIcon type={ft} />
                            <span>{label}</span>
                          </span>
                        </td>
                        <td className="se-sticky">
                          <div className="se-rule">
                            <button
                              type="button"
                              className="se-dd"
                              aria-haspopup="listbox"
                              aria-expanded="false"
                              disabled={saving}
                              aria-label={`Overwrite rule for ${label}: ${ruleLabel(v)}`}
                              onClick={(e) => {
                                const btn = e.currentTarget;
                                setOpen({
                                  btn,
                                  items: OVERWRITE_RULES,
                                  cur: v,
                                  width: 320,
                                  onPick: (next) => {
                                    void setRule(key, next as OverwriteRule, def);
                                  },
                                });
                              }}
                            >
                              <span>{ruleLabel(v)}</span>
                              {I.down}
                            </button>
                            <button
                              type="button"
                              className="se-reset"
                              aria-label={`Reset ${label} to the default rule`}
                              title="Reset to default"
                              disabled={!changed || saving}
                              onClick={() => {
                                void setRule(key, null, def);
                              }}
                            >
                              {I.reset}
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </section>
      ) : null}

      {tab === 'activity' ? (
        <section role="tabpanel" aria-label="Activity">
          <h2 className="se-h2">Enrichment Activity</h2>
          <p className="se-p">
            Gain complete transparency into your data enrichment. The activity log shows exactly
            what, when, why, and how your records are being enhanced.
          </p>
          <div className="se-actbar">
            <button
              type="button"
              className="se-plain"
              aria-haspopup="listbox"
              onClick={(e) => {
                const btn = e.currentTarget;
                setOpen({
                  btn,
                  items: ACTIVITY_SOURCES.map((s) => [s, s]),
                  cur: actSrc,
                  multi: true,
                  width: 220,
                  onPick: (v, on) => {
                    setActSrc((prev) => {
                      if (on) return prev.includes(v) ? prev : [...prev, v];
                      return prev.filter((x) => x !== v);
                    });
                    setActPage(1);
                  },
                });
              }}
            >
              {srcLbl}
              {I.down}
            </button>
            <button
              type="button"
              className="se-plain"
              aria-haspopup="listbox"
              onClick={(e) => {
                const btn = e.currentTarget;
                setOpen({
                  btn,
                  items: [
                    ['7', 'Last 7 days'],
                    ['30', 'Last 30 days'],
                    ['60', 'Last 60 days'],
                  ],
                  cur: String(actDays),
                  onPick: (v) => {
                    setActDays(Number(v));
                    setActPage(1);
                    closePop();
                  },
                });
              }}
            >
              Last {actDays} days
              {I.down}
            </button>
            <button
              type="button"
              className="se-plain"
              aria-haspopup="listbox"
              onClick={(e) => {
                const btn = e.currentTarget;
                setOpen({
                  btn,
                  items: [['', 'All users'], ...ACTIVITY_USERS.map((u) => [u, u] as PopItem)],
                  cur: actUser,
                  width: 200,
                  onPick: (v) => {
                    setActUser(v);
                    setActPage(1);
                  },
                });
              }}
            >
              {actUser || 'All users'}
              {I.down}
            </button>
            <span className="se-chip">{activityLoading ? '…' : `${activityTotal} results`}</span>
            <span className="se-spacer" />
            <div className="se-seg" role="radiogroup" aria-label="Object">
              {(
                [
                  ['all', 'All'],
                  ['contact', 'Contacts'],
                  ['company', 'Companies'],
                ] as const
              ).map(([v, label]) => (
                <button
                  key={v}
                  type="button"
                  role="radio"
                  aria-checked={actObj === v}
                  onClick={() => {
                    setActObj(v);
                    setActPage(1);
                  }}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>
          <div className="se-tablewrap">
            <table className="se-table se-acttable">
              <thead>
                <tr>
                  <th scope="col" aria-sort={actDir === 'desc' ? 'descending' : 'ascending'}>
                    <button
                      type="button"
                      className="se-sortbtn"
                      onClick={() => setActDir((d) => (d === 'desc' ? 'asc' : 'desc'))}
                    >
                      Timestamp{' '}
                      <Tip
                        label="The time when the enrichment activity completed."
                        tip="The time when the enrichment activity completed. Shown in your portal's timezone."
                      />
                      {I.sortDown}
                    </button>
                  </th>
                  <th scope="col">Source {I.sort}</th>
                  <th scope="col">User {I.sort}</th>
                  <th scope="col">
                    Records{' '}
                    <Tip
                      label="The count of records that were enriched."
                      tip="The count of records that were enriched, and records the system attempted to enrich but skipped."
                    />{' '}
                    {I.sort}
                  </th>
                  <th scope="col">Type {I.sort}</th>
                  <th scope="col" className="se-sticky">
                    <span className="crm-visually-hidden">Details</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {pageRows.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="se-empty">
                      {activityLoading
                        ? 'Loading enrichment activity…'
                        : 'No enrichment activity matches these filters.'}
                    </td>
                  </tr>
                ) : (
                  pageRows.map((a) => {
                    const [day, time] = fmtWhen(a.occurredAt);
                    const typeLabel = a.objectType === 'company' ? 'Company' : 'Contact';
                    return (
                      <tr key={a.id}>
                        <td>
                          <span className="se-when">
                            {day}
                            <small>{time}</small>
                          </span>
                        </td>
                        <td>
                          <span className="se-tag">{a.source}</span>
                        </td>
                        <td>{a.performedBy.name}</td>
                        <td>
                          <span className="se-recs">
                            <button
                              type="button"
                              className="se-reclink"
                              title={a.recordLabel}
                              onClick={() => setDetail(a)}
                            >
                              {a.recordLabel}
                            </button>
                            <small>
                              {a.recordCount} record{a.recordCount === 1 ? '' : 's'}
                            </small>
                          </span>
                        </td>
                        <td>{typeLabel}</td>
                        <td className="se-sticky">
                          <button
                            type="button"
                            className="se-btn se-btn--sm"
                            onClick={() => setDetail(a)}
                          >
                            Details
                          </button>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
          <nav className="se-pager" aria-label="Pages">
            <button
              type="button"
              className="se-pg"
              disabled={page <= 1}
              onClick={() => setActPage(page - 1)}
            >
              ‹ Prev
            </button>
            {actPages > 1 ? (
              <span className="se-pg__n" aria-current="page">
                {page}
              </span>
            ) : null}
            <button
              type="button"
              className="se-pg"
              disabled={page >= actPages}
              onClick={() => setActPage(page + 1)}
            >
              Next ›
            </button>
            <button
              type="button"
              className="se-plain"
              aria-haspopup="listbox"
              onClick={(e) => {
                const btn = e.currentTarget;
                setOpen({
                  btn,
                  items: [
                    ['25', '25 per page'],
                    ['50', '50 per page'],
                    ['100', '100 per page'],
                  ],
                  cur: String(actPer),
                  onPick: (v) => {
                    setActPer(Number(v));
                    setActPage(1);
                  },
                });
              }}
            >
              {actPer} per page
              {I.down}
            </button>
          </nav>
        </section>
      ) : null}

      {detail ? <DetailsDrawer row={detail} onClose={() => setDetail(null)} /> : null}
      {popEl}
    </div>
  );
}

function DetailsDrawer({ row, onClose }: { row: EnrichmentActivity; onClose: () => void }) {
  const [day, time] = fmtWhen(row.occurredAt);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey, true);
    return () => document.removeEventListener('keydown', onKey, true);
  }, [onClose]);

  return (
    <div className="se-dov" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <aside className="se-drawer" role="dialog" aria-modal="true" aria-labelledby="seDT">
        <header className="se-drawer__head">
          <h2 id="seDT">Enrichment details</h2>
          <button type="button" className="se-x" aria-label="Close" onClick={onClose}>
            {I.x}
          </button>
        </header>
        <div className="se-drawer__body">
          <dl className="se-dl">
            <div>
              <dt>Timestamp</dt>
              <dd>
                {day} {time}
              </dd>
            </div>
            <div>
              <dt>Source</dt>
              <dd>
                <span className="se-tag">{row.source}</span>
              </dd>
            </div>
            <div>
              <dt>User</dt>
              <dd>{row.performedBy.name}</dd>
            </div>
            <div>
              <dt>Records</dt>
              <dd>
                {row.recordLabel} ({row.recordCount} record{row.recordCount === 1 ? '' : 's'})
              </dd>
            </div>
            <div>
              <dt>Type</dt>
              <dd>{row.objectType === 'company' ? 'Company' : 'Contact'}</dd>
            </div>
          </dl>
          <h3 className="se-h3">Properties updated</h3>
          <ul className="se-list">
            {row.properties.map((p) => (
              <li key={p}>{p}</li>
            ))}
          </ul>
          <p className="se-p se-p--muted">
            Enriched values only fill properties allowed by the overwrite rules on the Mapping tab.
          </p>
        </div>
        <footer className="se-drawer__foot">
          <button type="button" className="se-btn" onClick={onClose}>
            Close
          </button>
        </footer>
      </aside>
    </div>
  );
}
