'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { getSequenceDeleteImpact, type SequenceDeleteImpact } from '../api.client';
import type { Sequence } from '../types';

const CONFIRM_WORD = 'delete';

const plural = (n: number, one: string, many: string) =>
  `${n.toLocaleString()} ${n === 1 ? one : many}`;

/**
 * HubSpot's Delete dialog (IDX-09, EDT-25), for a row, the selection and the editor's Delete: the
 * owner's heads-up when it is not yours, what the delete changes (counted by the API), and Delete
 * only once "delete" is typed. As in HubSpot a sequence contacts are enrolled in can be deleted:
 * they are unenrolled first.
 */
export function DeleteSequenceDialog({
  sequences,
  onClose,
  onConfirm,
}: {
  /** The sequences to delete; null or empty: closed. */
  sequences: Sequence[] | null;
  onClose: () => void;
  onConfirm: (sequences: Sequence[]) => Promise<void>;
}) {
  const me = useCurrentUser();
  const [busy, setBusy] = useState(false);
  const [typed, setTyped] = useState('');
  const [impact, setImpact] = useState<SequenceDeleteImpact[] | null>(null);
  const [impactError, setImpactError] = useState<string | null>(null);
  const open = Boolean(sequences?.length);
  const idsKey = sequences?.map((s) => s.id).join(',') ?? '';

  useEffect(() => {
    setTyped('');
    setImpact(null);
    setImpactError(null);
    if (!idsKey) return;
    const controller = new AbortController();
    getSequenceDeleteImpact(idsKey.split(','), controller.signal).then(
      (res) => setImpact(res.data),
      (err: unknown) => {
        if (!controller.signal.aborted) setImpactError(errorText(err));
      },
    );
    return () => controller.abort();
  }, [idsKey]);

  const title =
    sequences?.length === 1
      ? `Delete "${sequences[0]!.name}" sequence?`
      : `Delete ${sequences?.length ?? 0} sequences?`;
  // Heads-up: the owners of the sequences that are not yours.
  const others = [
    ...new Set(
      (sequences ?? [])
        .filter((s) => s.ownerId !== me.user.id)
        .map((s) => s.ownerName ?? 'Another user'),
    ),
  ];
  const sum = (key: 'contacts' | 'workflows') => (impact ?? []).reduce((n, row) => n + row[key], 0);
  const ready = typed.trim().toLowerCase() === CONFIRM_WORD;

  const confirm = async () => {
    if (!sequences?.length || busy || !ready) return;
    setBusy(true);
    try {
      await onConfirm(sequences);
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="seqDeleteModal" open={open} onClose={busy ? () => {} : onClose}>
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void confirm();
        }}
      >
        <ModalHeader id="seqDeleteModal" title={title} onClose={busy ? () => {} : onClose} />
        <div className="modal__body">
          {others.length > 0 ? (
            <Alert tone="warning">
              <strong>Heads up!</strong>{' '}
              {others.length === 1
                ? `${others[0]} owns ${sequences?.length === 1 ? 'this sequence' : 'one of these sequences'}. If it's deleted they will no longer be able to use it.`
                : `${others.join(', ')} own some of these sequences. If they're deleted they will no longer be able to use them.`}
            </Alert>
          ) : null}
          {impactError ? <Alert tone="danger">{impactError}</Alert> : null}
          {impact ? (
            <ul className="crm-mb-2">
              <li>{plural(sum('contacts'), 'contact', 'contacts')} will be unenrolled</li>
              <li>All scheduled emails won&apos;t be sent</li>
              <li>All remaining tasks won&apos;t be created</li>
              <li>
                {plural(sum('workflows'), 'associated workflow', 'associated workflows')} will no
                longer be able to enroll contacts
              </li>
              <li>This can&apos;t be undone.</li>
            </ul>
          ) : impactError ? null : (
            <p className="crm-text-muted">Counting what this deletes…</p>
          )}
          <div className="field">
            <label className="field__label" htmlFor="seqDeleteConfirm">
              Type &quot;{CONFIRM_WORD}&quot; below to confirm this action
            </label>
            <input
              id="seqDeleteConfirm"
              className="input"
              placeholder={CONFIRM_WORD}
              autoComplete="off"
              value={typed}
              onChange={(e) => setTyped(e.target.value)}
            />
          </div>
        </div>
        <div className="modal__footer seqm-modal-foot">
          <button
            type="submit"
            className={cn('btn-crm seq-btn-danger', busy && 'is-loading')}
            disabled={busy || !ready}
            aria-busy={busy}
          >
            Delete
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={onClose}
            disabled={busy}
          >
            Cancel
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
