'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { LpModal } from '@/features/list-page/ui/LpModal';
import { enrollRecords, listWorkflows } from '@/features/workflows/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

/** "3 calls" (the design's `nN`, lower case) or "3 Calls" (its title, capitalised). */
export function callsCount(n: number, capital = false): string {
  const noun = n === 1 ? 'call' : 'calls';
  return `${n.toLocaleString()} ${capital ? noun.charAt(0).toUpperCase() + noun.slice(1) : noun}`;
}

/** Why a call wasn't enrolled, as the builder's Manually enroll says it. */
const REFUSALS: Record<string, string> = {
  already_enrolled: 'already in the workflow',
  re_enrollment_off: 're-enrollment is off',
  loop_guard: 'stopped by the loop guard',
  no_access: 'you cannot edit it',
};

/**
 * CL5c1: the Calls page's "Enroll in workflow" (design list-page.js `bxWorkflow` through `bxPick`):
 * pick a call workflow and enroll the selected calls (POST /workflows/:id/enrollments). As the
 * Contacts bar's dialog, it lists the workflows that are on: one that is off refuses enrollments.
 */
export function CallsEnrollWorkflow({
  open,
  ids,
  onClose,
}: {
  open: boolean;
  /** The selected calls (one page, at most 100). */
  ids: string[];
  onClose: () => void;
}) {
  const toast = useToast();
  const [options, setOptions] = useState<CustomSelectOption[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [workflowId, setWorkflowId] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    setWorkflowId('');
    setError(null);
    setLoadError(null);
    setOptions(null);
    listWorkflows({ objectType: ['call'], status: ['on'], limit: 100 }).then(
      (page) => alive && setOptions(page.data.map((w) => ({ value: w.id, label: w.name }))),
      (err) => alive && setLoadError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [open]);

  const n = ids.length;
  const enroll = async () => {
    if (!workflowId || busy || !n) return;
    setBusy(true);
    setError(null);
    try {
      const res = await enrollRecords(workflowId, ids);
      const name = options?.find((o) => o.value === workflowId)?.label ?? 'the workflow';
      const refused = res.results.filter((r) => !r.enrollmentId);
      if (!res.enrolled) {
        // Nothing enrolled: the dialog stays open with the reason.
        const why = refused[0]?.refusal;
        setError(`Not enrolled: ${REFUSALS[why ?? ''] ?? why ?? 'refused'}`);
        return;
      }
      // The design's toast: "3 calls enrolled in Follow-up calls".
      toast(`${callsCount(res.enrolled)} enrolled in ${name}`);
      onClose();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <LpModal
      open={open}
      title={`Enroll ${callsCount(n, true)} in a workflow`}
      onClose={() => !busy && onClose()}
      className="lp-modal--pick"
      footer={
        <div className="lp-modal__acts lp-modal__acts--start">
          <button
            type="button"
            className={cn('lp-btn lp-btn--primary', busy && 'is-loading')}
            disabled={busy || !workflowId || !n}
            onClick={() => void enroll()}
          >
            Enroll
          </button>
          <button
            type="button"
            className="lp-btn lp-btn--outline"
            disabled={busy}
            onClick={onClose}
          >
            Cancel
          </button>
        </div>
      }
    >
      {error ? <Alert tone="danger">{error}</Alert> : null}
      {loadError ? <Alert tone="danger">{loadError}</Alert> : null}
      <div className="lp-field">
        <label htmlFor="callsEnrollWorkflow">Select a workflow:</label>
        <CustomSelect
          id="callsEnrollWorkflow"
          className="lp-bx__select"
          placeholder={options === null && !loadError ? 'Loading workflows…' : 'Select workflow'}
          value={workflowId}
          options={options ?? []}
          onChange={setWorkflowId}
          disabled={!options?.length}
        />
      </div>
    </LpModal>
  );
}
