'use client';

import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type { DatePrefs } from '@/features/activities/readable';
import { HxCaret, HxIcon } from '@/features/duplicates/design/HxIcon';
import { HxTip } from '@/features/duplicates/design/MergeDesignViews';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { cn } from '@/lib/utils/cn';
import type { DescribeField } from './describe';
import {
  DATE_PRESETS,
  DEFAULT_SORT,
  NO_FILTERS,
  dateFilterText,
  filterPopPlace,
  filterRows,
  filterText,
  historyRows,
  nextSort,
  pageOf,
  pagerNumbers,
  propertyOptions,
  sortRows,
  sourceOptions,
  stampLines,
  stepFocus,
  toggleValue,
  type HistoryFilters,
  type HistoryRow,
  type HistorySort,
  type SortKey,
} from './historyView';
import { MAX_ENTRIES, useHistory, type LoadHistory } from './useHistory';

/** PH1: what the design's drawer needs beyond master's. */
export interface HistoryDesign {
  /** The record's name, for "<Name> - Property history". */
  recordName: string;
  /**
   * EV23: `event` too (record-popups-hs.js:323-325 link the event's own pages); LR1: `lead`;
   * DR5a: `deal`.
   */
  objectType: 'contact' | 'company' | 'event' | 'lead' | 'deal';
  /** May open Settings › Properties (P1 `canOpenPropertySettings`): Manage properties shows (D4). */
  canManageProperties: boolean;
}

type FilterKey = 'prop' | 'src' | 'date';

/**
 * The design's `?object=` keys (`restore-records.php`, read by `RestoreRecordsLive.tsx:29-33`).
 * A custom object goes by its own key, which the Restore page reads as is (`:58-59`).
 */
const PLURAL = {
  contact: 'contacts',
  company: 'companies',
  event: 'event',
  lead: 'lead',
  deal: 'deals',
} as const;

const HEAD_TIP =
  "Property history shows every change to this record's properties, who or what made it, and when.";

export interface DesignHistoryViewProps {
  objectType: HistoryDesign['objectType'];
  canManageProperties: boolean;
  query: string;
  onQuery: (q: string) => void;
  propertyText: string;
  sourceText: string;
  dateText: string;
  openFilter: FilterKey | null;
  onFilter: (key: FilterKey, anchor: HTMLButtonElement) => void;
  sort: HistorySort;
  onSort: (key: SortKey) => void;
  /** This page's rows. */
  rows: HistoryRow[];
  /** Rows the search and filters keep, on every page. */
  total: number;
  page: number;
  pages: number;
  onPage: (page: number) => void;
  loading: boolean;
  error: string | null;
  capped: boolean;
  prefs: DatePrefs;
}

