'use client';

// G9 (issue 708), beyond the design: "Bulk edit history" on the Contacts list. It lists the bulk
// edits and owner changes of contacts (yours; an admin's: everyone's) with Undo; Undo previews
// what goes back (GET /property-changes?bulkOperationId=), then queues the undo
// (POST /bulk-operations/:id/undo) and follows it to its end.
import { useCallback, useEffect, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { useListDesign } from '@/features/list-page/listDesign';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { STATUS_TEXT, restoreStamp } from '@/features/list-page/ui/RestoreChangesForm';
import {
  previewPropertyChanges,
  type PropertyChangesPreview,
} from '@/features/property-changes/api.client';
import type { DescribeField } from '@/features/property-history/describe';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  getBulkOperation,
  listBulkOperations,
  undoBulkOperation,
  type BulkOperation,
} from '../api.client';
import {
  canUndoRow,
  editRowState,
  editSummary,
  previewRange,
  previewSummary,
  undoDoneMessage,
} from '../bulkHistory';

/** History catches up 5-15 s after an edit: ask this often, this many times. */
const PENDING_RETRY_MS = 3000;
const PENDING_TRIES = 10;

const contactsText = (n: number) => `${n.toLocaleString()} ${n === 1 ? 'contact' : 'contacts'}`;

