'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText, isApiError } from '@/lib/api/errors';
import {
  createListFolder,
  listAllLists,
  listFolders,
  updateList,
} from '@/features/lists/api.client';
import { listWorkflowFolders, listWorkflows, moveWorkflows } from '@/features/workflows/api.client';
import {
  archiveUnusedCleanupProperties,
  getAccountCleanupOverview,
  getAccountCleanupPreview,
  getAccountCleanupRule,
  runAccountCleanup,
  updateAccountCleanupRule,
  type AccountCleanupAsset,
  type AccountCleanupFilterCondition,
  type AccountCleanupObjectKey,
  type AccountCleanupPreview,
  type AccountCleanupRule,
} from '../api.client';
import { AccountCleanupFilters } from './AccountCleanupFilters';
import { groupBySuggestion, type FilingItem } from './filing';

const PERIOD_OPTIONS = [
  { value: '3', label: '3 months' },
  { value: '6', label: '6 months' },
  { value: '9', label: '9 months' },
  { value: '12', label: '1 year' },
  { value: '24', label: '2 years' },
  { value: '36', label: '3 years' },
];

/**
 * QA #382: only categories with an asset the cleanup API actually cleans are offered (no
 * HubSpot marketing assets such as blog posts, landing pages or marketing emails).
 */
const CATEGORIES = [
  { id: 'standard' as const, label: 'Standard objects' },
  { id: 'custom' as const, label: 'Custom objects' },
];

type CleanupCategory = (typeof CATEGORIES)[number]['id'];

const SUPPORTED = new Set<string>(['contacts', 'companies', 'deals', 'properties']);

const OBJECT_META: Record<
  string,
  { single: string; plural: string; Single: string; Plural: string }
> = {
  contacts: { single: 'contact', plural: 'contacts', Single: 'Contact', Plural: 'Contacts' },
  companies: { single: 'company', plural: 'companies', Single: 'Company', Plural: 'Companies' },
  deals: { single: 'deal', plural: 'deals', Single: 'Deal', Plural: 'Deals' },
  properties: {
    single: 'property',
    plural: 'properties',
    Single: 'Property',
    Plural: 'Properties',
  },
};

