'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { enrollmentPreview } from '@/features/workflows/api.client';
import type {
  WorkflowDefinition,
  WorkflowDetail,
  WorkflowProblem,
  WorkflowStep,
} from '@/features/workflows/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { ProblemsList, problemsFromError } from './shared';

/**
 * "Review and turn on" (design: workflow-editor.php): what blocks turning on, and whether
 * records that already meet the trigger enroll too. Turning on saves and publishes the draft
 * first (`onTurnOn`).
 */

function hasAction(steps: WorkflowStep[]): boolean {
  return steps.some(
    (s) =>
      s.type === 'action' ||
      (s.type === 'branch' &&
        ((s.paths ?? []).some((p) => hasAction(p.steps ?? [])) ||
          hasAction(s.otherwise?.steps ?? []))),
  );
}

function triggerIsSet(definition: WorkflowDefinition): boolean {
  const t = definition.trigger;
  if (t.type === 'filter') return t.filter.groups.some((g) => g.conditions.length > 0);
  return true;
}

function Check({ tone, children }: { tone: 'ok' | 'bad' | 'warn'; children: React.ReactNode }) {
  return (
    <div className={cn('wfe-check', `wfe-check--${tone}`)}>
      <svg viewBox="0 0 24 24" width="16" height="16" aria-hidden>
        {tone === 'ok' ? (
          <path d="m5 12 5 5 9-10" fill="none" stroke="currentColor" strokeWidth="2" />
        ) : (
          <path
            d="M12 3 2 21h20zM12 10v5M12 18h.01"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinejoin="round"
          />
        )}
      </svg>
      <span>{children}</span>
    </div>
  );
}

export function ReviewTurnOnDrawer({
  open,
  onClose,
  workflow,
  definition,
  check,
  canEnroll,
  onTurnOn,
}: {
  open: boolean;
  onClose: () => void;
  workflow: WorkflowDetail;
  definition: WorkflowDefinition;
  /** Saves the draft and asks the API what blocks publishing. */
  check: () => Promise<WorkflowProblem[]>;
  /** Enrolling the records that match already needs the enroll right. */
  canEnroll: boolean;
  /** Publishes the draft (when there is one) and turns the workflow on. */
  onTurnOn: (enrollExisting: boolean) => Promise<void>;
}) {
  const [problems, setProblems] = useState<WorkflowProblem[] | null>(null);
  const [checkError, setCheckError] = useState<string | null>(null);
  const [existing, setExisting] = useState<number | null>(null);
  const [enrollExisting, setEnrollExisting] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [errorProblems, setErrorProblems] = useState<WorkflowProblem[]>([]);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setProblems(null);
    setCheckError(null);
    setError(null);
    setErrorProblems([]);
    setEnrollExisting(false);
    setExisting(null);
    check().then(
      (found) => !cancelled && setProblems(found),
      (err: unknown) => !cancelled && setCheckError(errorText(err)),
    );
    if (workflow.currentVersionId && definition.trigger.type !== 'manual') {
      enrollmentPreview(workflow.id).then(
        (p) => !cancelled && setExisting(p.count),
        () => !cancelled && setExisting(null),
      );
    }
    return () => {
      cancelled = true;
    };
    // Only when the drawer opens: the check saves the draft.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  const triggerOk = triggerIsSet(definition);
  const actionOk = hasAction(definition.steps);
  const stepProblems = (problems ?? []).filter((p) => p.path.startsWith('steps'));
  const otherProblems = (problems ?? []).filter(
    (p) => !p.path.startsWith('steps') && !(p.path === 'steps' && !actionOk),
  );
  const unnamed = /^unnamed workflow/i.test(workflow.name.trim());
  const blocked =
    !triggerOk || !actionOk || problems === null || problems.length > 0 || Boolean(checkError);
  const manual = definition.trigger.type === 'manual';

  const turnOn = async () => {
    if (busy || blocked) return;
    setBusy(true);
    setError(null);
    setErrorProblems([]);
    try {
      await onTurnOn(enrollExisting && !manual);
      onClose();
    } catch (err) {
      setErrorProblems(problemsFromError(err) ?? []);
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };
  const close = busy ? () => {} : onClose;

  return (
    <CrmModal id="wfReviewDrawer" open={open} onClose={close} drawer size="wide">
      <ModalHeader id="wfReviewDrawer" title="Review and turn on" onClose={close} />
      <div className="modal__body">
        <Check tone={triggerOk ? 'ok' : 'bad'}>
          {triggerOk ? 'The enrollment trigger is set up' : 'Set up an enrollment trigger'}
        </Check>
        <Check tone={actionOk ? 'ok' : 'bad'}>
          {actionOk ? 'The workflow has an action' : 'Add at least one action'}
        </Check>
        {problems === null && !checkError ? (
          <p className="crm-text-muted crm-fs-7">Checking the actions…</p>
        ) : checkError ? (
          <Alert tone="danger">Could not check the workflow: {checkError}</Alert>
        ) : (
          <Check tone={stepProblems.length ? 'bad' : 'ok'}>
            {stepProblems.length
              ? `${stepProblems.length} action setting${stepProblems.length === 1 ? ' needs' : 's need'} fixing`
              : 'All actions are set up'}
          </Check>
        )}
        {problems && problems.length ? (
          <div className="crm-mb-3">
            <ProblemsList problems={[...stepProblems, ...otherProblems]} />
          </div>
        ) : null}
        {unnamed ? <Check tone="warn">Give the workflow a clear name (recommended)</Check> : null}

        {!manual && canEnroll ? (
          <fieldset className="crm-mt-4">
            <legend className="crm-fs-7 crm-fw-semibold crm-mb-2">
              Enroll records that already meet the trigger?
            </legend>
            <label className="check-row" htmlFor="wfReviewNew">
              <input
                id="wfReviewNew"
                type="radio"
                name="wfReviewExisting"
                checked={!enrollExisting}
                onChange={() => setEnrollExisting(false)}
              />
              <span>No, only records that meet the trigger from now on</span>
            </label>
            <label className="check-row" htmlFor="wfReviewExisting">
              <input
                id="wfReviewExisting"
                type="radio"
                name="wfReviewExisting"
                checked={enrollExisting}
                onChange={() => setEnrollExisting(true)}
              />
              <span>
                Yes, enroll {existing !== null ? <strong>{existing}</strong> : 'the'} existing
                record
                {existing === 1 ? '' : 's'} too
              </span>
            </label>
            {existing !== null && (workflow.hasDraft || definition.trigger.type === 'event') ? (
              <p className="crm-text-muted crm-fs-8 crm-mt-1 crm-mb-0">
                {definition.trigger.type === 'event'
                  ? 'For an event trigger, "existing" means records that had the event while the workflow was off.'
                  : 'Counted with the published version; the draft you turn on may match a different number.'}
              </p>
            ) : null}
          </fieldset>
        ) : (
          <p className="crm-text-muted crm-fs-7 crm-mt-3">
            Records are enrolled by hand or by other workflows.
          </p>
        )}

        {error ? (
          <div className="crm-mt-3">
            <Alert tone="danger">
              {error}
              {errorProblems.length ? <ProblemsList problems={errorProblems} /> : null}
            </Alert>
          </div>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={close} disabled={busy}>
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          onClick={() => void turnOn()}
          disabled={busy || blocked}
          aria-busy={busy}
        >
          <span className="btn-crm__spinner" aria-hidden />
          <span className="btn-crm__text">Turn on</span>
        </button>
      </div>
    </CrmModal>
  );
}
