'use client';

import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type { AssociationCandidate } from '@/features/associations/types';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import {
  listWorkflowEnrollments,
  listWorkflowErrors,
  listWorkflowIssues,
  listWorkflowTriggerLogs,
  resolveWorkflowErrors,
} from '@/features/workflows/api.client';
import { troubleshootItems, type TroubleshootItems } from '@/features/workflows/troubleshoot';
import type {
  WorkflowEnrollment,
  WorkflowErrorGroup,
  WorkflowIssue,
  WorkflowTriggerLog,
} from '@/features/workflows/types';
import { recordSearchFor } from '@/features/workflows/useRecordSearch';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { HistoryEmpty, REASON_LABELS } from './RunHistoryTab';
import { END_REASON_LABELS, actionLabel, eventLabel, formatWhen } from './shared';

/** The drawers' shared footer (design): Cancel, then "Review all automation issues". */
function Footer({ onClose }: { onClose: () => void }) {
  const router = useRouter();
  return (
    <div className="modal__footer wf-drawer-foot">
      <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
        Cancel
      </button>
      <button
        type="button"
        className="btn-crm btn-crm--outline"
        onClick={() => router.push('/workflows/issues')}
      >
        Review all automation issues
      </button>
    </div>
  );
}

/**
 * Troubleshoot actions (design: a drawer from Performance history): the workflow's failed
 * actions grouped by step and cause (GET /workflows/:id/errors), each with how many records it
 * hit; those allowed to enroll retry or skip them (POST /workflows/:id/errors/resolve; the workflow must be on).
 * Go-live 942: it lists the issues still to review, setup problems included, as the Issues page
 * and every count do. Reviewed ones are kept apart (see troubleshootItems).
 */