function nextRunText() {
  const now = new Date();
  const next = new Date(now.getFullYear(), now.getMonth() + 1, 1);
  return next.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

function formatUpdated(iso: string) {
  if (!iso || iso.startsWith('1970')) return '—';
  try {
    return new Date(iso).toLocaleString('en-US', {
      month: 'long',
      day: 'numeric',
      year: 'numeric',
      hour: 'numeric',
      minute: '2-digit',
    });
  } catch {
    return iso;
  }
}

const ICONS = {
  back: (
    <svg
      className="crm-me-1"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.2"
      aria-hidden
    >
      <path d="m15 18-6-6 6-6" />
    </svg>
  ),
  sparkles: (
    <svg
      className="lp-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden
    >
      <path d="m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3L12 3z" />
    </svg>
  ),
  ext: (
    <svg
      className="lp-i crm-ms-1"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden
    >
      <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3" />
    </svg>
  ),
  search: (
    <svg
      className="lp-i"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      aria-hidden
    >
      <circle cx="11" cy="11" r="7" />
      <path d="m21 21-4.3-4.3" />
    </svg>
  ),
  clipboard: (
    <svg className="ac-banner-illus" viewBox="0 0 92 92" aria-hidden>
      <rect className="ac-illus-paper" x="16" y="10" width="50" height="70" rx="6" />
      <rect className="ac-illus-clip" x="30" y="4" width="22" height="12" rx="3" />
      <path className="ac-illus-line-dark" d="M26 32h6M26 46h6M26 60h6" />
      <path className="ac-illus-line-accent" d="M38 32h18M38 46h18M38 60h10" />
      <path className="ac-illus-pencil" d="m60 72 22-22 6 6-22 22-9 3z" />
    </svg>
  ),
};

export function AccountCleanupView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const toast = useToast();
  const objectParamRaw = searchParams.get('object') ?? '';
  // Deep links sometimes use singular "lead"; criteria keys are plural.
  const objectParam = objectParamRaw === 'lead' ? 'leads' : objectParamRaw;
  const objectKey = SUPPORTED.has(objectParam) ? objectParam : null;
  const tabParam = searchParams.get('tab') === 'filing' ? 'filing' : 'cleanup';

  const [category, setCategory] = useState<CleanupCategory | null>(null);
  const [section, setSection] = useState<'cleanup' | 'filing'>(tabParam);
  const [assets, setAssets] = useState<AccountCleanupAsset[]>([]);
  const [loading, setLoading] = useState(true);

  const loadOverview = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getAccountCleanupOverview();
      setAssets(res.assets);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    void loadOverview();
  }, [loadOverview]);

  useEffect(() => {
    setSection(tabParam);
  }, [tabParam]);

  const setTabNav = (next: 'cleanup' | 'filing') => {
    setSection(next);
    const q = new URLSearchParams();
    if (next === 'filing') q.set('tab', 'filing');
    router.replace(`/settings/account-cleanup${q.toString() ? `?${q}` : ''}`);
  };

  const openCriteria = (key: string) => {
    if (!SUPPORTED.has(key)) {
      toast('Cleanup for this asset type is not available yet.', 'info');
      return;
    }
    router.push(`/settings/account-cleanup?object=${key}`);
  };

  if (objectKey) {
    return (
      <div className="ac-page crm-p-0" data-ac>
        <CriteriaView
          objectKey={objectKey}
          apiSupported={SUPPORTED.has(objectKey)}
          onBack={() => {
            router.push('/settings/account-cleanup');
            void loadOverview();
          }}
        />
      </div>
    );
  }

  // QA #382: assets the cleanup API supports; the first category that has any is the default.
  const cleanable = assets.filter((a) => a.supported && SUPPORTED.has(a.objectKey));
  const categoryOptions = CATEGORIES.filter((c) => cleanable.some((a) => a.category === c.id)).map(
    (c) => ({ value: c.id, label: c.label }),
  );
  const activeCategory =
    category && categoryOptions.some((c) => c.value === category)
      ? category
      : (categoryOptions[0]?.value ?? 'standard');
  const filtered = cleanable.filter((a) => a.category === activeCategory);

  return (
    <div className="ac-page crm-p-0" data-ac>
      <header className="ac-head">
        <h1 className="ac-title">Account Cleanup</h1>
        <nav className="ac-tabs" role="tablist" aria-label="Account Cleanup navigation">
          <button
            type="button"
            className={section === 'cleanup' ? 'ac-tab is-active' : 'ac-tab'}
            role="tab"
            aria-selected={section === 'cleanup'}
            onClick={() => setTabNav('cleanup')}
          >
            Cleanup
          </button>
          <button
            type="button"
            className={section === 'filing' ? 'ac-tab is-active' : 'ac-tab'}
            role="tab"
            aria-selected={section === 'filing'}
            onClick={() => setTabNav('filing')}
          >
            Filing
          </button>
        </nav>
      </header>

      {section === 'filing' ? (
        <FilingTab />
      ) : (
        <>
          <p className="ac-subheading">
            Automatically delete unused assets &amp; records to keep your account tidy
          </p>

          <section className="ac-banner">
            <div className="ac-banner__left">
              <div className="ac-banner__icon">{ICONS.clipboard}</div>
              <div className="ac-banner__info">
                <h2 className="ac-banner__title">Start tidying up your unused Contacts</h2>
                <p className="ac-banner__desc">
                  Turn on your first Cleanup to keep your account organized. You can customize the
                  criteria to fit your needs.
                </p>
              </div>
            </div>
            <button
              type="button"
              className="dt-btn dt-btn--primary ac-banner__btn"
              onClick={() => openCriteria('contacts')}
            >
              Get started
            </button>
          </section>

          <div className="ac-type-wrap">
            <label className="ac-type-label" htmlFor="ac-type-select">
              Select an Asset or Record type:
            </label>
            <CustomSelect
              id="ac-type-select"
              className="ac-custom-select"
              placeholder="Select an Asset or Record type"
              value={activeCategory}
              options={categoryOptions}
              searchable={false}
              onChange={(v) => {
                if (v) setCategory(v as CleanupCategory);
              }}
            />
          </div>

          <div className="ac-table-card">
            {loading ? (
              <div className="ac-row">
                <span className="ac-row__name crm-text-muted">Loading…</span>
              </div>
            ) : (
              filtered.map((item) => {
                const meta = OBJECT_META[item.objectKey] ?? {
                  single: item.plural,
                  plural: item.plural,
                  Single: item.label,
                  Plural: item.label,
                };
                const statusHtml =
                  item.status === 'active' ? (
                    <>
                      <span className="ac-dot ac-dot--active" />
                      <span>
                        Active · Next cleanup {nextRunText()} · {item.available}{' '}
                        {item.available === 1 ? meta.single : meta.plural} meet criteria
                      </span>
                    </>
                  ) : item.status === 'off' ? (
                    <>
                      <span className="ac-dot" />
                      <span>Off</span>
                    </>
                  ) : (
                    <>
                      <span className="ac-dot" />
                      <span>Not configured</span>
                    </>
                  );

                const badge =
                  item.status !== 'active' && item.available > 0 ? (
                    <span className="ac-row__badge">{item.available} available</span>
                  ) : null;

                const btnLabel =
                  item.status === 'active' || item.status === 'off' ? 'Edit' : 'Set up';

                return (
                  <div className="ac-row" key={item.objectKey}>
                    <span className="ac-row__name">{meta.Plural}</span>
                    <span className="ac-row__status">{statusHtml}</span>
                    <span className="ac-row__badge-wrap">{badge}</span>
                    <span className="ac-row__actions">
                      <button
                        type="button"
                        className={[
                          'dt-btn',
                          'dt-btn--sm',
                          item.status === 'active' ? null : 'dt-btn--primary',
                        ]
                          .filter(Boolean)
                          .join(' ')}
                        onClick={() => openCriteria(item.objectKey)}
                      >
                        {btnLabel}
                      </button>
                    </span>
                  </div>
                );
              })
            )}
          </div>

          <section className="ac-other">
            <h2 className="ac-other__heading">Other ways to organize your account</h2>
            <div className="ac-other__grid">
              <article className="ac-card">
                <div className="ac-card__body">
                  <h3 className="ac-card__title">Resolve alerts on connected apps</h3>
                  <p className="ac-card__desc">
                    Address errors in connected apps to maintain seamless integrations and avoid
                    disruptions.
                  </p>
                </div>
                <Link className="dt-btn dt-btn--sm ac-card__btn" href="/settings/extension">
                  Review app alerts{ICONS.ext}
                </Link>
              </article>
              <article className="ac-card">
                <div className="ac-card__body">
                  <h3 className="ac-card__title">Resolve workflow errors</h3>
                  <p className="ac-card__desc">
                    Review workflows with errors to prevent disruptions to your business processes.
                  </p>
                </div>
                <Link className="dt-btn dt-btn--sm ac-card__btn" href="/workflows">
                  Review affected workflows{ICONS.ext}
                </Link>
              </article>
            </div>
          </section>
        </>
      )}
    </div>
  );
}

