'use client';

import { useCallback, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { listWorkflowActionLogs } from '@/features/workflows/api.client';
import type { WorkflowActionLogRow, WorkflowActionResult } from '@/features/workflows/types';
import { useRecordSearch } from '@/features/workflows/useRecordSearch';
import { useCursorList } from '@/lib/hooks/useCursorList';
import { ResultBadge } from './EnrollmentDrawer';
import { outcomeText } from './outcome';
import { HistoryEmpty, HistorySearch, HistorySelect, Pager } from './RunHistoryTab';
import { ACTION_LABELS, RecordLink, formatWhen } from './shared';

const PAGE_SIZE = 50;

const RESULT_OPTIONS = [
  { value: '', label: 'All results' },
  { value: 'success', label: 'Succeeded' },
  { value: 'failed', label: 'Failed' },
  { value: 'skipped', label: 'Skipped' },
];

const ACTION_OPTIONS = [
  { value: '', label: 'All actions' },
  ...Object.entries(ACTION_LABELS).map(([value, label]) => ({ value, label })),
  { value: 'branch', label: 'Branch' },
];

/**
 * Action logs view of the workflow editor (HUB-262, design workflow-editor.php?tab=logs): what
 * every step did for every record, newest first, by record, result and action
 * (GET /workflows/:id/action-logs, HUB-260).
 */
export function ActionLogsView({
  workflowId,
  objectType,
  timeZone,
  stepLabel,
  onOpen,
}: {
  workflowId: string;
  objectType: string;
  timeZone: string;
  stepLabel: (stepId: string) => string;
  onOpen: (enrollmentId: string) => void;
}) {
  const [search, setSearch] = useState('');
  const [result, setResult] = useState('');
  const [actionType, setActionType] = useState('');
  const records = useRecordSearch(objectType, search);

  const noMatch = records.ids !== null && records.ids.length === 0;
  const fetchPage = useCallback(
    ({ cursor, signal }: { cursor: string | null; signal: AbortSignal }) =>
      listWorkflowActionLogs(
        workflowId,
        {
          result: result ? [result as WorkflowActionResult] : undefined,
          actionType: actionType ? [actionType] : undefined,
          recordId: records.ids ?? undefined,
          limit: PAGE_SIZE,
          cursor: cursor ?? undefined,
        },
        { signal },
      ),
    [workflowId, result, actionType, records.ids],
  );
  const list = useCursorList<WorkflowActionLogRow>(
    fetchPage,
    `${workflowId}|${result}|${actionType}|${(records.ids ?? []).join(',')}`,
    // A search that matches no record has nothing to load.
    { enabled: !noMatch && !records.searching },
  );
  const filtered = Boolean(result || actionType || records.ids);
  const rows = noMatch ? [] : list.rows;

  return (
    <section className="card wfh-card" aria-label="Action logs">
      {/* Design: search on the left, results in the middle, actions on the right. */}
      <div className="wfh-toolbar wfh-toolbar--logs">
        <HistorySearch value={search} onChange={setSearch} />
        <HistorySelect
          label="Result"
          value={result}
          options={RESULT_OPTIONS}
          onChange={setResult}
        />
        <HistorySelect
          label="Action"
          value={actionType}
          options={ACTION_OPTIONS}
          onChange={setActionType}
        />
      </div>
      {list.error ? <Alert tone="danger">{list.error}</Alert> : null}
      <div className="table-wrap crm-table-wrap">
        <table className="crm-table wfh-table">
          <thead>
            <tr>
              <th scope="col">Time</th>
              <th scope="col">Record</th>
              <th scope="col">Action</th>
              <th scope="col">Result</th>
              <th scope="col">Details</th>
            </tr>
          </thead>
          {rows.length > 0 ? (
            <tbody>
              {rows.map((row) => (
                <tr
                  key={row.id}
                  className="wfh-row"
                  tabIndex={0}
                  title="Open this record's run"
                  onClick={() => onOpen(row.enrollmentId)}
                  onKeyDown={(e) => e.key === 'Enter' && onOpen(row.enrollmentId)}
                >
                  <td data-label="Time" className="crm-text-nowrap">
                    {formatWhen(row.createdAt, timeZone)}
                  </td>
                  <td data-label="Record" onClick={(e) => e.stopPropagation()}>
                    <RecordLink type={row.recordType} id={row.recordId} name={row.recordName} />
                  </td>
                  <td data-label="Action">
                    {stepLabel(row.stepId)}
                    <div className="wfh-sub">
                      {ACTION_LABELS[row.actionType] ??
                        (row.actionType === 'branch' ? 'Branch' : row.actionType)}
                    </div>
                  </td>
                  <td data-label="Result">
                    <ResultBadge result={row.result} />
                  </td>
                  <td data-label="Details">
                    {/* QA #374: what happened in words, not the stored detail. */}
                    <div className="wfh-sub wfh-truncate">
                      {outcomeText({
                        action: row.actionType,
                        result: row.result,
                        detail: row.detail,
                      })}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          ) : null}
        </table>
      </div>
      {rows.length === 0 ? (
        list.loading || records.searching ? (
          <p className="wfh-loading">Loading…</p>
        ) : (
          <HistoryEmpty
            icon="list"
            title={filtered ? 'No action logs match' : 'No action logs'}
            text={
              filtered
                ? 'Try a different record, result or action.'
                : 'Logs appear once records start moving through the workflow.'
            }
          />
        )
      ) : null}
      <Pager
        page={list.page}
        hasNext={list.hasNext}
        loading={list.loading}
        count={rows.length}
        onPrev={() => void list.goTo(list.page - 1, list.pageCursors[list.page - 2] ?? null)}
        onNext={() => void list.goTo(list.page + 1, list.pageCursors[list.page] ?? null)}
      />
    </section>
  );
}
