'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { updateCall } from '@/features/activities/api.client';
import { LpBoard, type LpBoardColumn } from '@/features/list-page/ui/LpBoard';
import type { PicklistOption } from '@/features/picklists/api.client';
import { errorText } from '@/lib/api/errors';
import { listCalls } from '../api.client';
import { callDateCell, callTitle } from '../format';
import type { CallRow, ListCallsParams } from '../types';

/** Cards each column loads at a time ("Load more" adds the next ones). */
export const BOARD_PAGE = 25;

type ColumnState = { rows: CallRow[]; total: number; page: number; loading: boolean };

/**
 * The columns a board shows (design calls.php: grouped by call outcome, `meta.groups`): the
 * outcome picklist's active values, in its order. With an outcome filter, the outcomes it leaves
 * out stay as empty columns, as the design's board keeps every group.
 */
export function boardOutcomes(options: PicklistOption[]): PicklistOption[] {
  return options.filter((o) => !o.archived);
}

/**
 * CGL6 (go-live QA #8, beyond the design, whose calls board has the outcome groups only): the
 * column of calls with no outcome, last, under the design's empty-value label (list-page.js
 * `boardValueLabel`), so the board shows every call.
 */
export const NO_OUTCOME = '__none__';
export const NO_OUTCOME_LABEL = '(No value)';

/** The board's column values: the outcomes, then "(No value)" once there are outcomes at all. */
export function boardColumnValues(outcomes: PicklistOption[]): string[] {
  return outcomes.length ? [...outcomes.map((o) => o.value), NO_OUTCOME] : [];
}

/**
 * Whether a column's calls are loaded at all: the outcome filter, if any, includes it. Calls with
 * no outcome never match an outcome filter, so their column is empty under one.
 */
export function columnShown(outcome: string, filtered: readonly string[]): boolean {
  if (outcome === NO_OUTCOME) return filtered.length === 0;
  return filtered.length === 0 || filtered.includes(outcome);
}

/** One column's query: the list's, for that outcome or (CGL6) for calls with none. */
export function columnParams(
  params: ListCallsParams,
  column: string,
  page: number,
): ListCallsParams {
  const base = { ...params, limit: BOARD_PAGE, page };
  if (column !== NO_OUTCOME) return { ...base, outcome: column, noOutcome: undefined };
  return { ...base, outcome: undefined, noOutcome: 'true' };
}

/** The outcome a card dropped in this column gets: none for "(No value)". */
export function movedOutcome(column: string): string | null {
  return column === NO_OUTCOME ? null : column;
}

/** A column's name. */
export function columnLabel(column: string, outcomes: PicklistOption[]): string {
  if (column === NO_OUTCOME) return NO_OUTCOME_LABEL;
  return outcomes.find((o) => o.value === column)?.label ?? column;
}

/**
 * CL4: the Calls board (design list-page.js `renderBoard` with `bdGroup: 'outcome'`). Each column
 * loads its own calls with the page's filters, so its count is the real one; dragging a card to
 * another column changes the call's outcome. Cards show the title, the owner and (CGL6, go-live
 * QA #8) the call's activity date; the design's card shows the last modified date.
 */