type FilingKey = 'segments' | 'workflows';

const FILING_LABELS: Record<FilingKey, { Plural: string; plural: string; single: string }> = {
  segments: { Plural: 'Segments', plural: 'segments', single: 'segment' },
  workflows: { Plural: 'Workflows', plural: 'workflows', single: 'workflow' },
};

const countOf = (n: number, key: FilingKey) =>
  `${n} ${n === 1 ? FILING_LABELS[key].single : FILING_LABELS[key].plural}`;

interface FilingData {
  unfiled: FilingItem[];
  folders: string[];
}

/** Every workflow in no folder (all pages). */
async function unfiledWorkflows(): Promise<FilingItem[]> {
  const out: FilingItem[] = [];
  let cursor: string | undefined;
  for (let page = 0; page < 20; page++) {
    const res = await listWorkflows({ noFolder: true, limit: 100, cursor });
    out.push(...res.data.filter((w) => !w.folder).map((w) => ({ id: w.id, name: w.name })));
    cursor = res.nextCursor ?? undefined;
    if (!cursor) break;
  }
  return out;
}

async function loadFiling(key: FilingKey): Promise<FilingData> {
  if (key === 'segments') {
    const [{ lists }, folders] = await Promise.all([listAllLists(), listFolders()]);
    return {
      unfiled: lists.filter((l) => !l.folder).map((l) => ({ id: l.id, name: l.name })),
      folders: folders.map((f) => f.folder),
    };
  }
  const [unfiled, { folders }] = await Promise.all([unfiledWorkflows(), listWorkflowFolders()]);
  return { unfiled, folders };
}

