'use client';

import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import type { AssociationCandidate, AssociationObjectType } from '@/features/associations/types';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import { recordSearchFor } from '@/features/workflows/useRecordSearch';
import { enrollmentPreview, enrollRecords } from '@/features/workflows/api.client';
import type { WorkflowDetail, WorkflowEnrollmentPreview } from '@/features/workflows/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { RecordLink, formatWhen, objectLabel } from './shared';

const REFUSALS: Record<string, string> = {
  already_enrolled: 'It is already in this workflow.',
  re_enrollment_off: 'It was in this workflow before and re-enrollment is off.',
  no_access: 'You may not edit this record.',
  loop_guard: 'Stopped by the loop guard.',
};

/**
 * Enrollment: who turning it on with "enroll existing records" would enroll (preview), turning it
 * on or off, and enrolling one record by hand.
 */
export function EnrollmentTab({
  workflow,
  canEdit,
  canPublish,
  canEnroll,
  timeZone,
  onTurnOn,
  onTurnOff,
  onEnrolled,
}: {
  workflow: WorkflowDetail;
  canEdit: boolean;
  canPublish: boolean;
  canEnroll: boolean;
  timeZone: string;
  onTurnOn: () => void;
  onTurnOff: () => void;
  onEnrolled: () => void;
}) {
  const toast = useToast();
  const [preview, setPreview] = useState<WorkflowEnrollmentPreview | null>(null);
  const [previewError, setPreviewError] = useState<string | null>(null);
  const [record, setRecord] = useState<AssociationCandidate | null>(null);
  const [enrolling, setEnrolling] = useState(false);

  const loadPreview = useCallback(() => {
    if (!canEdit || !workflow.currentVersionId) return;
    setPreviewError(null);
    enrollmentPreview(workflow.id).then(setPreview, (err) => {
      setPreview(null);
      setPreviewError(errorText(err));
    });
  }, [canEdit, workflow.id, workflow.currentVersionId]);

  useEffect(loadPreview, [loadPreview, workflow.status]);

  const enroll = async () => {
    if (!record || enrolling) return;
    setEnrolling(true);
    try {
      const res = await enrollRecords(workflow.id, [record.id]);
      const one = res.results[0];
      if (res.enrolled > 0) {
        toast(`${record.title} enrolled`);
        setRecord(null);
        onEnrolled();
      } else {
        toast(
          `${record.title} was not enrolled: ${REFUSALS[one?.refusal ?? ''] ?? one?.refusal ?? 'refused'}`,
          'danger',
          { durationMs: 9000 },
        );
      }
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setEnrolling(false);
    }
  };

  const objectType = workflow.objectType as AssociationObjectType;
  const published = Boolean(workflow.currentVersionId);

  return (
    <div className="crm-d-flex crm-flex-column crm-gap-4">
      <section className="sales-kpis" aria-label="Enrollment">
        <article className="sales-kpi">
          <div className="sales-kpi__label">Status</div>
          <div className="sales-kpi__value">
            {workflow.status === 'on' ? 'On' : workflow.status === 'off' ? 'Off' : 'Draft'}
          </div>
        </article>
        <article className="sales-kpi">
          <div className="sales-kpi__label">Enrolled now</div>
          <div className="sales-kpi__value">{workflow.enrolledCount}</div>
        </article>
        <article className="sales-kpi">
          <div className="sales-kpi__label">Live version</div>
          <div className="sales-kpi__value">
            {workflow.currentVersionNo ? `v${workflow.currentVersionNo}` : '—'}
          </div>
        </article>
        <article className="sales-kpi">
          <div className="sales-kpi__label">
            {workflow.status === 'on' ? 'On since' : 'Turned off'}
          </div>
          <div className="sales-kpi__value crm-fs-6">
            {formatWhen(
              workflow.status === 'on' ? workflow.turnedOnAt : workflow.turnedOffAt,
              timeZone,
            )}
          </div>
        </article>
      </section>

      <section className="sales-card sales-card--pad">
        <h3 className="sales-card__title crm-mb-2">Turn on</h3>
        {!published ? (
          <p className="crm-mb-0">Publish the workflow before turning it on.</p>
        ) : !canEdit ? (
          <p className="crm-mb-0 crm-text-muted">You can see this workflow but not change it.</p>
        ) : (
          <>
            {previewError ? <Alert tone="warning">{previewError}</Alert> : null}
            {preview ? (
              preview.trigger === 'manual' ? (
                <p>Manual trigger: records are only enrolled by hand.</p>
              ) : (
                <>
                  <p className="crm-mb-2">
                    Turning it on with &ldquo;enroll existing records&rdquo; would enroll{' '}
                    <strong>
                      {preview.count} {objectLabel(workflow.objectType).toLowerCase()}
                      {preview.count === 1 ? '' : ' records'}
                    </strong>{' '}
                    {preview.trigger === 'filter'
                      ? 'that match the trigger now'
                      : `that had the trigger event while it was off${
                          preview.since ? ` (since ${formatWhen(preview.since, timeZone)})` : ''
                        }`}
                    .
                  </p>
                  {preview.recordIds.length ? (
                    <div className="crm-fs-8 crm-mb-2">
                      {(preview.records ?? preview.recordIds.map((id) => ({ id, name: '' }))).map(
                        (r, i) => (
                          <span key={r.id}>
                            {i ? ', ' : null}
                            <RecordLink type={workflow.objectType} id={r.id} name={r.name} />
                          </span>
                        ),
                      )}
                      {preview.count > preview.recordIds.length
                        ? ` and ${preview.count - preview.recordIds.length} more`
                        : ''}
                    </div>
                  ) : null}
                </>
              )
            ) : !previewError && workflow.status !== 'on' ? (
              <p className="crm-text-muted">Checking which records match…</p>
            ) : null}
            <div className="crm-d-flex crm-gap-2">
              {workflow.status === 'on' ? (
                canPublish ? (
                  <button type="button" className="btn-crm btn-crm--outline" onClick={onTurnOff}>
                    Turn off
                  </button>
                ) : (
                  <p className="crm-fs-8 crm-text-muted crm-mb-0">
                    Your permission set does not allow turning workflows off.
                  </p>
                )
              ) : workflow.canTurnOn ? (
                <button type="button" className="btn-crm btn-crm--primary" onClick={onTurnOn}>
                  Turn on…
                </button>
              ) : (
                <p className="crm-fs-8 crm-text-muted crm-mb-0">
                  Only the CRM admin or the workflow&apos;s owner can turn it on.
                </p>
              )}
            </div>
          </>
        )}
      </section>

      {canEnroll ? (
        <section className="sales-card sales-card--pad">
          <h3 className="sales-card__title crm-mb-2">Enroll a record by hand</h3>
          {workflow.status !== 'on' ? (
            <p className="crm-fs-8 crm-text-muted">
              Turn the workflow on before enrolling records.
            </p>
          ) : null}
          <div className="crm-d-flex crm-flex-wrap crm-gap-2 crm-align-items-center">
            <div style={{ flex: '1 1 280px' }}>
              <RecordSearchInput
                id="wfEnrollRecord"
                type={objectType}
                search={recordSearchFor(workflow.objectType)}
                value={record}
                onPick={setRecord}
                disabled={workflow.status !== 'on'}
              />
            </div>
            <button
              type="button"
              className={cn('btn-crm btn-crm--primary', enrolling && 'is-loading')}
              disabled={!record || enrolling || workflow.status !== 'on'}
              onClick={() => void enroll()}
            >
              Enroll
            </button>
          </div>
        </section>
      ) : null}
    </div>
  );
}