export function CallsBoard({
  params,
  outcomes,
  outcomesStatus,
  outcomeFilter,
  timeZone,
  reloadKey,
  canMove,
  onPreview,
  onRows,
  onMoved,
}: {
  /** The list's query (filters, search, sort), without paging. */
  params: ListCallsParams;
  outcomes: PicklistOption[];
  /** Whether the outcome picklist (the columns) has loaded. */
  outcomesStatus: 'loading' | 'ready' | 'error';
  /** The page's outcome filter: other columns stay empty. */
  outcomeFilter: readonly string[];
  timeZone: string;
  reloadKey: number;
  /** Whether the person may change this call (null: no one on this page may move cards). */
  canMove: ((row: CallRow) => boolean) | null;
  onPreview: (id: string) => void;
  /** Every card on the board, so the page's preview can find the call. */
  onRows: (rows: CallRow[]) => void;
  /** A card moved: the page reloads the list's count and the board. */
  onMoved: () => void;
}) {
  const toast = useToast();
  const [columns, setColumns] = useState<Record<string, ColumnState>>({});
  const [movingId, setMovingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const paramsKey = JSON.stringify(params);
  const shown = boardColumnValues(outcomes).filter((v) => columnShown(v, outcomeFilter));
  const shownKey = shown.join('\n');
  const latest = useRef({ params, shown });
  latest.current = { params, shown };
  /** Bumped by each full reload, so a Load more reply for an older query is dropped. */
  const generation = useRef(0);

  /** One column's page of calls. */
  const loadColumn = useCallback(async (outcome: string, page: number, signal?: AbortSignal) => {
    const res = await listCalls(columnParams(latest.current.params, outcome, page), { signal });
    return { rows: res.data, total: res.total ?? res.data.length };
  }, []);

  // Every column again when the query, the outcomes or the page's refresh changes.
  useEffect(() => {
    const ctrl = new AbortController();
    const values = latest.current.shown;
    generation.current += 1;
    setColumns((cur) =>
      Object.fromEntries(
        values.map((v) => [v, { ...(cur[v] ?? { rows: [], total: 0, page: 1 }), loading: true }]),
      ),
    );
    Promise.all(values.map((v) => loadColumn(v, 1, ctrl.signal))).then(
      (pages) => {
        if (ctrl.signal.aborted) return;
        setColumns(
          Object.fromEntries(values.map((v, i) => [v, { ...pages[i]!, page: 1, loading: false }])),
        );
        setError(null);
      },
      (err) => {
        if (ctrl.signal.aborted) return;
        setError(errorText(err));
        setColumns((cur) =>
          Object.fromEntries(Object.entries(cur).map(([k, c]) => [k, { ...c, loading: false }])),
        );
      },
    );
    return () => ctrl.abort();
  }, [paramsKey, shownKey, reloadKey, loadColumn]);

  useEffect(() => {
    onRows(Object.values(columns).flatMap((c) => c.rows));
  }, [columns, onRows]);

  const loadMore = async (outcome: string) => {
    const col = columns[outcome];
    if (!col || col.loading) return;
    const gen = generation.current;
    setColumns((cur) => ({ ...cur, [outcome]: { ...col, loading: true } }));
    try {
      const page = await loadColumn(outcome, col.page + 1);
      if (gen !== generation.current) return;
      setColumns((cur) => {
        const now = cur[outcome] ?? col;
        const seen = new Set(now.rows.map((r) => r.id));
        return {
          ...cur,
          [outcome]: {
            rows: [...now.rows, ...page.rows.filter((r) => !seen.has(r.id))],
            total: page.total,
            page: col.page + 1,
            loading: false,
          },
        };
      });
    } catch (err) {
      if (gen !== generation.current) return;
      toast(errorText(err), 'danger');
      setColumns((cur) => ({ ...cur, [outcome]: { ...col, loading: false } }));
    }
  };

  const move = async (id: string, from: string, to: string) => {
    // One move at a time: the board reloads after each.
    if (from === to || !canMove || movingId) return;
    const row = columns[from]?.rows.find((r) => r.id === id);
    if (!row) return;
    if (!canMove(row)) {
      toast('You can only move calls you may edit', 'danger');
      return;
    }
    setMovingId(id);
    try {
      await updateCall(id, { outcome: movedOutcome(to) });
      toast(`Call outcome set to ${columnLabel(to, outcomes)}`);
      // The page reloads the count and every column (`reloadKey`).
      onMoved();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setMovingId(null);
    }
  };

  const boardColumns: LpBoardColumn[] = boardColumnValues(outcomes).map((value) => {
    const col = columns[value];
    const rows = col?.rows ?? [];
    const total = col?.total ?? 0;
    return {
      id: value,
      name: columnLabel(value, outcomes),
      count: total,
      cards: rows.map((r) => ({
        id: r.id,
        name: callTitle(r),
        // CL6b: the card's name opens the call's page; its eye button the docked preview.
        href: `/calls/${r.id}`,
        lines: [],
        owner: r.owner?.name ?? null,
        meta: callDateCell(r.occurredAt, timeZone),
      })),
      ...(rows.length < total
        ? {
            more: {
              loading: Boolean(col?.loading),
              disabled: Boolean(col?.loading),
              onLoad: () => void loadMore(value),
            },
          }
        : {}),
    };
  });

  return (
    <div className="lp-callsboard">
      {error ? <p className="lp-notes crm-text-danger">{error}</p> : null}
      {outcomesStatus === 'error' ? (
        <p className="lp-notes crm-text-danger">
          Call outcomes could not be loaded. Refresh the page to try again.
        </p>
      ) : null}
      <LpBoard
        columns={boardColumns}
        plural="calls"
        onMove={canMove ? (id, from, to) => void move(id, from, to) : undefined}
        onPreview={onPreview}
        movingId={movingId}
        design={{
          singular: 'call',
          noColumns:
            outcomesStatus === 'loading' ? 'Loading call outcomes…' : 'No call outcomes to show.',
        }}
      />
    </div>
  );
}