export function TroubleshootActionsDrawer({
  open,
  onClose,
  workflowId,
  isOn,
  canEnroll,
  timeZone,
  stepLabel,
  onOpen,
  onResolved,
}: {
  open: boolean;
  onClose: () => void;
  workflowId: string;
  isOn: boolean;
  canEnroll: boolean;
  timeZone: string;
  stepLabel: (stepId: string) => string;
  onOpen: (enrollmentId: string) => void;
  onResolved: () => void;
}) {
  const toast = useToast();
  const [items, setItems] = useState<TroubleshootItems | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);

  const load = useCallback(() => {
    setError(null);
    setItems(null);
    Promise.all([
      listWorkflowErrors(workflowId),
      listWorkflowIssues('new', undefined, workflowId),
      listWorkflowIssues('reviewed', undefined, workflowId),
    ]).then(
      ([errors, fresh, reviewed]) =>
        setItems(troubleshootItems(errors.groups, fresh.data, reviewed.data)),
      (err) => {
        setItems(troubleshootItems([], [], []));
        setError(errorText(err));
      },
    );
  }, [workflowId]);

  useEffect(() => {
    if (open) load();
  }, [open, load]);

  const resolve = async (group: WorkflowErrorGroup, action: 'retry' | 'skip') => {
    const key = `${group.stepId}|${group.reason}|${action}`;
    if (busy) return;
    setBusy(key);
    try {
      const res = await resolveWorkflowErrors(workflowId, {
        action,
        enrollmentIds: group.enrollmentIds.slice(0, 100),
      });
      const failed = res.results.filter((r) => r.error);
      const done = res.results.length - failed.length;
      toast(
        `${action === 'retry' ? 'Retrying' : 'Skipped'} ${done} record${done === 1 ? '' : 's'}${
          failed.length ? `; ${failed.length} could not be: ${failed[0]!.error}` : ''
        }`,
        failed.length ? 'info' : 'success',
      );
      load();
      onResolved();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusy(null);
    }
  };

  const setupItem = (issue: WorkflowIssue) => (
    <li key={issue.key} className="wft-item">
      <div className="wft-item__head">
        <strong>{issue.stepId ? stepLabel(issue.stepId) : 'Workflow'}</strong>
        <span className="badge badge--danger">Setup problem</span>
      </div>
      <p className="wft-item__reason">{issue.message}</p>
      <p className="wfh-sub">
        {issue.actionType ? `${actionLabel(issue.actionType)} · ` : ''}fix it in the workflow or its
        connection
      </p>
    </li>
  );

  const failedItem = (g: WorkflowErrorGroup) => {
    const key = `${g.stepId}|${g.reason}`;
    return (
      <li key={key} className="wft-item">
        <div className="wft-item__head">
          <strong>{stepLabel(g.stepId)}</strong>
          <span className="badge badge--danger">{g.count} failed</span>
        </div>
        <p className="wft-item__reason">{g.reason}</p>
        <p className="wfh-sub">
          {actionLabel(g.actionType)}
          {g.lastFailedAt ? ` · last failed ${formatWhen(g.lastFailedAt, timeZone)}` : ''}
        </p>
        {g.enrollmentIds[0] ? (
          <div className="wft-item__foot">
            <button type="button" className="link" onClick={() => onOpen(g.enrollmentIds[0]!)}>
              View latest run
            </button>
            {canEnroll ? (
              <span className="crm-d-flex crm-gap-2">
                <button
                  type="button"
                  className={cn(
                    'btn-crm btn-crm--outline btn-crm--sm',
                    busy === `${key}|skip` && 'is-loading',
                  )}
                  disabled={!isOn || busy !== null}
                  onClick={() => void resolve(g, 'skip')}
                >
                  Skip
                </button>
                <button
                  type="button"
                  className={cn(
                    'btn-crm btn-crm--primary btn-crm--sm',
                    busy === `${key}|retry` && 'is-loading',
                  )}
                  disabled={!isOn || busy !== null}
                  onClick={() => void resolve(g, 'retry')}
                >
                  Retry
                </button>
              </span>
            ) : null}
          </div>
        ) : null}
      </li>
    );
  };

  const toReview = items ? items.setup.length + items.failed.length : 0;
  const reviewed = items ? items.reviewedSetup.length + items.reviewedFailed.length : 0;
  const retryable = items ? items.failed.length + items.reviewedFailed.length : 0;

  return (
    <CrmModal id="wfTroubleshootActions" drawer open={open} onClose={onClose}>
      <ModalHeader id="wfTroubleshootActions" title="Troubleshoot actions" onClose={onClose} />
      <div className="modal__body wft">
        <p className="wft__lead">
          Actions in this workflow that failed or were skipped recently, and how to fix them.
        </p>
        {error ? <Alert tone="danger">{error}</Alert> : null}
        {items === null ? (
          <p className="wfh-loading">Loading…</p>
        ) : (
          <>
            {retryable && !isOn && canEnroll ? (
              <p className="wft__note">Turn the workflow on to retry or skip failed actions.</p>
            ) : null}
            {items.setup.length ? (
              <ul className="wft-list" aria-label="Setup problems">
                {items.setup.map(setupItem)}
              </ul>
            ) : null}
            {items.failed.length ? (
              <ul className="wft-list" aria-label="Failed actions">
                {items.failed.map(failedItem)}
              </ul>
            ) : null}
            {/* Not after a failed load: nothing was checked then. */}
            {toReview || error ? null : (
              <HistoryEmpty
                icon="check"
                title={reviewed ? 'No action errors to review' : 'No action errors'}
                text={
                  reviewed
                    ? 'Everything found here has been marked reviewed.'
                    : 'Every action ran without problems, and nothing in its setup is broken.'
                }
              />
            )}
            {reviewed ? (
              <details className="wft-reviewed">
                <summary>Reviewed ({reviewed}), not counted</summary>
                <ul className="wft-list" aria-label="Reviewed">
                  {items.reviewedSetup.map(setupItem)}
                  {items.reviewedFailed.map(failedItem)}
                </ul>
              </details>
            ) : null}
          </>
        )}
      </div>
      <Footer onClose={onClose} />
    </CrmModal>
  );
}

interface CheckResult {
  enrollments: WorkflowEnrollment[];
  logs: WorkflowTriggerLog[];
}

/**
 * Troubleshoot enrollment (design: a drawer from Performance history): pick a record, then
 * "Check record" shows whether it is or was in the workflow and why it did or did not enter
 * (GET /workflows/:id/enrollments and GET /workflow-trigger-logs for that record).
 */