/** The drawer's body (`paint()`, record-popups-hs.js:318-333), from its state. */
export function DesignHistoryView(p: DesignHistoryViewProps) {
  const uid = useId();
  const filter = (key: FilterKey, label: string, text: string) => (
    <span className="hx-filter">
      <span className="hx-filter__l" id={`${uid}f-${key}`}>
        {label}
      </span>
      <button
        type="button"
        className="hx-filter__b"
        aria-haspopup="dialog"
        aria-expanded={p.openFilter === key}
        aria-labelledby={`${uid}f-${key} ${uid}v-${key}`}
        onClick={(e) => p.onFilter(key, e.currentTarget)}
      >
        <span id={`${uid}v-${key}`}>{text}</span>
        <HxCaret />
      </button>
    </span>
  );
  const head = (key: SortKey, label: string) => {
    const on = p.sort.key === key;
    return (
      <th scope="col" aria-sort={on ? (p.sort.dir > 0 ? 'ascending' : 'descending') : 'none'}>
        <button type="button" className="hx-sort" onClick={() => p.onSort(key)}>
          {label}
          <HxIcon name={on ? (p.sort.dir > 0 ? 'up' : 'down') : 'sort'} />
        </button>
      </th>
    );
  };
  return (
    <div className="hx-ph">
      <p className="hx-lead">
        View all the property changes for this record. You can restore property values. Restored
        activity will be recorded in{' '}
        <a
          className="hx-link"
          href={`/recycle-bin?object=${PLURAL[p.objectType]}`}
          target="_blank"
          rel="noopener"
        >
          Backup &amp; Restore.
        </a>
      </p>
      <div className="hx-bar">
        <label className="hx-searchbox hx-searchbox--md">
          <input
            type="search"
            placeholder="Search"
            aria-label="Search property history"
            value={p.query}
            onChange={(e) => p.onQuery(e.target.value)}
          />
          <HxIcon name="search" />
        </label>
        {p.canManageProperties ? (
          <a
            className="btn-crm btn-crm--outline hx-btn-ext"
            href={`/settings/properties?object=${p.objectType}`}
            target="_blank"
            rel="noopener"
          >
            Manage properties
            <HxIcon name="ext" />
          </a>
        ) : null}
      </div>
      <div className="hx-filters">
        {filter('prop', 'Property', p.propertyText)}
        {filter('src', 'Source', p.sourceText)}
        {filter('date', 'Date', p.dateText)}
      </div>
      {p.error ? <p className="ev-help ev-help--danger">{p.error}</p> : null}
      {p.loading ? <p className="ev-help">Loading history…</p> : null}
      {!p.loading && !p.error ? (
        <>
          <div className="hx-tablewrap">
            <table className="hx-table">
              <caption className="hx-sr">Property history, {p.total} changes</caption>
              <thead>
                <tr>
                  {head('prop', 'Property')}
                  <th scope="col">Changed To</th>
                  {head('at', 'Date')}
                  {head('source', 'Source')}
                </tr>
              </thead>
              <tbody>
                {p.rows.length ? (
                  p.rows.map((x) => {
                    const [day, time, zone] = stampLines(x.iso, p.prefs);
                    return (
                      <tr key={x.id}>
                        <td>{x.prop}</td>
                        <td>{x.to}</td>
                        <td className="hx-nowrap">
                          {day}
                          <br />
                          {time}
                          <br />
                          {zone}
                        </td>
                        <td>
                          <span className="hx-src">
                            {x.source}
                            <HxTip text={`Changed by ${x.source.toLowerCase()}`} />
                          </span>
                          {x.person ? (
                            <span className="hx-trunc" title={x.person}>
                              {x.person}
                            </span>
                          ) : null}
                        </td>
                      </tr>
                    );
                  })
                ) : (
                  <tr>
                    <td colSpan={4} className="hx-empty">
                      No property changes match these filters.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
          <nav className="hx-pager" aria-label="Pages">
            <button type="button" disabled={p.page <= 1} onClick={() => p.onPage(p.page - 1)}>
              <HxIcon name="back" />
              Prev
            </button>
            {pagerNumbers(p.page, p.pages).map((n) =>
              n === p.page ? (
                <span key={n} className="hx-pager__n is-on" aria-current="page">
                  {n}
                </span>
              ) : (
                <button
                  key={n}
                  type="button"
                  className="hx-pager__n"
                  aria-label={`Page ${n}`}
                  onClick={() => p.onPage(n)}
                >
                  {n}
                </button>
              ),
            )}
            <button type="button" disabled={p.page >= p.pages} onClick={() => p.onPage(p.page + 1)}>
              Next
              <HxIcon name="right" />
            </button>
          </nav>
        </>
      ) : null}
      {!p.loading && p.capped ? (
        <p className="ev-help">Showing the latest {MAX_ENTRIES} changes.</p>
      ) : null}
    </div>
  );
}

export interface PopItem {
  v: string;
  label: string;
  /** G12: a second line (an owner's email), searched with the label (record-popups-hs.js:108). */
  sub?: string;
}

/** The option's text: its label, and its second line when it has one (:115, :117). */
function popLabel(it: PopItem) {
  return (
    <span>
      {it.label}
      {it.sub ? <small>{it.sub}</small> : null}
    </span>
  );
}

/**
 * The design's filter popover (`filterPop`, record-popups-hs.js:93-176) under a filter button:
 * several values with search and "Deselect all", or one value with "+ Custom date range".
 * Escape closes only the popover (its listener runs first and stops the event, :153, :161).
 */
export function FilterPop({
  anchor,
  label,
  items,
  selected,
  multi,
  search,
  custom,
  onChange,
  onCustom,
  onClose,
}: {
  anchor: HTMLElement;
  label: string;
  items: PopItem[];
  selected: string[];
  multi: boolean;
  search: boolean;
  custom?: boolean;
  onChange: (selected: string[]) => void;
  onCustom?: (from: string, to: string) => void;
  /** `noFocus`: closed by a click elsewhere, so focus stays where it went. */
  onClose: (noFocus?: boolean) => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const fromRef = useRef<HTMLInputElement>(null);
  const toRef = useRef<HTMLInputElement>(null);
  const toast = useToast();
  const [q, setQ] = useState('');
  const [rangeOpen, setRangeOpen] = useState(false);
  const [place, setPlace] = useState<ReturnType<typeof filterPopPlace> | null>(null);
  const closeRef = useRef(onClose);
  closeRef.current = onClose;

  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    setPlace(
      filterPopPlace(
        anchor.getBoundingClientRect(),
        { width: el.offsetWidth, height: el.offsetHeight },
        { width: window.innerWidth, height: window.innerHeight },
      ),
    );
  }, [anchor, rangeOpen]);

  useEffect(() => {
    if (!place) return;
    const el = ref.current;
    if (rangeOpen) fromRef.current?.focus();
    else
      el?.querySelector<HTMLElement>(
        '[data-q], .hx-pop__list input, .hx-pop__list button',
      )?.focus();
    // Focus once placed (and when the custom range opens), as filterPop :147, :174.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [place === null, rangeOpen]);

  useEffect(() => {
    const outside = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!ref.current?.contains(t) && !anchor.contains(t)) closeRef.current(true);
    };
    const key = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        e.preventDefault();
        closeRef.current();
        return;
      }
      const el = ref.current;
      if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && el?.contains(document.activeElement)) {
        const its = [
          ...el.querySelectorAll<HTMLElement>('.hx-pop__list input, .hx-pop__list button'),
        ];
        if (!its.length) return;
        e.preventDefault();
        its[
          stepFocus(
            its.length,
            its.indexOf(document.activeElement as HTMLElement),
            e.key === 'ArrowDown',
          )
        ]?.focus();
      }
    };
    document.addEventListener('mousedown', outside, true);
    window.addEventListener('keydown', key, true);
    return () => {
      document.removeEventListener('mousedown', outside, true);
      window.removeEventListener('keydown', key, true);
    };
  }, [anchor]);

  const needle = q.trim().toLowerCase();
  const shown = items.filter(
    (it) => !needle || `${it.label} ${it.sub ?? ''}`.toLowerCase().includes(needle),
  );
  const apply = () => {
    const from = fromRef.current?.value ?? '';
    const to = toRef.current?.value ?? '';
    if (!from || !to) {
      toast('Choose both dates', 'info');
      return;
    }
    onClose();
    onCustom?.(from, to);
  };

  return createPortal(
    <div
      ref={ref}
      className={cn('hx-pop', place?.up && 'is-up')}
      role="dialog"
      aria-label={label}
      style={{
        left: place?.left ?? 0,
        top: place?.top ?? 0,
        visibility: place ? 'visible' : 'hidden',
      }}
    >
      <span className="hx-pop__arrow" aria-hidden="true" style={{ left: place?.arrowLeft ?? 14 }} />
      {search ? (
        <div className="hx-pop__search">
          <label className="hx-searchbox">
            <input
              type="search"
              placeholder="Search"
              aria-label="Search"
              autoComplete="off"
              data-q=""
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
            <HxIcon name="search" />
          </label>
        </div>
      ) : null}
      <div className="hx-pop__list" role={multi ? 'group' : 'listbox'}>
        {shown.length ? (
          shown.map((it) => {
            const on = selected.includes(it.v);
            return multi ? (
              <label key={it.v} className="hx-pop__opt">
                <input
                  type="checkbox"
                  checked={on}
                  onChange={(e) => onChange(toggleValue(selected, it.v, e.target.checked))}
                />
                {popLabel(it)}
              </label>
            ) : (
              <button
                key={it.v}
                type="button"
                role="option"
                aria-selected={on}
                className={cn('hx-pop__opt hx-pop__opt--single', on && 'is-on')}
                onClick={() => {
                  onClose();
                  onChange([it.v]);
                }}
              >
                {popLabel(it)}
              </button>
            );
          })
        ) : (
          <p className="hx-pop__none">No results found</p>
        )}
      </div>
      {multi ? (
        <button type="button" className="hx-pop__foot" onClick={() => onChange([])}>
          Deselect all
        </button>
      ) : null}
      {custom ? (
        <div className="hx-pop__custom">
          {rangeOpen ? null : (
            <button type="button" className="hx-pop__add" onClick={() => setRangeOpen(true)}>
              + Custom date range
            </button>
          )}
          <div className="hx-pop__range" hidden={!rangeOpen}>
            <label>
              From
              <input type="date" ref={fromRef} />
            </label>
            <label>
              To
              <input type="date" ref={toRef} />
            </label>
            <button type="button" className="btn-crm btn-crm--primary btn-crm--sm" onClick={apply}>
              Apply
            </button>
          </div>
        </div>
      ) : null}
    </div>,
    document.body,
  );
}

