'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import type { AssociationCandidate, AssociationObjectType } from '@/features/associations/types';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import { recordSearchFor } from '@/features/workflows/useRecordSearch';
import { listWorkflowVersions, testWorkflow } from '@/features/workflows/api.client';
import type {
  WorkflowDetail,
  WorkflowTestResult,
  WorkflowVersionSummary,
} from '@/features/workflows/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { ResultBadge } from './EnrollmentDrawer';
import { outcomeText, usePropertyLabels } from './outcome';
import { actionLabel, objectLabel, useWorkflowAccess } from './shared';

/**
 * Test with a record: what the workflow would do to one record (delays skipped), writing,
 * sending and queueing nothing. Uses the saved draft unless a version is chosen.
 */
export function TestRunTab({
  workflow,
  stepLabel,
}: {
  workflow: WorkflowDetail;
  stepLabel: (stepId: string) => string;
}) {
  const [record, setRecord] = useState<AssociationCandidate | null>(null);
  const [versionId, setVersionId] = useState('');
  const [versions, setVersions] = useState<WorkflowVersionSummary[]>([]);
  const [result, setResult] = useState<WorkflowTestResult | null>(null);
  const labelOf = usePropertyLabels(workflow.objectType);
  const { timeZone } = useWorkflowAccess();
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    listWorkflowVersions(workflow.id).then(
      (res) => setVersions(res.data),
      () => setVersions([]),
    );
  }, [workflow.id, workflow.updatedAt]);

  const run = async () => {
    if (!record || busy) return;
    setBusy(true);
    setError(null);
    setResult(null);
    try {
      setResult(
        await testWorkflow(workflow.id, {
          recordId: record.id,
          ...(versionId ? { versionId } : {}),
        }),
      );
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="crm-d-flex crm-flex-column crm-gap-4">
      <section className="sales-card sales-card--pad">
        <h3 className="sales-card__title crm-mb-2">Test with a record</h3>
        <p className="crm-fs-7 crm-text-muted">
          Runs one {objectLabel(workflow.objectType).toLowerCase()} through the workflow with the
          delays skipped and shows what each step would do. Nothing is saved, sent or queued.
        </p>
        <div className="form-grid crm-mt-3">
          <div className="field">
            <label className="field__label" htmlFor="wfTestRecord">
              {objectLabel(workflow.objectType)}
            </label>
            <RecordSearchInput
              id="wfTestRecord"
              type={workflow.objectType as AssociationObjectType}
              search={recordSearchFor(workflow.objectType)}
              value={record}
              onPick={setRecord}
            />
          </div>
          <label className="field">
            <span className="field__label">Version</span>
            <select
              className="select"
              value={versionId}
              onChange={(e) => setVersionId(e.target.value)}
            >
              <option value="">
                {workflow.draft ? 'The draft (saved)' : 'The published version'}
              </option>
              {versions
                .filter((v) => v.publishedAt !== null)
                .map((v) => (
                  <option key={v.id} value={v.id}>
                    Version {v.versionNo}
                    {v.current ? ' (live)' : ''}
                  </option>
                ))}
            </select>
          </label>
        </div>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary crm-mt-3', busy && 'is-loading')}
          disabled={!record || busy}
          onClick={() => void run()}
        >
          Run test
        </button>
      </section>

      {error ? <Alert tone="danger">{error}</Alert> : null}

      {result ? (
        <section className="sales-card sales-card--pad">
          {/* Go-live 944: first, would the trigger enroll this record by itself? */}
          <Alert tone={result.trigger.expectedToStart ? 'success' : 'warning'}>
            <strong>
              {result.trigger.expectedToStart
                ? 'The trigger would enroll this record.'
                : 'The trigger would not enroll this record by itself.'}
            </strong>
            <ul className="crm-mb-0 crm-ps-3">
              {result.trigger.checks.map((c) => (
                <li key={c.label}>
                  {c.ok ? '✓' : '✕'} {c.label}
                </li>
              ))}
            </ul>
          </Alert>
          <h3 className="sales-card__title crm-mb-2 crm-mt-3">
            {result.trigger.expectedToStart ? '' : 'If it were enrolled by hand: '}
            {result.completed ? 'the record would reach the end' : 'the run would stop early'}
          </h3>
          {result.steps.length === 0 ? (
            <p className="crm-mb-0 crm-text-muted">No steps would run.</p>
          ) : (
            <ol className="crm-ps-4 crm-mb-0">
              {result.steps.map((s, i) => (
                <li key={`${s.stepId}-${i}`} className="crm-mb-2">
                  <div className="crm-d-flex crm-gap-2 crm-align-items-center">
                    <ResultBadge result={s.result} />
                    <strong>{stepLabel(s.stepId)}</strong>
                    <span className="crm-fs-8 crm-text-muted">
                      {s.type === 'action' && s.action ? actionLabel(s.action) : s.type}
                    </span>
                  </div>
                  {/* QA #374: the outcome in words (property labels, no ids or JSON). */}
                  <div className="crm-fs-8 crm-text-muted crm-text-break">
                    {outcomeText(s, labelOf, timeZone)}
                  </div>
                </li>
              ))}
            </ol>
          )}
        </section>
      ) : null}
    </div>
  );
}