export function HistoryList({
  ops,
  now,
  labelOf,
  stamp,
  canUndo,
  loading,
  error,
  hasMore,
  onUndo,
  onRetry,
  onMore,
}: {
  ops: BulkOperation[];
  now: Date;
  labelOf: (field: string) => string;
  stamp: (iso: string) => string;
  /** People who may change contacts; others see the history only. */
  canUndo: boolean;
  loading: boolean;
  error: string | null;
  hasMore: boolean;
  onUndo: (op: BulkOperation) => void;
  onRetry: () => void;
  onMore: () => void;
}) {
  return (
    <div className="lp-bulkhist">
      {error ? (
        <Alert tone="danger">
          {`Couldn't load bulk edits. ${error} `}
          <button type="button" className="lp-link" onClick={onRetry}>
            Retry
          </button>
        </Alert>
      ) : null}
      {!ops.length && !loading && !error ? (
        <p className="lp-bulkhist__empty">No bulk edits yet.</p>
      ) : null}
      {ops.length ? (
        <table className="lp-bulkhist__table">
          <thead>
            <tr>
              <th scope="col">When</th>
              <th scope="col">By</th>
              <th scope="col">Changed</th>
              <th scope="col">Records</th>
              <th scope="col">
                <span className="lp-sr">Undo</span>
              </th>
            </tr>
          </thead>
          <tbody>
            {ops.map((op) => {
              const state = editRowState(op, now);
              return (
                <tr key={op.id}>
                  <td>{stamp(op.createdAt)}</td>
                  <td>{op.createdBy?.name ?? '--'}</td>
                  <td>{editSummary(op, labelOf)}</td>
                  <td>{contactsText(op.succeeded)}</td>
                  <td className="lp-bulkhist__act">
                    {state.text ? (
                      <span className={cn('lp-bulkhist__state', `is-${state.kind}`)}>
                        {state.text}
                      </span>
                    ) : null}
                    {canUndo && canUndoRow(state) ? (
                      <button
                        type="button"
                        className="lp-btn lp-btn--sm"
                        onClick={() => onUndo(op)}
                      >
                        Undo
                      </button>
                    ) : null}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      ) : null}
      {loading ? <p className="lp-bulkhist__empty">Loading…</p> : null}
      {hasMore && !loading ? (
        <button type="button" className="lp-link lp-bulkhist__more" onClick={onMore}>
          Load more
        </button>
      ) : null}
    </div>
  );
}

export function UndoPreviewBody({
  preview,
  error,
  waiting,
  describe,
  stamp,
}: {
  preview: PropertyChangesPreview | null;
  error: string | null;
  /** Field history hasn't caught up with the edit yet. */
  waiting: boolean;
  describe: DescribeField;
  stamp: (iso: string) => string;
}) {
  if (error) return <Alert tone="danger">{error}</Alert>;
  if (waiting || !preview) {
    return <p className="lp-bulkhist__wait">Getting the changes ready…</p>;
  }
  const summary = previewSummary(preview);
  return (
    <>
      <p className="lp-bulkhist__sum">{summary.text}</p>
      {preview.data.length ? (
        <ul className="lp-rc__list lp-bulkhist__chgs" aria-label="Values that go back">
          {preview.data.map((c) => {
            const f = describe(c.field);
            const off = c.status !== 'ready';
            return (
              <li key={c.id} className={cn('lp-rc__chg', off && 'is-off')}>
                <strong className="lp-rc__rec">{c.recordName}</strong>
                <span className="lp-rc__prop">
                  {`${f.label}: `}
                  <s>{f.text(c.to)}</s> → <b>{f.text(c.from)}</b>
                </span>
                <span className="lp-rc__meta">{stamp(c.changedAt)}</span>
                {c.status === 'ready' ? null : (
                  <span className="lp-rc__why">{STATUS_TEXT[c.status]}</span>
                )}
              </li>
            );
          })}
        </ul>
      ) : null}
    </>
  );
}

type Step = 'list' | 'preview' | 'undoing';

/**
 * The dialog. `startWith` (the toast's Undo) opens straight on that edit's preview; `onUndone`
 * reloads the list once an undo has finished.
 */
export function BulkEditHistory({
  open,
  onClose,
  describe,
  canUndo,
  startWith,
  onUndone,
}: {
  open: boolean;
  onClose: () => void;
  describe: DescribeField;
  canUndo: boolean;
  startWith: BulkOperation | null;
  onUndone: () => void;
}) {
  const toast = useToast();
  const zone = useListDesign()?.timeZone;
  const stamp = useCallback((iso: string) => restoreStamp(iso, zone), [zone]);
  const labelOf = useCallback((field: string) => describe(field).label, [describe]);

  const [step, setStep] = useState<Step>('list');
  const [ops, setOps] = useState<BulkOperation[]>([]);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [listError, setListError] = useState<string | null>(null);
  const [target, setTarget] = useState<BulkOperation | null>(null);
  const [preview, setPreview] = useState<PropertyChangesPreview | null>(null);
  const [waiting, setWaiting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [running, setRunning] = useState<BulkOperation | null>(null);
  const [busy, setBusy] = useState(false);
  /** Bumped on close and on each new preview or undo: older answers are dropped. */
  const runRef = useRef(0);
  /**
   * The undo being followed. Closing the dialog doesn't stop it: the undo carries on on the
   * server, so when it ends the list still reloads and the toast still shows.
   */
  const undoRef = useRef(0);
  const openRef = useRef(open);
  openRef.current = open;
  const mountedRef = useRef(true);
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  const load = useCallback((after: string | null) => {
    setLoading(true);
    setListError(null);
    listBulkOperations({
      objectType: 'contact',
      actions: ['update', 'assign_owner'],
      limit: 25,
      ...(after && { cursor: after }),
    })
      .then(
        (page) => {
          setOps((cur) => (after ? [...cur, ...page.data] : page.data));
          setCursor(page.nextCursor);
        },
        (err: unknown) => setListError(errorText(err)),
      )
      .finally(() => setLoading(false));
  }, []);

  const showPreview = useCallback((op: BulkOperation) => {
    const run = ++runRef.current;
    setTarget(op);
    setStep('preview');
    setPreview(null);
    setError(null);
    setWaiting(true);
    const ask = (tries: number) => {
      previewPropertyChanges({
        source: 'crm',
        objectTypes: ['contact'],
        bulkOperationId: op.id,
        ...previewRange(op, new Date()),
      }).then(
        (p) => {
          if (run !== runRef.current) return;
          if (p.pending && tries < PENDING_TRIES) {
            window.setTimeout(() => ask(tries + 1), PENDING_RETRY_MS);
            return;
          }
          setWaiting(false);
          if (p.pending) {
            setError("The changes aren't ready yet. Try again in a minute.");
            return;
          }
          setPreview(p);
        },
        (err: unknown) => {
          if (run !== runRef.current) return;
          setWaiting(false);
          setError(errorText(err));
        },
      );
    };
    ask(1);
  }, []);

  useEffect(() => {
    if (!open) {
      runRef.current++;
      return;
    }
    setStep('list');
    setOps([]);
    setCursor(null);
    setRunning(null);
    setBusy(false);
    setError(null);
    setPreview(null);
    setWaiting(false);
    load(null);
    if (startWith) showPreview(startWith);
    // `startWith` is read when the dialog opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  /** Follows the undo to its end, whether or not the dialog is still open. */
  const follow = (id: string, undo: number, shown: number) => {
    getBulkOperation(id).then(
      (op) => {
        if (!mountedRef.current || undo !== undoRef.current) return;
        // Still the dialog's current step: the same opening, no other preview since.
        const here = openRef.current && shown === runRef.current;
        if (op.status === 'done' || op.status === 'failed') {
          setBusy(false);
          // Some values may be back even when it failed: reload either way.
          onUndone();
          if (op.status === 'failed') {
            const why = op.error ?? 'The undo stopped before it finished';
            if (here) setError(why);
            else toast(why, 'danger', { durationMs: 9000 });
            return;
          }
          toast(undoDoneMessage(op), op.failed ? 'info' : 'success', { durationMs: 8000 });
          if (here) {
            setStep('list');
            load(null);
          }
          return;
        }
        if (here) setRunning(op);
        window.setTimeout(() => follow(id, undo, shown), 1500);
      },
      () => {
        if (mountedRef.current && undo === undoRef.current) {
          window.setTimeout(() => follow(id, undo, shown), 4000);
        }
      },
    );
  };

  const confirm = async () => {
    if (!target) return;
    const shown = ++runRef.current;
    const undo = ++undoRef.current;
    setBusy(true);
    setError(null);
    try {
      const op = await undoBulkOperation(target.id);
      if (!mountedRef.current) return;
      if (openRef.current && shown === runRef.current) {
        setRunning(op);
        setStep('undoing');
      }
      follow(op.id, undo, shown);
    } catch (err) {
      if (!mountedRef.current) return;
      setBusy(false);
      if (openRef.current && shown === runRef.current) setError(errorText(err));
      else toast(errorText(err), 'danger', { durationMs: 9000 });
    }
  };

  const ready = preview ? previewSummary(preview) : null;
  const canConfirm =
    canUndo &&
    !busy &&
    !waiting &&
    !error &&
    preview !== null &&
    (ready!.ready > 0 || preview.capped);

  const footer =
    step === 'list' ? (
      <div className="lp-modal__acts">
        <button type="button" className="lp-btn" onClick={onClose}>
          Close
        </button>
      </div>
    ) : step === 'preview' ? (
      <div className="lp-modal__acts">
        <button
          type="button"
          className="lp-btn lp-btn--primary"
          disabled={!canConfirm}
          onClick={() => void confirm()}
        >
          Undo bulk edit
        </button>
        <button
          type="button"
          className="lp-btn"
          onClick={() => {
            runRef.current++;
            setStep('list');
          }}
        >
          Back
        </button>
      </div>
    ) : (
      <div className="lp-modal__acts">
        <button type="button" className="lp-btn" onClick={onClose}>
          Close
        </button>
      </div>
    );

  return (
    <LpModal
      open={open}
      title={step === 'list' ? 'Bulk edit history' : 'Undo bulk edit'}
      onClose={onClose}
      className="lp-modal--wide lp-modal--bulkhist"
      footer={footer}
    >
      {step === 'list' ? (
        <HistoryList
          ops={ops}
          now={new Date()}
          labelOf={labelOf}
          stamp={stamp}
          canUndo={canUndo}
          loading={loading}
          error={listError}
          hasMore={cursor !== null}
          onUndo={showPreview}
          onRetry={() => load(null)}
          onMore={() => load(cursor)}
        />
      ) : null}
      {step === 'preview' && target ? (
        <>
          <p className="lp-bulkhist__what">
            {`${editSummary(target, labelOf)} on ${contactsText(target.succeeded)}, ${stamp(target.createdAt)}`}
          </p>
          <UndoPreviewBody
            preview={preview}
            error={error}
            waiting={waiting}
            describe={describe}
            stamp={stamp}
          />
        </>
      ) : null}
      {step === 'undoing' ? (
        <div role="status">
          {error ? (
            <Alert tone="danger">{error}</Alert>
          ) : (
            <p className="lp-bulkhist__wait">
              {running?.total
                ? `Undoing ${running.processed.toLocaleString()} of ${running.total.toLocaleString()}…`
                : 'Undoing…'}
            </p>
          )}
        </div>
      ) : null}
    </LpModal>
  );
}