interface ViewState {
  q: string;
  filters: HistoryFilters;
  sort: HistorySort;
  page: number;
}

/**
 * PH1: "<Name> - Property history" as the 28 Oct design (record-popups-hs.js:301-355), on the
 * same history reads as master's drawer. One picked property is read through the API's `field`
 * (D3, master's `PropertyHistoryDrawer`), so an older field isn't cut off by the 500 read.
 */
export function DesignHistoryDrawer({
  open,
  onClose,
  load,
  describe,
  initialField = 'all',
  reloadKey,
  timeZone,
  design,
}: {
  open: boolean;
  onClose: () => void;
  load: LoadHistory;
  describe: DescribeField;
  initialField?: string;
  reloadKey?: unknown;
  timeZone?: string;
  design: HistoryDesign;
}) {
  const { regionFormat, timeZone: userZone } = useUserPrefs();
  const zone = timeZone ?? userZone;
  // The view's state until the drawer closes; then it opens on `initialField` again.
  const [picked, setPicked] = useState<ViewState | null>(null);
  const st: ViewState = picked ?? {
    q: '',
    filters: { ...NO_FILTERS, props: initialField !== 'all' ? [initialField] : [] },
    sort: DEFAULT_SORT,
    page: 1,
  };
  const [pop, setPop] = useState<{ key: FilterKey; anchor: HTMLElement } | null>(null);
  // Bumped on close, so the history is read again each time the drawer opens.
  const [round, setRound] = useState(0);
  const close = () => {
    setPicked(null);
    setPop(null);
    setRound((n) => n + 1);
    onClose();
  };
  const readKey = `${String(reloadKey ?? '')}@${round}`;

  const single = st.filters.props.length === 1 ? st.filters.props[0] : undefined;
  const all = useHistory(open, load, undefined, readKey);
  const one = useHistory(open && single !== undefined, load, single, readKey);
  const view = single !== undefined ? one : all;
  const error = view.error ?? (single !== undefined ? all.error : null);

  const allRows = historyRows(all.entries, describe);
  const rows = historyRows(view.entries, describe);
  const kept = sortRows(filterRows(rows, { ...st.filters, q: st.q }, new Date(), zone), st.sort);
  const shown = pageOf(kept, st.page);
  const set = (patch: Partial<ViewState>) => setPicked({ ...st, ...patch });
  const setFilters = (patch: Partial<HistoryFilters>) =>
    set({ filters: { ...st.filters, ...patch }, page: 1 });
  const closePop = (noFocus?: boolean) => {
    const anchor = pop?.anchor;
    setPop(null);
    if (!noFocus && anchor?.isConnected) anchor.focus();
  };

  return (
    <CrmModal id="propertyHistoryModal" open={open} onClose={close} drawer className="ph-drawer">
      <div className="modal__header">
        <h2 className="modal__title" id="propertyHistoryModal-title">
          {`${design.recordName} - Property history`}
        </h2>
        <span className="hx-headtip">
          <HxTip text={HEAD_TIP} />
        </span>
        <button type="button" className="modal__close" aria-label="Close" onClick={close}>
          <CrmIcon name="x" className="iconSize-20" />
        </button>
      </div>
      <div className="modal__body">
        <DesignHistoryView
          objectType={design.objectType}
          canManageProperties={design.canManageProperties}
          query={st.q}
          onQuery={(q) => set({ q, page: 1 })}
          propertyText={filterText(st.filters.props.map((f) => describe(f).label))}
          sourceText={filterText(st.filters.sources)}
          dateText={dateFilterText(st.filters)}
          openFilter={pop?.key ?? null}
          onFilter={(key, anchor) => setPop(pop?.key === key ? null : { key, anchor })}
          sort={st.sort}
          onSort={(key) => set({ sort: nextSort(st.sort, key) })}
          rows={shown.rows}
          total={kept.length}
          page={shown.page}
          pages={shown.pages}
          onPage={(page) => set({ page })}
          loading={view.loading}
          error={error}
          capped={view.capped}
          prefs={{ region: regionFormat, timeZone: zone }}
        />
      </div>
      {open && pop?.key === 'prop' ? (
        <FilterPop
          anchor={pop.anchor}
          label="Filter by property"
          multi
          search
          items={propertyOptions(allRows, st.filters.props, describe)}
          selected={st.filters.props}
          onChange={(props) => setFilters({ props })}
          onClose={closePop}
        />
      ) : null}
      {open && pop?.key === 'src' ? (
        <FilterPop
          anchor={pop.anchor}
          label="Filter by source"
          multi
          search
          items={sourceOptions(allRows).map((s) => ({ v: s, label: s }))}
          selected={st.filters.sources}
          onChange={(sources) => setFilters({ sources })}
          onClose={closePop}
        />
      ) : null}
      {open && pop?.key === 'date' ? (
        <FilterPop
          anchor={pop.anchor}
          label="Filter by date"
          multi={false}
          search={false}
          custom
          items={[{ v: '', label: 'All' }, ...DATE_PRESETS.map(([v, label]) => ({ v, label }))]}
          selected={[st.filters.range ? 'custom' : (st.filters.date ?? '')]}
          onChange={([v]) =>
            setFilters({ date: (v || null) as HistoryFilters['date'], range: null })
          }
          onCustom={(from, to) => setFilters({ range: { from, to }, date: null })}
          onClose={closePop}
        />
      ) : null}
    </CrmModal>
  );
}
