'use client';

import { useEffect, useMemo, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { listContacts } from '@/features/contacts/api.client';
import type { ContactListItem } from '@/features/contacts/types';
import { previewEnrollment } from '@/features/sequences/api.client';
import {
  ALREADY_ENROLLED_TEXT,
  PICK_CONTACT_TEXT,
  enrollButtonText,
} from '@/features/sequences/enrollReview';
import type { Sequence } from '@/features/sequences/types';
import { MAX_ENROLL_CONTACTS } from '@/features/sequences/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  EnrollReview,
  SequenceBlockAlert,
  useEnrollReview,
  useMySender,
  type EnrollContact,
} from './EnrollReview';
import { REFUSAL_LABELS } from './shared';

function nameOf(contact: ContactListItem): string {
  const full = `${contact.firstName ?? ''} ${contact.lastName ?? ''}`.trim();
  return full || contact.email || `Contact ${contact.id.slice(0, 8)}`;
}

/**
 * Enroll contacts, design DES-5: two steps, Contacts then Review (#58). Contacts lists who can be
 * picked, the ineligible ones disabled with the reason; Review is the shared enroll review
 * (start step, time zone, send time, sender, email preview and per-contact edits), then
 * "Enroll N contacts".
 */
export function EnrollContactsDrawer({
  open,
  sequence,
  onClose,
  onEnrolled,
}: {
  open: boolean;
  sequence: Sequence;
  onClose: () => void;
  onEnrolled: () => void;
}) {
  const toast = useToast();
  const [search, setSearch] = useState('');
  const [query, setQuery] = useState('');
  const [contacts, setContacts] = useState<ContactListItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [picked, setPicked] = useState<Map<string, ContactListItem>>(new Map());
  const [step, setStep] = useState<'pick' | 'review'>('pick');
  const [error, setError] = useState<string | null>(null);
  const { sender, problem } = useMySender(open);
  const mailboxId = sender.mailboxId;
  /**
   * Listed contacts that cannot be enrolled (already in a sequence, unsubscribed, bounced…),
   * checked as the list loads so they are shown disabled with the reason, like HubSpot
   * (QA 14 Oct #49, #61). The review checks the picks again.
   */
  const [refusals, setRefusals] = useState<Map<string, string>>(new Map());
  const pickedList = useMemo<EnrollContact[]>(
    () => [...picked.values()].map((c) => ({ id: c.id, name: nameOf(c), email: c.email })),
    [picked],
  );
  const review = useEnrollReview({
    open,
    sequence,
    contacts: step === 'review' ? pickedList : [],
    sender,
  });

  // Every opening starts over.
  useEffect(() => {
    if (!open) return;
    setSearch('');
    setQuery('');
    setPicked(new Map());
    setStep('pick');
    setError(null);
  }, [open]);

  useEffect(() => {
    const timer = window.setTimeout(() => setQuery(search.trim()), 250);
    return () => window.clearTimeout(timer);
  }, [search]);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setLoading(true);
    // #493: any part of the name ("Open", "QA Open Track") or the email finds the contact,
    // as the Contacts page's search does.
    listContacts({ search: query || undefined, searchMode: 'contains', limit: 50 })
      .then((page) => {
        if (!cancelled) setContacts(page.data.filter((c) => Boolean(c.email)));
      })
      .catch((err) => {
        if (!cancelled) {
          setContacts([]);
          setError(errorText(err));
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open, query]);

  const listedIds = contacts.map((c) => c.id).join(',');
  useEffect(() => {
    setRefusals(new Map());
    if (!open || !mailboxId || sequence.status === 'archived' || !listedIds) return;
    let cancelled = false;
    previewEnrollment(sequence.id, {
      contactIds: listedIds.split(',').slice(0, MAX_ENROLL_CONTACTS),
      senderMailboxId: mailboxId,
    }).then(
      (check) => {
        if (cancelled) return;
        setRefusals(
          new Map(
            check.data
              .filter((d) => !d.eligible)
              .map((d) => [
                d.contactId,
                d.message ?? (d.reason ? REFUSAL_LABELS[d.reason] : 'Cannot be enrolled'),
              ]),
          ),
        );
        // A pick that turns out ineligible is dropped.
        setPicked((current) => {
          const bad = check.data.filter((d) => !d.eligible && current.has(d.contactId));
          if (!bad.length) return current;
          const next = new Map(current);
          bad.forEach((d) => next.delete(d.contactId));
          return next;
        });
      },
      () => {
        // Not shown up front: the review still lists who cannot be enrolled.
      },
    );
    return () => {
      cancelled = true;
    };
  }, [open, mailboxId, sequence.id, sequence.status, listedIds]);

  const toggle = (contact: ContactListItem, on: boolean) => {
    setError(null);
    setPicked((current) => {
      const next = new Map(current);
      if (on) next.set(contact.id, contact);
      else next.delete(contact.id);
      return next;
    });
  };

  const blocked = review.block;
  const busy = review.enrolling;

  const next = async () => {
    if (step === 'pick') {
      if (picked.size === 0) {
        setError(PICK_CONTACT_TEXT);
        return;
      }
      setError(null);
      setStep('review');
      return;
    }
    const result = await review.submit();
    if (!result) return;
    if (result.created === 0) {
      const allIn = result.data.every((d) => d.reason === 'already_enrolled');
      toast(allIn ? ALREADY_ENROLLED_TEXT : 'No contacts were enrolled.', 'info');
      return;
    }
    toast(
      `${result.created} contact${result.created === 1 ? '' : 's'} enrolled.${
        result.refused > 0 ? ` ${result.refused} could not be enrolled.` : ''
      }`,
      result.refused > 0 ? 'info' : 'success',
    );
    onEnrolled();
  };

  const eligible = review.preview?.eligible ?? picked.size;
  // Next is always there to pick from (the design says "Pick at least one contact"); enrolling
  // needs the mailbox and a checked preview.
  const canNext =
    !blocked &&
    !busy &&
    (step === 'pick' ||
      (sender.ready && !review.loading && review.preview !== null && eligible > 0));
  const id = 'seqEnrollDrawer';

  return (
    <CrmModal id={id} open={open} onClose={busy ? () => {} : onClose} drawer plainBackdrop>
      <ModalHeader id={id} title="Enroll contacts" onClose={onClose} />
      <div className="modal__body seqen">
        <ol className="seq-stepper seq-enrol__steps" aria-label="Progress">
          <li
            className={cn('seq-stepper__item', step === 'pick' ? 'is-current' : 'is-done')}
            onClick={() => (step === 'review' && !busy ? setStep('pick') : undefined)}
          >
            <span className="seq-stepper__dot" aria-hidden="true" />
            Contacts
          </li>
          <li className={cn('seq-stepper__item', step === 'review' && 'is-current')}>
            <span className="seq-stepper__dot" aria-hidden="true" />
            Review
          </li>
        </ol>
        {blocked ? (
          <SequenceBlockAlert sequence={sequence} text={blocked} problems={review.problems} />
        ) : null}
        {problem ? <Alert tone="warning">{problem}</Alert> : null}
        {error ? <Alert tone="danger">{error}</Alert> : null}

        {step === 'review' ? (
          <EnrollReview
            idPrefix="seqEnrol"
            sequence={sequence}
            contacts={pickedList}
            sender={sender}
            review={review}
          />
        ) : (
          <>
            <p className="seqen__intro">
              Pick who should get this sequence. Emails go out from your inbox, one step at a time.
            </p>
            <input
              className="input"
              type="search"
              placeholder="Search contacts by name or email"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Search contacts"
            />
            <p className="seqen__count">
              {picked.size} of {MAX_ENROLL_CONTACTS} selected
            </p>
            {loading && contacts.length === 0 ? (
              <p className="seqm-empty">Loading contacts…</p>
            ) : contacts.length === 0 ? (
              <p className="seqm-empty">No contacts with an email address found.</p>
            ) : (
              <ul className="seqen__list" aria-label="Contacts">
                {contacts.map((contact) => {
                  const on = picked.has(contact.id);
                  const refused = refusals.get(contact.id);
                  return (
                    <li key={contact.id}>
                      <label
                        className={cn('seqen-card', on && 'is-on', refused && 'is-off')}
                        title={refused}
                      >
                        <span className="check">
                          <input
                            type="checkbox"
                            checked={on}
                            disabled={
                              Boolean(refused) || (!on && picked.size >= MAX_ENROLL_CONTACTS)
                            }
                            onChange={(e) => toggle(contact, e.target.checked)}
                          />
                          <span className="check__box" aria-hidden />
                        </span>
                        <span className="seqen-card__who">
                          <strong>
                            {refused ? (
                              <span className="seqen-card__warn" aria-hidden>
                                ⚠{' '}
                              </span>
                            ) : null}
                            {nameOf(contact)}
                          </strong>
                          <small>{refused ?? contact.email}</small>
                        </span>
                        {contact.company ? (
                          <span className="seqen-card__company">{contact.company.name}</span>
                        ) : null}
                      </label>
                    </li>
                  );
                })}
              </ul>
            )}
          </>
        )}
      </div>
      <div className="modal__footer seq-enrol__foot">
        {step === 'review' ? (
          <button
            type="button"
            className="btn-crm btn-crm--outline seq-enrol__back"
            onClick={() => setStep('pick')}
            disabled={busy}
          >
            Back
          </button>
        ) : null}
        <button
          type="button"
          className="btn-crm btn-crm--outline"
          onClick={onClose}
          disabled={busy}
        >
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          onClick={() => void next()}
          disabled={!canNext}
          aria-busy={busy}
        >
          {step === 'review' ? enrollButtonText(eligible) : 'Next'}
        </button>
      </div>
    </CrmModal>
  );
}
