'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import {
  getWorkflowEnrollment,
  resolveWorkflowEnrollment,
  unenrollWorkflowEnrollment,
} from '@/features/workflows/api.client';
import type { WorkflowEnrollmentDetail } from '@/features/workflows/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  END_REASON_LABELS,
  EnrollmentStatusBadge,
  RecordLink,
  SOURCE_LABELS,
  actionLabel,
  eventLabel,
  formatWhen,
} from './shared';
import { outcomeText, usePropertyLabels } from './outcome';

const LOG_BADGE: Record<string, string> = {
  success: 'badge--success',
  skipped: 'badge--warning',
  failed: 'badge--danger',
};

export function ResultBadge({ result }: { result: string }) {
  return <span className={cn('badge', LOG_BADGE[result])}>{result}</span>;
}

/**
 * One enrollment (one record's run): its steps and action log, with retry / skip of a failed
 * step and taking the record out (editors only).
 */
export function EnrollmentDrawer({
  enrollmentId,
  canEnroll,
  timeZone,
  stepLabel,
  onClose,
  onChanged,
}: {
  enrollmentId: string | null;
  canEnroll: boolean;
  timeZone: string;
  stepLabel: (stepId: string) => string;
  onClose: () => void;
  onChanged: () => void;
}) {
  const toast = useToast();
  const [detail, setDetail] = useState<WorkflowEnrollmentDetail | null>(null);
  const labelOf = usePropertyLabels(detail?.recordType);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState<'retry' | 'skip' | 'unenroll' | null>(null);
  const [reason, setReason] = useState('');
  const [unenrolling, setUnenrolling] = useState(false);

  useEffect(() => {
    setDetail(null);
    setError(null);
    setReason('');
    setUnenrolling(false);
    if (!enrollmentId) return;
    let cancelled = false;
    getWorkflowEnrollment(enrollmentId).then(
      (res) => !cancelled && setDetail(res),
      (err) => !cancelled && setError(errorText(err)),
    );
    return () => {
      cancelled = true;
    };
  }, [enrollmentId]);

  const resolve = async (action: 'retry' | 'skip') => {
    if (!detail || busy) return;
    setBusy(action);
    try {
      setDetail(await resolveWorkflowEnrollment(detail.id, action));
      toast(action === 'retry' ? 'The failed step runs again' : 'Skipped the failed step');
      onChanged();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusy(null);
    }
  };

  const unenroll = async () => {
    if (!detail || busy || !reason.trim()) return;
    setBusy('unenroll');
    try {
      await unenrollWorkflowEnrollment(detail.id, reason.trim());
      toast('Record taken out of the workflow');
      setDetail(await getWorkflowEnrollment(detail.id));
      setUnenrolling(false);
      onChanged();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusy(null);
    }
  };

  const active = detail?.status === 'running' || detail?.status === 'waiting';

  return (
    <CrmModal
      id="wfEnrollmentDrawer"
      open={Boolean(enrollmentId)}
      onClose={onClose}
      drawer
      size="wide"
    >
      <ModalHeader id="wfEnrollmentDrawer" title="Enrollment" onClose={onClose} />
      <div className="modal__body">
        {error ? <Alert tone="danger">{error}</Alert> : null}
        {!detail && !error ? <p className="crm-text-muted">Loading…</p> : null}
        {detail ? (
          <div className="crm-d-flex crm-flex-column crm-gap-4">
            <dl className="crm-mb-0">
              <div className="crm-d-flex crm-gap-2 crm-align-items-center crm-mb-2">
                <RecordLink
                  type={detail.recordType}
                  id={detail.recordId}
                  name={detail.recordName}
                />
                <EnrollmentStatusBadge status={detail.status} />
                <span className="crm-fs-8 crm-text-muted">version {detail.versionNo ?? '—'}</span>
              </div>
              <div className="crm-fs-7">
                Entered {formatWhen(detail.enrolledAt, timeZone)} ·{' '}
                {SOURCE_LABELS[detail.source] ?? detail.source}
                {detail.triggerEventType ? ` (${eventLabel(detail.triggerEventType)})` : ''}
              </div>
              {detail.currentStepId ? (
                <div className="crm-fs-7">At step: {stepLabel(detail.currentStepId)}</div>
              ) : null}
              {detail.endedAt ? (
                <div className="crm-fs-7">
                  Left {formatWhen(detail.endedAt, timeZone)} ·{' '}
                  {END_REASON_LABELS[detail.endReason ?? ''] ?? detail.endReason ?? ''}
                  {detail.endNote ? ` · “${detail.endNote}”` : ''}
                </div>
              ) : null}
            </dl>

            {canEnroll && (detail.status === 'failed' || active) ? (
              <div className="crm-d-flex crm-flex-wrap crm-gap-2">
                {detail.status === 'failed' ? (
                  <>
                    <button
                      type="button"
                      className={cn(
                        'btn-crm btn-crm--primary btn-crm--sm',
                        busy === 'retry' && 'is-loading',
                      )}
                      disabled={busy !== null}
                      onClick={() => void resolve('retry')}
                    >
                      Retry failed step
                    </button>
                    <button
                      type="button"
                      className={cn(
                        'btn-crm btn-crm--outline btn-crm--sm',
                        busy === 'skip' && 'is-loading',
                      )}
                      disabled={busy !== null}
                      onClick={() => void resolve('skip')}
                    >
                      Skip it and go on
                    </button>
                  </>
                ) : null}
                {active && !unenrolling ? (
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline btn-crm--sm"
                    onClick={() => setUnenrolling(true)}
                  >
                    Take out of workflow
                  </button>
                ) : null}
              </div>
            ) : null}

            {unenrolling ? (
              <div className="sales-card crm-p-3">
                <label className="field">
                  <span className="field__label">Why? (kept in the history)</span>
                  <textarea
                    className="input"
                    rows={2}
                    maxLength={500}
                    value={reason}
                    onChange={(e) => setReason(e.target.value)}
                  />
                </label>
                <div className="crm-d-flex crm-gap-2 crm-mt-2">
                  <button
                    type="button"
                    className={cn(
                      'btn-crm btn-crm--primary btn-crm--sm',
                      busy === 'unenroll' && 'is-loading',
                    )}
                    disabled={busy !== null || !reason.trim()}
                    onClick={() => void unenroll()}
                  >
                    Take out
                  </button>
                  <button
                    type="button"
                    className="btn-crm btn-crm--ghost btn-crm--sm"
                    onClick={() => setUnenrolling(false)}
                  >
                    Cancel
                  </button>
                </div>
              </div>
            ) : null}

            <section>
              <div className="eyebrow-label crm-mb-2">Action log</div>
              {detail.actionLogs.length === 0 ? (
                <p className="crm-fs-8 crm-text-muted">No steps ran yet.</p>
              ) : (
                <ul className="crm-ps-0 crm-mb-0" style={{ listStyle: 'none' }}>
                  {detail.actionLogs.map((log) => (
                    <li key={log.id} className="crm-mb-2">
                      <div className="crm-d-flex crm-gap-2 crm-align-items-center">
                        <ResultBadge result={log.result} />
                        <strong className="crm-fs-7">{stepLabel(log.stepId)}</strong>
                        <span className="crm-fs-8 crm-text-muted crm-ms-auto">
                          {formatWhen(log.createdAt, timeZone)}
                        </span>
                      </div>
                      <div className="crm-fs-8 crm-text-muted crm-text-break">
                        {actionLabel(log.actionType)} ·{' '}
                        {outcomeText(
                          { action: log.actionType, result: log.result, detail: log.detail },
                          labelOf,
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </section>

            <section>
              <div className="eyebrow-label crm-mb-2">Scheduled steps</div>
              {detail.steps.length === 0 ? (
                <p className="crm-fs-8 crm-text-muted">None.</p>
              ) : (
                <ul className="crm-ps-3 crm-mb-0 crm-fs-7">
                  {detail.steps.map((s, i) => (
                    <li key={`${s.stepId}-${i}`}>
                      {stepLabel(s.stepId)}: {s.status}
                      {s.dueAt ? ` · due ${formatWhen(s.dueAt, timeZone)}` : ''}
                      {s.awaitedEvent ? ` · waiting for ${eventLabel(s.awaitedEvent)}` : ''}
                      {s.attempts > 1 ? ` · ${s.attempts} attempts` : ''}
                    </li>
                  ))}
                </ul>
              )}
            </section>
          </div>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
      </div>
    </CrmModal>
  );
}