export function TroubleshootEnrollmentDrawer({
  open,
  onClose,
  workflowId,
  objectType,
  timeZone,
  stepLabel,
  onOpen,
}: {
  open: boolean;
  onClose: () => void;
  workflowId: string;
  objectType: string;
  timeZone: string;
  stepLabel: (stepId: string) => string;
  onOpen: (enrollmentId: string) => void;
}) {
  const [record, setRecord] = useState<AssociationCandidate | null>(null);
  const [checking, setChecking] = useState(false);
  const [result, setResult] = useState<CheckResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setResult(null);
    setError(null);
  }, [open]);

  const onCheck = async () => {
    if (!record || checking) return;
    const recordId = record.id;
    setChecking(true);
    setError(null);
    try {
      const [enrollments, logs] = await Promise.all([
        listWorkflowEnrollments(workflowId, { recordId, limit: 20 }),
        listWorkflowTriggerLogs({ workflowId, recordType: objectType, recordId, limit: 20 }),
      ]);
      setResult({ enrollments: enrollments.data, logs: logs.data });
    } catch (err) {
      setError(errorText(err));
    } finally {
      setChecking(false);
    }
  };

  const active = result?.enrollments.find((e) => e.status === 'running' || e.status === 'waiting');
  const last = result?.enrollments[0];
  const shown = active ?? last;
  const name = record?.title ?? 'This record';

  let summary: string;
  if (active) {
    summary = `Enrolled ${formatWhen(active.enrolledAt, timeZone)}${
      active.currentStepId ? ` · now at ${stepLabel(active.currentStepId)}` : ''
    }`;
  } else if (last) {
    const how =
      last.status === 'completed'
        ? 'completed'
        : (END_REASON_LABELS[last.endReason ?? ''] ?? last.status);
    summary = `Last enrolled ${formatWhen(last.enrolledAt, timeZone)} · ${how}`;
  } else if (result?.logs.length) {
    summary = 'See why below.';
  } else {
    summary =
      'No trigger decision was logged for it: it has not met the trigger since the workflow was turned on.';
  }

  return (
    <CrmModal id="wfTroubleshootEnrollment" drawer open={open} onClose={onClose}>
      <ModalHeader
        id="wfTroubleshootEnrollment"
        title="Troubleshoot enrollment"
        onClose={onClose}
      />
      <div className="modal__body wft">
        <p className="wft__lead">
          Find out why a record did or didn&apos;t enroll in this workflow.
        </p>
        <label className="wf-move__label" htmlFor="wfTroubleshootRecord">
          Record
        </label>
        <RecordSearchInput
          id="wfTroubleshootRecord"
          type={objectType}
          search={recordSearchFor(objectType)}
          value={record}
          onPick={(r) => {
            setRecord(r);
            setResult(null);
          }}
        />
        {error ? (
          <div className="crm-mt-3">
            <Alert tone="danger">{error}</Alert>
          </div>
        ) : null}

        {result ? (
          <div className="wft-result">
            <div className={cn('wft-verdict', active ? 'is-in' : last ? 'is-was' : 'is-out')}>
              <strong>
                {active
                  ? `${name} is in this workflow`
                  : last
                    ? `${name} was enrolled before`
                    : `${name} has not enrolled`}
              </strong>
              <span>{summary}</span>
              {shown ? (
                <button type="button" className="link" onClick={() => onOpen(shown.id)}>
                  View run
                </button>
              ) : null}
            </div>

            {result.logs.length ? (
              <>
                <h4 className="wf-detail__sub crm-mt-3">Recent trigger decisions</h4>
                <ul className="wft-list">
                  {result.logs.map((row) => (
                    <li key={row.id} className="wft-item">
                      <div className="wft-item__head">
                        <span>{REASON_LABELS[row.reason] ?? row.reason}</span>
                        <span
                          className={cn(
                            'badge',
                            row.outcome === 'enrolled' && 'badge--success',
                            row.outcome === 'failed' && 'badge--danger',
                            row.outcome === 'skipped' && 'badge--warning',
                          )}
                        >
                          {row.outcome === 'unenrolled' ? 'taken out' : row.outcome}
                        </span>
                      </div>
                      <div className="wft-item__foot">
                        <span>
                          {formatWhen(row.createdAt, timeZone)}
                          {row.eventType ? ` · ${eventLabel(row.eventType)}` : ''}
                        </span>
                      </div>
                    </li>
                  ))}
                </ul>
              </>
            ) : null}
          </div>
        ) : null}
      </div>
      <div className="modal__footer wf-drawer-foot">
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', checking && 'is-loading')}
          disabled={!record || checking}
          onClick={() => void onCheck()}
        >
          Check record
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </CrmModal>
  );
}
