'use client';

// Enroll a lead in a sequence (HUB-340): enrolls the lead's primary contact through the same
// flow as the contact page (connected mailbox, preview of who is eligible and when each step
// runs, then enroll once). A lead with only a company asks which of the company's contacts to
// use; it never guesses.
import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { getMyMailbox } from '@/features/inbox/api.client';
import { listSequences } from '@/features/sequences/api.client';
import type { Sequence } from '@/features/sequences/types';
import { EnrollPreviewDialog } from '@/features/sequences/ui/EnrollPreviewDialog';
import { errorText } from '@/lib/api/errors';
import { listLinkedRecords } from '../../api.client';
import { primaryCompanyOf, primaryContactOf, type PrimaryContact } from '../../leads';

type Loaded = {
  /** The primary contact; null when the lead has only a company. */
  primary: PrimaryContact | null;
  company: { id: string; name: string } | null;
  /** The company's contacts to pick from when there is no primary contact. */
  companyContacts: PrimaryContact[];
  sequences: Sequence[];
  mailboxId: string | null;
  mailboxReady: boolean;
};

export function EnrollLeadDialog({
  open,
  objectKey,
  leadId,
  leadName,
  onClose,
  onEnrolled,
}: {
  open: boolean;
  objectKey: string;
  leadId: string;
  leadName: string;
  onClose: () => void;
  onEnrolled: () => void;
}) {
  const [data, setData] = useState<Loaded | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [contactId, setContactId] = useState('');
  const [sequenceId, setSequenceId] = useState('');
  const [previewOpen, setPreviewOpen] = useState(false);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    setData(null);
    setError(null);
    setContactId('');
    setPreviewOpen(false);
    (async () => {
      const [primary, sequencesPage, mailbox] = await Promise.all([
        primaryContactOf(objectKey, leadId),
        listSequences({ status: 'active', limit: 100 }),
        getMyMailbox(),
      ]);
      let company: Loaded['company'] = null;
      let companyContacts: PrimaryContact[] = [];
      if (!primary) {
        company = await primaryCompanyOf(objectKey, leadId);
        if (company) {
          const page = await listLinkedRecords({
            fromType: 'company',
            fromId: company.id,
            toType: 'contact',
            limit: 100,
            card: 'true',
          });
          companyContacts = page.data.map((c) => ({
            id: c.id,
            name: c.name ?? 'Unnamed contact',
            email: c.email ?? null,
          }));
        }
      }
      if (!alive) return;
      setData({
        primary,
        company,
        companyContacts,
        sequences: sequencesPage.data,
        mailboxId: mailbox.id ?? null,
        mailboxReady: Boolean(mailbox.connected && mailbox.status === 'connected' && mailbox.id),
      });
      setContactId(primary?.id ?? '');
      setSequenceId(sequencesPage.data[0]?.id ?? '');
    })().catch((err: unknown) => alive && setError(errorText(err)));
    return () => {
      alive = false;
    };
  }, [open, objectKey, leadId]);

  const contact = data?.primary ?? data?.companyContacts.find((c) => c.id === contactId) ?? null;
  const sequence = data?.sequences.find((s) => s.id === sequenceId) ?? null;
  const blocked = !data?.mailboxReady || !contact || !sequence;

  return (
    <>
      <CrmModal id="leadEnrollModal" open={open && !previewOpen} onClose={onClose}>
        <ModalHeader
          id="leadEnrollModal"
          title={`Enroll ${leadName} in a sequence`}
          onClose={onClose}
        />
        <div className="modal__body">
          {error ? <Alert tone="danger">{error}</Alert> : null}
          {!data && !error ? <p className="crm-text-body-secondary">Loading…</p> : null}
          {data ? (
            <>
              {!data.mailboxReady ? (
                <Alert tone="warning">
                  Connect your mailbox in Settings &gt; Email before enrolling contacts.
                </Alert>
              ) : null}
              <div className="field">
                <span className="field__label">Contact</span>
                {data.primary ? (
                  <p>
                    <strong>{data.primary.name}</strong>{' '}
                    <span className="crm-text-body-secondary">
                      (the lead&apos;s primary contact)
                    </span>
                  </p>
                ) : data.company && data.companyContacts.length > 0 ? (
                  <>
                    <p className="crm-text-body-secondary">
                      This lead has no contact, only {data.company.name}. Pick which of its contacts
                      to enroll.
                    </p>
                    <select
                      className="input"
                      aria-label="Contact to enroll"
                      value={contactId}
                      onChange={(e) => setContactId(e.target.value)}
                    >
                      <option value="">Choose a contact</option>
                      {data.companyContacts.map((c) => (
                        <option key={c.id} value={c.id}>
                          {c.name}
                        </option>
                      ))}
                    </select>
                  </>
                ) : (
                  <p className="crm-text-body-secondary" role="alert">
                    This lead has no contact
                    {data.company ? `, and ${data.company.name} has no contacts` : ''}. Link a
                    contact to the lead first.
                  </p>
                )}
              </div>
              <div className="field crm-mt-3">
                <label className="field__label" htmlFor="leadEnrollSequence">
                  Sequence
                </label>
                {data.sequences.length === 0 ? (
                  <p className="crm-text-body-secondary">No active sequences.</p>
                ) : (
                  <select
                    className="input"
                    id="leadEnrollSequence"
                    value={sequenceId}
                    onChange={(e) => setSequenceId(e.target.value)}
                  >
                    {data.sequences.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.name}
                      </option>
                    ))}
                  </select>
                )}
              </div>
            </>
          ) : null}
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={blocked}
            onClick={() => setPreviewOpen(true)}
          >
            Preview enrollment
          </button>
        </div>
      </CrmModal>
      {contact ? (
        <EnrollPreviewDialog
          open={open && previewOpen}
          onClose={() => setPreviewOpen(false)}
          sequence={sequence}
          // Sequences QA: the primary contact's email, for the review's To: line.
          contact={{ id: contact.id, name: contact.name, email: contact.email }}
          onEnrolled={() => {
            setPreviewOpen(false);
            onEnrolled();
          }}
        />
      ) : null}
    </>
  );
}
