'use client';

import { useMemo, useState } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { formatStamp } from '@/features/objects/record/fields';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { changedByText, type DescribeField } from './describe';
import { DesignHistoryDrawer, type HistoryDesign } from './PropertyHistoryDesign';
import { MAX_ENTRIES, useHistory, type LoadHistory } from './useHistory';

export type { LoadHistory } from './useHistory';
export type { HistoryDesign } from './PropertyHistoryDesign';

export interface PropertyHistoryDrawerProps {
  open: boolean;
  onClose: () => void;
  load: LoadHistory;
  describe: DescribeField;
  /** A field as history names it (`email`, `custom.budget`), or `all`. */
  initialField?: string;
  /** History is read again when this changes, e.g. the record's `updatedAt`. */
  reloadKey?: unknown;
  timeZone?: string;
  /**
   * PH1: the 28 Oct design's drawer (`record-popups-hs.js` `history()`): search, Property /
   * Source / Date filters, a sortable table and pages. Contacts and Companies pass it; without
   * it (Deals, custom records) the drawer is master's.
   */
  design?: HistoryDesign;
}

/**
 * "Property history" (HUB-356) for any record: every change of its properties, or one
 * property's. Opened from the record's menu (all properties) or from a property's history button.
 */
export function PropertyHistoryDrawer({ design, ...props }: PropertyHistoryDrawerProps) {
  return design ? (
    <DesignHistoryDrawer {...props} design={design} />
  ) : (
    <ClassicHistoryDrawer {...props} />
  );
}

/**
 * Master's drawer (HUB-356): every change with the old and new value, when, the source (CRM UI,
 * Import, Workflow…) and who, with a property picker.
 */
function ClassicHistoryDrawer({
  open,
  onClose,
  load,
  describe,
  initialField = 'all',
  reloadKey,
  timeZone,
}: Omit<PropertyHistoryDrawerProps, 'design'>) {
  // The field picked in the drawer, until it closes; then it opens on `initialField` again.
  const [picked, setPicked] = useState<string | null>(null);
  const field = picked ?? initialField;
  // QA #352/#368: change times in the user's date format and time zone, as the record pages.
  const { regionFormat, timeZone: userZone } = useUserPrefs();
  const zone = timeZone ?? userZone;
  // Bumped on close, so the history is read again each time the drawer opens.
  const [round, setRound] = useState(0);
  const close = () => {
    setPicked(null);
    setRound((n) => n + 1);
    onClose();
  };
  const readKey = `${String(reloadKey ?? '')}@${round}`;

  // Every field's changes (for the picker and "All properties"), and the chosen field's own
  // changes read from the API, so an older field's history isn't cut off by MAX_ENTRIES.
  const all = useHistory(open, load, undefined, readKey);
  const one = useHistory(open && field !== 'all', load, field, readKey);
  const view = field === 'all' ? all : one;

  const fields = useMemo(() => {
    const names = [...new Set(all.entries.map((e) => e.field))];
    if (field !== 'all' && !names.includes(field)) names.unshift(field);
    return names.map((name) => ({ name, label: describe(name).label }));
  }, [all.entries, field, describe]);

  const label = field === 'all' ? null : describe(field).label;
  const error = view.error ?? (field === 'all' ? null : all.error);

  return (
    <CrmModal id="propertyHistoryModal" open={open} onClose={close} drawer>
      <ModalHeader
        id="propertyHistoryModal"
        title={label ? `${label} history` : 'Property history'}
        onClose={close}
      />
      <div className="modal__body">
        <div className="field">
          <label className="field__label" htmlFor="propertyHistoryField">
            Property
          </label>
          <select
            className="input"
            id="propertyHistoryField"
            value={field}
            onChange={(e) => setPicked(e.target.value)}
          >
            <option value="all">All properties</option>
            {fields.map((f) => (
              <option key={f.name} value={f.name}>
                {f.label}
              </option>
            ))}
          </select>
        </div>
        {error ? <p className="ev-help ev-help--danger">{error}</p> : null}
        {view.loading ? <p className="ev-help">Loading history…</p> : null}
        {!view.loading && !view.error && view.entries.length === 0 ? (
          <p className="ev-help">
            No changes recorded{label ? ` for ${label}` : ''}. Changes show here a few seconds after
            they are saved.
          </p>
        ) : null}
        {!view.loading ? (
          <ul className="evr-history" aria-label={label ? `${label} history` : 'Property history'}>
            {view.entries.map((e) => {
              const f = describe(e.field);
              const from = f.text(e.from);
              const to = f.text(e.to);
              return (
                <li key={e.id}>
                  {field === 'all' ? (
                    <p className="evr-history__what">
                      <strong>{f.label}</strong>
                    </p>
                  ) : null}
                  <p className="evr-history__value">
                    {e.from === null || e.from === '' ? (
                      to
                    ) : (
                      <>
                        <s>{from}</s> → {to}
                      </>
                    )}
                  </p>
                  <p className="evr-history__meta">
                    {formatStamp(e.changedAt, { region: regionFormat, timeZone: zone })} ·{' '}
                    {changedByText(e)}
                  </p>
                </li>
              );
            })}
          </ul>
        ) : null}
        {!view.loading && view.capped ? (
          <p className="ev-help">Showing the latest {MAX_ENTRIES} changes.</p>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline btn-crm--sm" onClick={close}>
          Close
        </button>
      </div>
    </CrmModal>
  );
}