/** Moves items into a folder (made first for segments when it is new). */
async function fileInto(key: FilingKey, folder: string, ids: string[], known: string[]) {
  if (key === 'workflows') {
    await moveWorkflows(ids, folder);
    return;
  }
  if (!known.some((f) => f.toLowerCase() === folder.toLowerCase())) {
    await createListFolder(folder).catch((err) => {
      if (!(isApiError(err) && err.status === 409)) throw err;
    });
  }
  for (const id of ids) await updateList(id, { folder });
}

function FilingTab() {
  const toast = useToast();
  const [data, setData] = useState<Partial<Record<FilingKey, FilingData>>>({});
  const [loadError, setLoadError] = useState<string | null>(null);
  const [drawer, setDrawer] = useState<FilingKey | null>(null);
  const [expanded, setExpanded] = useState<Record<string, boolean>>({});
  const [checked, setChecked] = useState<Set<string>>(new Set());
  /** Where unmatched items go: an existing folder or a new name. */
  const [otherFolder, setOtherFolder] = useState('');
  const [applying, setApplying] = useState(false);

  const reload = useCallback(async (key: FilingKey) => {
    const next = await loadFiling(key);
    setData((prev) => ({ ...prev, [key]: next }));
    return next;
  }, []);

  useEffect(() => {
    Promise.all((['segments', 'workflows'] as FilingKey[]).map(reload)).catch((err) =>
      setLoadError(errorText(err)),
    );
  }, [reload]);

  const current = drawer ? data[drawer] : undefined;
  const groups = useMemo(
    () => (current ? groupBySuggestion(current.unfiled, current.folders) : []),
    [current],
  );
  const groupKey = (folder: string | null) => folder ?? '\u0000none';

  const openDrawer = (key: FilingKey) => {
    const d = data[key];
    if (!d) return;
    setDrawer(key);
    setExpanded({});
    setOtherFolder('');
    // Matched groups start ticked; the unmatched one needs a folder first.
    setChecked(
      new Set(
        groupBySuggestion(d.unfiled, d.folders)
          .filter((g) => g.folder !== null)
          .map((g) => groupKey(g.folder)),
      ),
    );
  };

  const toApply = groups.filter(
    (g) => checked.has(groupKey(g.folder)) && (g.folder !== null || otherFolder.trim()),
  );

  const apply = async () => {
    if (!drawer || !current || !toApply.length) return;
    setApplying(true);
    let moved = 0;
    try {
      for (const g of toApply) {
        const folder = (g.folder ?? otherFolder).trim();
        await fileInto(
          drawer,
          folder,
          g.items.map((i) => i.id),
          current.folders,
        );
        moved += g.items.length;
      }
      toast(`Filed ${countOf(moved, drawer)}`, 'success');
      setDrawer(null);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setApplying(false);
      await reload(drawer).catch(() => {});
    }
  };

  return (
    <>
      <p className="ac-subheading">
        File your unfiled segments and workflows into folders to keep them organized and easy to
        find.
      </p>
      {loadError ? <p className="field__help su-danger">{loadError}</p> : null}
      <div className="ac-filing-card">
        <div className="ac-filing-header">
          <span>Asset type</span>
          <span>Unfiled</span>
          <span />
        </div>
        {(Object.keys(FILING_LABELS) as FilingKey[]).map((key) => {
          const label = FILING_LABELS[key];
          const d = data[key];
          return (
            <div className="ac-filing-row" key={key} data-filing-row={key}>
              <span className="ac-filing-row__name">{label.Plural}</span>
              <span>
                <span className="ac-unfiled-badge">
                  {d ? `${d.unfiled.length} unfiled` : 'Loading…'}
                </span>
              </span>
              <span>
                <button
                  type="button"
                  className="ac-analyze-btn"
                  disabled={!d || d.unfiled.length === 0}
                  onClick={() => openDrawer(key)}
                >
                  {ICONS.sparkles} File unfiled {label.plural}
                </button>
              </span>
            </div>
          );
        })}
        <div className="ac-filing-row" data-filing-row="forms">
          <span className="ac-filing-row__name">Forms</span>
          <span />
          <span>
            <Link className="ac-organize-btn" href="/forms">
              Organize forms{ICONS.ext}
            </Link>
          </span>
        </div>
      </div>
      {drawer && current ? (
        <div
          className="modal-backdrop modal-backdrop--drawer is-open"
          role="dialog"
          aria-modal="true"
          aria-label={`File unfiled ${FILING_LABELS[drawer].plural}`}
        >
          <div className="modal ac-drawer">
            <header className="ac-drawer__head">
              <div className="ac-drawer__title-wrap">
                {ICONS.sparkles}
                <h2 className="ac-drawer__title">File unfiled {FILING_LABELS[drawer].plural}</h2>
              </div>
              <button
                type="button"
                className="dt-x"
                aria-label="Close"
                onClick={() => setDrawer(null)}
              >
                ×
              </button>
            </header>
            <div className="ac-drawer__body">
              <p className="ac-drawer__summary">
                You have{' '}
                <strong>{countOf(current.unfiled.length, drawer).replace(' ', ' unfiled ')}</strong>
                .
                {current.folders.length
                  ? ' Each is matched to the existing folder whose name it shares the most words with. Tick the groups to file.'
                  : ' There are no folders yet: pick a name for a new one below.'}
              </p>
              <div className="ac-folder-table">
                {groups.map((g) => {
                  const k = groupKey(g.folder);
                  const open = expanded[k] ?? false;
                  return (
                    <div key={k} className="ac-folder-group">
                      <div className="ac-folder-row">
                        <label className="dt-check">
                          <input
                            type="checkbox"
                            checked={checked.has(k)}
                            onChange={(e) =>
                              setChecked((prev) => {
                                const next = new Set(prev);
                                if (e.target.checked) next.add(k);
                                else next.delete(k);
                                return next;
                              })
                            }
                            aria-label={g.folder ?? 'No matching folder'}
                          />
                        </label>
                        <button
                          type="button"
                          className="ac-folder-title-col"
                          onClick={() => setExpanded((prev) => ({ ...prev, [k]: !open }))}
                        >
                          <span className={`ac-caret${open ? 'is-open' : ''}`}>▸</span>
                          <span className="ac-folder-name">{g.folder ?? 'No matching folder'}</span>
                        </button>
                        {g.folder === null ? (
                          <span />
                        ) : (
                          <span className="ac-badge-folder ac-badge-folder--existing">
                            <span className="ac-badge-folder__dot" />
                            <span>Existing</span>
                          </span>
                        )}
                        <span className="ac-folder-count">{g.items.length}</span>
                      </div>
                      {g.folder === null ? (
                        <div className="ac-nested-wrap">
                          <div className="field">
                            <label className="field__label" htmlFor="ac-filing-other">
                              File these into
                            </label>
                            <input
                              id="ac-filing-other"
                              className="input"
                              list="ac-filing-folders"
                              placeholder="Folder name"
                              aria-label="Folder for unmatched items"
                              value={otherFolder}
                              maxLength={100}
                              onChange={(e) => setOtherFolder(e.target.value)}
                            />
                            <p className="field__help">An existing folder, or a new name.</p>
                          </div>
                        </div>
                      ) : null}
                      {open ? (
                        <div className="ac-nested-wrap">
                          {g.items.map((item) => (
                            <div className="ac-nested-row" key={item.id}>
                              <span>{item.name}</span>
                            </div>
                          ))}
                        </div>
                      ) : null}
                    </div>
                  );
                })}
              </div>
              <datalist id="ac-filing-folders">
                {current.folders.map((f) => (
                  <option key={f} value={f} />
                ))}
              </datalist>
            </div>
            <footer className="ac-drawer__foot">
              <button type="button" className="dt-btn" onClick={() => setDrawer(null)}>
                Cancel
              </button>
              <button
                type="button"
                className="dt-btn dt-btn--primary"
                disabled={applying || toApply.length === 0}
                onClick={apply}
              >
                {applying
                  ? 'Filing…'
                  : `File ${countOf(
                      toApply.reduce((n, g) => n + g.items.length, 0),
                      drawer,
                    )}`}
              </button>
            </footer>
          </div>
        </div>
      ) : null}
    </>
  );
}

function CriteriaView({
  objectKey,
  apiSupported,
  onBack,
}: {
  objectKey: string;
  apiSupported: boolean;
  onBack: () => void;
}) {
  const toast = useToast();
  const meta = OBJECT_META[objectKey] ?? {
    single: 'record',
    plural: 'records',
    Single: 'Record',
    Plural: 'Records',
  };
  const [rule, setRule] = useState<AccountCleanupRule | null>(null);
  const [months, setMonths] = useState(6);
  const [filters, setFilters] = useState<AccountCleanupFilterCondition[][]>([]);
  const [preview, setPreview] = useState<AccountCleanupPreview | null>(null);
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [busy, setBusy] = useState(false);
  const [selectedProps, setSelectedProps] = useState<Set<string>>(new Set());
  const PAGE_SIZE = 10;
  const apiKey = apiSupported ? (objectKey as AccountCleanupObjectKey) : null;

  const dirty = useMemo(() => {
    if (!rule) return false;
    return rule.months !== months || JSON.stringify(rule.filters) !== JSON.stringify(filters);
  }, [rule, months, filters]);

  const load = useCallback(async () => {
    if (!apiKey) {
      setRule({
        objectKey: 'contacts',
        enabled: false,
        months: 6,
        filters: [],
        updatedAt: null,
      });
      setPreview({
        data: [],
        total: 0,
        nextCursor: null,
        months: 6,
        rules: [],
      });
      return;
    }
    try {
      const r = await getAccountCleanupRule(apiKey);
      setRule(r);
      setMonths(r.months);
      setFilters(r.filters ?? []);
      const p = await getAccountCleanupPreview({
        objectKey: apiKey,
        months: r.months,
        limit: PAGE_SIZE,
        filters: r.filters ?? [],
      });
      setPreview(p);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  }, [apiKey, toast]);

  useEffect(() => {
    void load();
  }, [load]);

  const refreshPreview = useCallback(
    async (nextMonths = months, q = search, offset = page, nextFilters = filters) => {
      if (!apiKey) return;
      try {
        const p = await getAccountCleanupPreview({
          objectKey: apiKey,
          months: nextMonths,
          limit: PAGE_SIZE,
          cursor: offset ? String(offset * PAGE_SIZE) : undefined,
          q: q || undefined,
          filters: nextFilters,
        });
        setPreview(p);
      } catch (err) {
        toast(errorText(err), 'danger');
      }
    },
    [apiKey, months, page, search, filters, toast],
  );

  useEffect(() => {
    if (!apiKey || !rule) return;
    const t = window.setTimeout(() => {
      void refreshPreview(months, search, page, filters);
    }, 250);
    return () => window.clearTimeout(t);
  }, [apiKey, rule, months, search, page, filters, refreshPreview]);

  const saveRule = async (enabled: boolean, runNow: boolean) => {
    if (!apiKey) {
      toast(`Cleanup automation for ${meta.plural} is not available yet.`, 'info');
      return;
    }
    let hasFilterError = false;
    const withErrors = filters.map((group) =>
      group.map((cond) => {
        const needsVals = cond.op === 'any' || cond.op === 'none' || cond.op === 'equal';
        if (needsVals && !(cond.vals && cond.vals.length)) {
          hasFilterError = true;
          return { ...cond, error: true };
        }
        const rest = { ...cond } as AccountCleanupFilterCondition & { error?: boolean };
        delete rest.error;
        return rest;
      }),
    );
    if (hasFilterError) {
      setFilters(withErrors as AccountCleanupFilterCondition[][]);
      toast('Fix filter errors before continuing.', 'danger');
      return;
    }
    setBusy(true);
    try {
      const saved = await updateAccountCleanupRule({
        objectKey: apiKey,
        enabled,
        months,
        filters: filters.map((group) => group.map(({ prop, op, vals }) => ({ prop, op, vals }))),
      });
      setRule(saved);
      if (runNow) {
        if (apiKey === 'properties' && selectedProps.size > 0) {
          const res = await archiveUnusedCleanupProperties([...selectedProps]);
          toast(`Archived ${res.archived} unused ${meta.plural}`, 'success');
          setSelectedProps(new Set());
        } else {
          const res = await runAccountCleanup({ objectKey: apiKey, runNow: true });
          toast(
            apiKey === 'properties'
              ? `Archived ${res.processed} unused properties`
              : `${meta.Plural} cleanup is on. Next cleanup ${nextRunText()}.` +
                  (res.jobId ? ` Cleanup queued for ${res.matched} matching records.` : ''),
            'success',
          );
        }
      } else {
        toast(
          enabled
            ? `${meta.Plural} cleanup is on. Next cleanup ${nextRunText()}.`
            : `${meta.Plural} cleanup is off`,
          'success',
        );
      }
      await refreshPreview(months, search, 0);
      setPage(0);
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const totalPages = Math.max(1, Math.ceil((preview?.total ?? 0) / PAGE_SIZE));

  return (
    <div className="ac-criteria">
      <button type="button" className="ac-back" onClick={onBack}>
        {ICONS.back}Back
      </button>

      <header className="ac-criteria__head">
        <h1 className="ac-criteria__title">Criteria for {meta.plural} cleanup</h1>
        <p className="ac-criteria__sub">
          Set up your cleanup policy and review {meta.plural} before enabling monthly cleanup.
        </p>
      </header>

      {rule?.enabled ? (
        <div className="ac-active-banner" role="status">
          <div>
            <strong>Monthly cleanup is on</strong>
            Next cleanup on {nextRunText()}. Deleted {meta.plural} can be restored for 90 days from
            Restore records.
          </div>
        </div>
      ) : null}

      <div className="ac-rules">
        <p className="ac-rules__intro">A {meta.single} is considered unused if:</p>
        <ul className="ac-rules__list">
          {(preview?.rules ?? []).map((r) => (
            <li key={r}>{r}</li>
          ))}
        </ul>
      </div>

      {objectKey !== 'properties' ? (
        <>
          <label className="ac-period-label" htmlFor="ac-period">
            Delete unused {meta.plural} after
          </label>
          <CustomSelect
            id="ac-period"
            className="ac-custom-select crm-w-100 crm-mb-5"
            placeholder="Select period"
            value={String(months)}
            options={PERIOD_OPTIONS}
            searchable={false}
            onChange={(v) => {
              setMonths(Number(v));
              setPage(0);
            }}
          />
        </>
      ) : (
        <p className="ac-subheading crm-mb-5">
          Custom properties with no values on live contacts, companies, or deals can be archived.
        </p>
      )}

      {objectKey !== 'properties' ? (
        <AccountCleanupFilters
          objectKey={objectKey}
          objectSingular={meta.single}
          filters={filters}
          onChange={setFilters}
        />
      ) : null}

      <section className="ac-preview">
        <div className="ac-preview__header">
          <h2 className="ac-preview__count">
            {preview?.total
              ? `${preview.total} ${
                  preview.total === 1 ? meta.single : meta.plural
                } meeting the criteria`
              : `No ${meta.plural} meet the criteria`}
          </h2>
          {preview && preview.total > 0 ? (
            <div className="ac-search-box">
              <input
                type="search"
                placeholder={`Search by ${meta.single} name`}
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(0);
                }}
                autoComplete="off"
              />
              {ICONS.search}
            </div>
          ) : null}
        </div>

        {!preview?.total ? (
          <div className="ac-empty-box">
            <p className="crm-text-muted">No {meta.plural} meet the criteria</p>
          </div>
        ) : (
          <div className="ac-table-wrap">
            <table className="ac-data-table">
              <thead>
                <tr>
                  {objectKey === 'properties' ? (
                    <th scope="col">
                      <span className="crm-visually-hidden">Select</span>
                    </th>
                  ) : null}
                  <th scope="col">{meta.Single} name</th>
                  <th scope="col">Updated At</th>
                  <th scope="col">Created By</th>
                </tr>
              </thead>
              <tbody>
                {(preview?.data ?? []).map((row) => (
                  <tr key={row.id}>
                    {objectKey === 'properties' ? (
                      <td>
                        <input
                          type="checkbox"
                          checked={selectedProps.has(row.id)}
                          onChange={(e) => {
                            setSelectedProps((prev) => {
                              const next = new Set(prev);
                              if (e.target.checked) next.add(row.id);
                              else next.delete(row.id);
                              return next;
                            });
                          }}
                          aria-label={`Select ${row.name}`}
                        />
                      </td>
                    ) : null}
                    <td>{row.name}</td>
                    <td>{formatUpdated(row.updatedAt)}</td>
                    <td>{row.ownerName ?? '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {totalPages > 1 ? (
          <div className="lp-pager crm-mt-3">
            <button
              type="button"
              className="dt-btn dt-btn--sm"
              disabled={page <= 0}
              onClick={() => setPage((p) => Math.max(0, p - 1))}
            >
              Previous
            </button>
            <span>
              Page {page + 1} of {totalPages}
            </span>
            <button
              type="button"
              className="dt-btn dt-btn--sm"
              disabled={page + 1 >= totalPages}
              onClick={() => setPage((p) => p + 1)}
            >
              Next
            </button>
          </div>
        ) : null}
      </section>

      <footer className="ac-foot">
        {rule?.enabled ? (
          <button
            type="button"
            className="dt-btn dt-btn--danger crm-me-auto"
            disabled={busy}
            onClick={() => void saveRule(false, false)}
          >
            Turn off
          </button>
        ) : (
          <span className="crm-me-auto" />
        )}
        {objectKey === 'properties' ? (
          <button
            type="button"
            className="dt-btn dt-btn--primary"
            disabled={busy || selectedProps.size === 0}
            onClick={() => void saveRule(true, true)}
          >
            Archive selected
          </button>
        ) : (
          <button
            type="button"
            className="dt-btn dt-btn--primary"
            disabled={busy || (rule?.enabled && !dirty)}
            onClick={() => void saveRule(true, !rule?.enabled)}
          >
            {rule?.enabled ? 'Save changes' : 'Clean up and automate'}
          </button>
        )}
        <button type="button" className="dt-btn" disabled={busy} onClick={onBack}>
          Cancel
        </button>
      </footer>
    </div>
  );
}
