'use client';

import { Fragment, useEffect, useMemo, useState, type ReactNode } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import type { EmailTemplate } from '@/features/inbox/types';
import { sequenceReport } from '@/features/sequences/api.client';
import type { SequenceReportRow, SequenceSettings, SequenceStep } from '@/features/sequences/types';
import { addDays } from '@/lib/utils/timezone';
import { cn } from '@/lib/utils/cn';
import { HsSwitch } from '@/features/settings/ui/calling/HsSwitch';
import { DropMenu } from './DropMenu';
import {
  AddEmailDrawer,
  EmailTypeDrawer,
  PencilIcon,
  REP_KINDS,
  ReplaceIcon,
  TaskStepDrawer,
  StepEmailEditor,
  TemplatePickerDrawer,
  TokenText,
  repKindOf,
  type EmailStepOption,
  type EmailThreading,
  type RepKind,
} from './DynamicStepDrawers';
import { StepChoiceGrid } from './SequenceStartPicker';
import { BusinessDaysPopover, DEFAULT_STEP_DELAY } from './shared';
import { useSendTestEmail } from './useSendTestEmail';

type Wait = Extract<SequenceStep, { type: 'wait' }>;

/** The automated outreach's closing wait (the time the contact gets to engage). */
const END_WAIT: Wait = { type: 'wait', amount: 1, unit: 'business_days', lane: 'auto' };
/** HubSpot's "Delay: 1 business day" between steps. */
const GAP_WAIT: Wait = {
  type: 'wait',
  amount: DEFAULT_STEP_DELAY,
  unit: 'business_days',
  lane: 'auto',
};
const REP_WAIT: Wait = { ...GAP_WAIT, lane: 'rep' };

const isRep = (step: SequenceStep) => step.lane === 'rep';

function waitText(step: Wait): string {
  const unit = step.unit === 'business_days' ? 'business day' : 'day';
  return `${step.amount} ${unit}${step.amount === 1 ? '' : 's'}`;
}

const plain = (html: string | null | undefined) =>
  (html ?? '')
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/p>/gi, '\n')
    .replace(/<[^>]*>/g, '')
    .replace(/&nbsp;/g, ' ')
    .trim();

function Icon({ kind }: { kind: 'send' | RepKind }) {
  const paths: Record<string, ReactNode> = {
    send: <path d="m21 3-9.5 9.5M21 3l-6.5 18-3-8.5L3 9.5z" />,
    manual_email: (
      <>
        <rect x="3" y="5" width="18" height="14" rx="2" />
        <path d="m3 7 9 6 9-6" />
      </>
    ),
    call_task: (
      <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2" />
    ),
    todo: <path d="M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2" />,
    linkedin_message: (
      <>
        <rect x="3" y="3" width="18" height="18" rx="3" />
        <path d="M8 10v7M8 7v.5M12 17v-4a2 2 0 0 1 4 0v4M12 10v7" />
      </>
    ),
    linkedin_connect: (
      <>
        <rect x="3" y="3" width="18" height="18" rx="3" />
        <path d="M8 10v7M8 7v.5M12 17v-4a2 2 0 0 1 4 0v4M12 10v7" />
      </>
    ),
  };
  return (
    <span className={cn('dyn-icon', `dyn-icon--${kind}`)} aria-hidden>
      <svg
        viewBox="0 0 24 24"
        width="16"
        height="16"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      >
        {paths[kind]}
      </svg>
    </span>
  );
}

export function Kebab({
  label,
  items,
  text,
}: {
  label: string;
  items: Parameters<typeof DropMenu>[0]['items'];
  /** HubSpot's step cards: a text button ("Actions ▾") instead of the ⋮ icon. */
  text?: string;
}) {
  return (
    <DropMenu
      trigger={<span aria-hidden>{text ? `${text} ▾` : '⋮'}</span>}
      triggerClassName={cn('dyn-kebab', text && 'dyn-kebab--text')}
      ariaLabel={label}
      items={items}
    />
  );
}

/** Sequences QA steps BUG-02: the design's hint on a delay counted in business days. */
export function WeekendsHint() {
  return (
    <span
      className="seqa-info"
      role="img"
      aria-label="Weekends are skipped"
      title="Weekends are skipped"
    >
      ⓘ
    </span>
  );
}

type EmailStep = Extract<SequenceStep, { type: 'automated_email' | 'manual_email' }>;

/** HubSpot's "↩ REPLY" / "✉ NEW THREAD" chip. */
export function ThreadChip({ reply }: { reply: boolean }) {
  return (
    <span className={cn('dyn-chip', reply && 'dyn-chip--reply')}>
      {reply ? '↩ REPLY' : '✉ NEW THREAD'}
    </span>
  );
}

/** An email step's card body: the template, subject, body (see more / less) and its numbers. */
export function EmailCardBody({
  step,
  template,
  row,
  open,
  onToggle,
  templatesLoading = false,
  versionTools,
  footer,
  replySubject,
}: {
  step: EmailStep;
  /** The subject of the email this one replies to (a reply has none of its own). */
  replySubject?: string | null;
  template: EmailTemplate | null;
  /** The template list is still loading: its body is not known yet. */
  templatesLoading?: boolean;
  row: SequenceReportRow | undefined;
  open: boolean;
  onToggle: () => void;
  /** Sequences #82: the Version A row's edit (pencil) and more (…) buttons. */
  versionTools?: ReactNode;
  /** Sequences #82: under the numbers, e.g. "+ Add A/B test". */
  footer?: ReactNode;
}) {
  const subject = template?.subject ?? step.subject ?? '';
  const body = plain(template?.bodyHtml ?? step.bodyHtml);
  const rate = (part: number, whole: number) =>
    whole ? `${Math.round((part / whole) * 100)}%` : '0%';
  return (
    <div className="dyn-email">
      <div className={cn('dyn-email__row', versionTools ? 'dyn-email__row--tools' : undefined)}>
        <span>
          {/* HubSpot: "Template <name>"; "Version A" only with an A/B test. */}
          <strong>{'variantB' in step && step.variantB ? 'Version A' : 'Template'}</strong>{' '}
          {template?.name ?? (step.templateId ? 'Template' : 'Own email')}
        </span>
        {versionTools}
      </div>
      <div className="dyn-email__row">
        <strong>Subject:</strong>{' '}
        {step.threadAsReply ? (
          replySubject ? (
            <TokenText text={replySubject} />
          ) : (
            <span className="crm-text-muted">Re: the earlier email (sent in its thread)</span>
          )
        ) : subject ? (
          <TokenText text={subject} />
        ) : (
          <span className="crm-text-muted">No subject</span>
        )}
        <ThreadChip reply={step.threadAsReply} />
      </div>
      <div className="dyn-email__body">
        <p className={cn(!open && 'is-clamped')}>
          {body ? (
            <TokenText text={body} />
          ) : step.templateId && !template ? (
            templatesLoading ? (
              'Loading the email…'
            ) : (
              'This template was deleted or is not shared with you.'
            )
          ) : (
            'No body yet.'
          )}
        </p>
        {body.length > 80 ? (
          <button type="button" className="seqz-back" onClick={onToggle}>
            {open ? '⌃ See less' : '⌄ See more'}
          </button>
        ) : null}
      </div>
      {/* HubSpot shows no numbers until the sequence has sent something. */}
      {row ? (
        <dl className="dyn-email__stats">
          {/* HubSpot's order: Sends, Opens, Clicks, Replies, Meetings (QA 14 Oct #40). */}
          <div>
            <dt>{(row?.sent ?? 0).toLocaleString()}</dt>
            <dd>Sent</dd>
          </div>
          <div>
            <dt>{rate(row?.opened ?? 0, row?.sent ?? 0)}</dt>
            <dd>Opens</dd>
          </div>
          <div>
            <dt>{rate(row?.clicked ?? 0, row?.sent ?? 0)}</dt>
            <dd>Clicks</dd>
          </div>
          <div>
            <dt>{rate(row?.replied ?? 0, row?.sent ?? 0)}</dt>
            <dd>Replies</dd>
          </div>
          <div>
            <dt>{rate(row?.meetingsBooked ?? 0, row?.sent ?? 0)}</dt>
            <dd>Meetings</dd>
          </div>
        </dl>
      ) : null}
      {footer}
    </div>
  );
}

/** Per-step numbers for the last year (sent, opens, replies, meetings), by step index. */
export function useStepStats(sequenceId: string, timezone: string) {
  const [stats, setStats] = useState<Map<number, SequenceReportRow>>(new Map());
  useEffect(() => {
    // A sequence not saved yet has no numbers.
    if (!sequenceId) return;
    let cancelled = false;
    const today = new Date().toLocaleDateString('en-CA', { timeZone: timezone });
    sequenceReport({ from: addDays(today, -365), to: today, groupBy: 'step', sequenceId }).then(
      (report) => {
        if (cancelled) return;
        setStats(
          new Map(report.data.flatMap((r) => (r.stepIndex === null ? [] : [[r.stepIndex, r]]))),
        );
      },
      () => {
        if (!cancelled) setStats(new Map());
      },
    );
    return () => {
      cancelled = true;
    };
  }, [sequenceId, timezone]);
  return stats;
}

/** The step's subject: its template's, or its own. */
const subjectOfEmail = (step: SequenceStep, template: EmailTemplate | null): string => {
  if (step.type !== 'automated_email' && step.type !== 'manual_email') return '';
  return template?.subject ?? step.subject ?? '';
};

/** A pill that opens HubSpot's "Business days" popover (delay chips, "End enrollment in"). */
function DelayPill({
  prefix,
  step,
  none = false,
  canEdit,
  open,
  onOpen,
  onClose,
  onSave,
}: {
  prefix: string;
  step: Wait | null;
  /** A rep step saved with no delay before it: "None", set from the popover. */
  none?: boolean;
  canEdit: boolean;
  open: boolean;
  onOpen: () => void;
  onClose: () => void;
  onSave: (amount: number) => void;
}) {
  const unit = step?.unit ?? 'business_days';
  return (
    <span className="seq-bdp-wrap">
      <button
        type="button"
        className="dyn-gap__chip"
        disabled={!canEdit}
        aria-haspopup="dialog"
        aria-expanded={open}
        onClick={onOpen}
      >
        <span aria-hidden>⏱</span> {prefix}: {step && !none ? waitText(step) : 'None'}
      </button>
      {open ? (
        <BusinessDaysPopover
          value={step && !none ? step.amount : 0}
          unit={unit}
          onSave={onSave}
          onCancel={onClose}
        />
      ) : null}
    </span>
  );
}

/**
 * The Steps view of a dynamic sequence (design: two lanes). Automated outreach on the left
 * (automated emails, waits between them, and the closing wait), the engagement signal between
 * the lanes, and the rep-led task steps on the right. Edits go to `onStepsChange` /
 * `onSettingsChange`; the editor's Save button saves them.
 */
export function DynamicSequenceCanvas({
  sequenceId,
  timezone,
  steps,
  settings,
  canEdit,
  templates,
  meName,
  ownerNameOf,
  onTemplateCreated,
  onTemplateUpdated,
  onStepsChange,
  onSettingsChange,
  onOpenAutomate,
}: {
  sequenceId: string;
  timezone: string;
  steps: SequenceStep[];
  settings: SequenceSettings;
  canEdit: boolean;
  templates: EmailTemplate[] | null;
  meName: string;
  ownerNameOf: (userId: string | undefined) => string | null;
  onTemplateCreated: (template: EmailTemplate) => void;
  /** A template changed with Edit email › Save. */
  onTemplateUpdated?: (template: EmailTemplate) => void;
  onStepsChange: (steps: SequenceStep[]) => void;
  onSettingsChange: (settings: SequenceSettings) => void;
  /** The "Go to the automate tab" link of the Unenroll criteria tooltip. */
  onOpenAutomate?: () => void;
}) {
  const signal = settings.dynamic ?? { signalOpens: 2, signalClicks: 1 };
  const repStart = useMemo(() => {
    const i = steps.findIndex(isRep);
    return i === -1 ? steps.length : i;
  }, [steps]);
  const auto = steps.slice(0, repStart);
  const rep = steps.slice(repStart);
  const endWait = auto.at(-1)?.type === 'wait' ? (auto.at(-1) as Wait) : null;
  const autoBody = endWait ? auto.slice(0, -1) : auto;
  const emails = autoBody.filter((s) => s.type === 'automated_email');
  /** The rep lane's task steps (not its waits), with their place in `steps`. */
  const repTasks = rep.flatMap((step, offset) =>
    step.type === 'wait' ? [] : [{ step, index: repStart + offset }],
  );

  /** The email being added or replaced: `insertAt` is where in `steps` a new one goes. */
  const [emailTarget, setEmailTarget] = useState<
    { insertAt: number } | { replace: number } | undefined
  >(undefined);
  /** The email step open in Edit email (QA 14 Oct #43). */
  const [editEmail, setEditEmail] = useState<number | null>(null);
  /** The email whose threading is being edited (Edit threading). */
  const [threadEdit, setThreadEdit] = useState<number | null>(null);
  /** A task step being added (`insert`: where, and whether it follows a delay) or edited. */
  const [task, setTask] = useState<{
    kind: RepKind;
    index: number | null;
    insert?: { at: number; withWait: boolean };
  } | null>(null);
  /** HubSpot's inline "Configure your next step" cards: the gap they are open in. */
  const [autoGap, setAutoGap] = useState<number | null>(null);
  const [repGap, setRepGap] = useState<number | null>(null);
  /** The delay popover that is open: "w<step index>", "n<task step index>" or "end". */
  const [delayOpen, setDelayOpen] = useState<string | null>(null);
  const [signalOpen, setSignalOpen] = useState(false);
  const toast = useToast();
  const [expanded, setExpanded] = useState<Set<number>>(new Set());
  const stats = useStepStats(sequenceId, timezone);

  const set = (next: SequenceStep[]) => onStepsChange(next);
  const templateOf = (id: string | null) => templates?.find((t) => t.id === id) ?? null;

  /** The first email of the sequence starts a thread: nothing before it to reply to. */
  const withFirstEmailNew = (next: SequenceStep[]): SequenceStep[] => {
    const first = next.findIndex((s) => s.type === 'automated_email' || s.type === 'manual_email');
    return next.map((s, i) =>
      i === first && (s.type === 'automated_email' || s.type === 'manual_email') && s.threadAsReply
        ? { ...s, threadAsReply: false }
        : s,
    );
  };

  /** The emails before `before` (a step index), as "Step N: <subject>" for a reply to choose. */
  const emailOptionsBefore = (before: number): EmailStepOption[] =>
    steps
      .slice(0, before)
      .flatMap((s, i) => (s.type === 'automated_email' || s.type === 'manual_email' ? [i] : []))
      .map((stepIndex, n) => {
        const s = steps[stepIndex]!;
        const subject = subjectOfEmail(s, templateOf('templateId' in s ? s.templateId : null));
        return {
          id: String(stepIndex),
          label: `Step ${n + 1}: ${subject || (s.type === 'manual_email' ? 'Manual email' : 'No subject')}`,
        };
      });

  /** The subject a reply keeps: the first email of its thread's. */
  const threadSubject = (index: number): string | null => {
    for (let i = index - 1; i >= 0; i--) {
      const s = steps[i]!;
      if (s.type !== 'automated_email' && s.type !== 'manual_email') continue;
      if (s.threadAsReply) continue;
      return subjectOfEmail(s, templateOf(s.templateId)) || null;
    }
    return null;
  };

  // --- Automated outreach ----------------------------------------------------------------------

  const addEmail = (template: EmailTemplate, threading: EmailThreading, insertAt: number) => {
    const email: SequenceStep = {
      type: 'automated_email',
      templateId: template.id,
      subject: null,
      bodyHtml: null,
      threadAsReply: threading.reply,
      lane: 'auto',
    };
    if (emails.length === 0) {
      set([email, endWait ?? { ...END_WAIT }, ...rep]);
    } else {
      const base = endWait ? steps : [...autoBody, { ...END_WAIT }, ...rep];
      const next = [...base];
      next.splice(insertAt, 0, { ...GAP_WAIT }, email);
      set(next);
    }
    setEmailTarget(undefined);
    setAutoGap(null);
  };

  const replaceTemplate = (index: number, template: EmailTemplate) => {
    set(
      steps.map((s, i) =>
        i === index && 'templateId' in s
          ? { ...s, templateId: template.id, subject: null, bodyHtml: null }
          : s,
      ),
    );
    setEmailTarget(undefined);
  };

  const removeAuto = (index: number) => {
    // An email goes with the wait before it (or the one after, for the first email).
    const before = steps[index - 1];
    const after = steps[index + 1];
    const drop = new Set([index]);
    if (before?.type === 'wait' && index - 1 >= 0 && before.lane !== 'rep') drop.add(index - 1);
    else if (after?.type === 'wait' && index + 1 < repStart - (endWait ? 1 : 0))
      drop.add(index + 1);
    set(withFirstEmailNew(steps.filter((_, i) => !drop.has(i))));
    // Sequences QA steps BUG-03: the design's toasts (sequences-steps.js).
    toast('Step deleted', 'success');
  };

  /** Moves an email past the next email; the delays stay where they are. */
  const moveEmail = (index: number, by: -1 | 1) => {
    const target = neighbour(autoBody, index, by, (s) => s.type === 'automated_email');
    if (target === null) return;
    const next = [...steps];
    [next[index], next[target]] = [next[target]!, next[index]!];
    set(withFirstEmailNew(next));
  };

  const setWait = (index: number, amount: number) => {
    set(steps.map((s, i) => (i === index && s.type === 'wait' ? { ...s, amount } : s)));
    setDelayOpen(null);
  };

  const setEndWait = (amount: number) => {
    const wait: Wait = { ...(endWait ?? END_WAIT), amount };
    set([...autoBody, wait, ...rep]);
    setDelayOpen(null);
  };

  // --- Rep-led outreach ------------------------------------------------------------------------

  const saveTask = (step: SequenceStep) => {
    if (!task) return;
    if (task.index !== null) {
      set(steps.map((s, i) => (i === task.index ? step : s)));
    } else {
      const at = task.insert?.at ?? steps.length;
      const next = [...steps];
      next.splice(at, 0, ...(task.insert?.withWait ? [{ ...REP_WAIT }, step] : [step]));
      set(next);
    }
    setTask(null);
    setRepGap(null);
  };

  /** Swaps a task step with the next one; the delays stay where they are. */
  const moveRep = (index: number, by: -1 | 1) => {
    const target = neighbour(steps, index, by, (s) => isRep(s) && s.type !== 'wait');
    if (target === null) return;
    const next = [...steps];
    [next[index], next[target]] = [next[target]!, next[index]!];
    set(next);
  };

  const removeRep = (index: number) => {
    // A step goes with the delay before it (or the one after, for the first step).
    const drop = new Set([index]);
    const before = steps[index - 1];
    const after = steps[index + 1];
    if (before?.type === 'wait' && isRep(before)) drop.add(index - 1);
    else if (after?.type === 'wait' && isRep(after)) drop.add(index + 1);
    set(steps.filter((_, i) => !drop.has(i)));
  };

  /** A rep task step's delay (the wait right before it) is set, or added when it had none. */
  const setRepDelay = (taskIndex: number, amount: number) => {
    const before = steps[taskIndex - 1];
    if (before?.type === 'wait' && isRep(before)) setWait(taskIndex - 1, amount);
    else {
      const next = [...steps];
      next.splice(taskIndex, 0, { ...REP_WAIT, amount });
      set(next);
      setDelayOpen(null);
    }
  };

  /** Where in `steps` a task step added after the `n`th task (0-based) goes. */
  const repInsertAt = (n: number) => {
    const following = repTasks[n + 1];
    if (!following) return { at: steps.length, withWait: true };
    const before = steps[following.index - 1];
    return {
      at: before?.type === 'wait' && isRep(before) ? following.index - 1 : following.index,
      withWait: true,
    };
  };

  // --- Stats -----------------------------------------------------------------------------------

  const autoDays =
    autoBody.reduce((sum, s) => sum + (s.type === 'wait' ? s.amount : 0), 0) +
    (endWait?.amount ?? 0) +
    (emails.length ? 1 : 0) +
    rep.reduce((sum, s) => sum + (s.type === 'wait' ? s.amount : 0), 0);

  const testEmail = useSendTestEmail();

  const emailCard = (step: SequenceStep, index: number) => {
    if (step.type !== 'automated_email') return null;
    const template = templateOf(step.templateId);
    return (
      <article key={index} className="dyn-card">
        <header className="dyn-card__head">
          <Icon kind="send" />
          <strong>Automated Email</strong>
          {canEdit ? (
            <Kebab
              label="Automated email actions"
              text="Actions"
              items={[
                {
                  key: 'thread',
                  label: 'Edit threading',
                  onSelect: () => setThreadEdit(index),
                },
                {
                  key: 'up',
                  label: 'Move up',
                  disabled:
                    neighbour(autoBody, index, -1, (s) => s.type === 'automated_email') === null,
                  onSelect: () => moveEmail(index, -1),
                },
                {
                  key: 'down',
                  label: 'Move down',
                  disabled:
                    neighbour(autoBody, index, 1, (s) => s.type === 'automated_email') === null,
                  onSelect: () => moveEmail(index, 1),
                },
                {
                  key: 'test',
                  label: 'Send test to me',
                  disabled: Boolean(testEmail.blocked(step, template)),
                  title: testEmail.blocked(step, template) ?? undefined,
                  onSelect: () => void testEmail.send(step, template),
                },
                {
                  key: 'remove',
                  label: 'Delete',
                  separated: true,
                  onSelect: () => removeAuto(index),
                },
              ]}
            />
          ) : null}
        </header>
        <EmailCardBody
          step={step}
          template={template}
          templatesLoading={templates === null}
          row={stats.get(index)}
          replySubject={step.threadAsReply ? threadSubject(index) : null}
          versionTools={
            canEdit ? (
              // Sequences QA steps BUG-10: as HubSpot's dynamic sequences, "Edit template" and
              // "Replace template" sit on the template row (not in Actions).
              <span className="dyn-email__tools">
                <button
                  type="button"
                  className="dyn-icon-btn"
                  aria-label="Edit template"
                  title={step.templateId && !template ? 'Template not available' : 'Edit template'}
                  disabled={Boolean(step.templateId) && !template}
                  onClick={() => setEditEmail(index)}
                >
                  <PencilIcon />
                </button>
                <button
                  type="button"
                  className="dyn-icon-btn"
                  aria-label="Replace template"
                  title="Replace template"
                  onClick={() => setEmailTarget({ replace: index })}
                >
                  <ReplaceIcon />
                </button>
              </span>
            ) : null
          }
          open={expanded.has(index)}
          onToggle={() =>
            setExpanded((cur) => {
              const next = new Set(cur);
              if (next.has(index)) next.delete(index);
              else next.add(index);
              return next;
            })
          }
        />
      </article>
    );
  };

  const waitChip = (step: SequenceStep, index: number) =>
    step.type === 'wait' ? (
      <div key={index} className="dyn-gap">
        <span className="dyn-gap__line" aria-hidden />
        {/* Sequences QA steps BUG-02: HubSpot's and the design's "Delay: N business days". */}
        <DelayPill
          prefix="Delay"
          step={step}
          canEdit={canEdit}
          open={delayOpen === `w${index}`}
          onOpen={() => setDelayOpen(`w${index}`)}
          onClose={() => setDelayOpen(null)}
          onSave={(n) => setWait(index, n)}
        />
        <span className="dyn-gap__line" aria-hidden />
      </div>
    ) : null;

  /** HubSpot's "+" (tooltip "Add") between two steps. */
  const plus = (onClick: () => void, key?: string) =>
    canEdit ? (
      <button
        key={key}
        type="button"
        className="dyn-add"
        aria-label="Add"
        title="Add"
        onClick={onClick}
      >
        +
      </button>
    ) : null;

  /** The rep step kinds as the chooser lists them (the standard picker's, LinkedIn grouped). */
  const followupChoices = (insert: { at: number; withWait: boolean } | undefined) => (
    <StepChoiceGrid
      repOnly
      disabled={!canEdit}
      onPick={(kind) => kind !== 'automated_email' && setTask({ kind, index: null, insert })}
    />
  );

  const repCard = (step: SequenceStep, index: number, n: number) => {
    const kind = repKindOf(step);
    if (!kind) return null;
    const meta = REP_KINDS.find((k) => k.key === kind)!;
    const title = 'title' in step && step.title ? step.title : '';
    return (
      <article key={index} className="dyn-card dyn-card--rep">
        <header className="dyn-card__head">
          <Icon kind={kind} />
          <span className="dyn-card__title">
            {/* Sequences QA steps BUG-01: HubSpot's card name, "LinkedIn InMail Task". */}
            <strong>
              {meta.heading}
              {step.pauseUntilDone ? <span className="dyn-badge">PAUSES SEQUENCE</span> : null}
            </strong>
          </span>
          {canEdit ? (
            <Kebab
              label={`${meta.label} actions`}
              text="Actions"
              items={[
                { key: 'edit', label: 'Edit task', onSelect: () => setTask({ kind, index }) },
                {
                  key: 'up',
                  label: 'Move up',
                  disabled: n === 0,
                  onSelect: () => moveRep(index, -1),
                },
                {
                  key: 'down',
                  label: 'Move down',
                  disabled: n === repTasks.length - 1,
                  onSelect: () => moveRep(index, 1),
                },
                {
                  key: 'remove',
                  label: 'Delete',
                  separated: true,
                  onSelect: () => removeRep(index),
                },
              ]}
            />
          ) : null}
        </header>
        <p className="dyn-card__note">
          <strong>Task title:</strong> {title ? <TokenText text={title} /> : null}
        </p>
        {step.type === 'manual_email' ? (
          <p className="dyn-card__note">
            <ThreadChip reply={step.threadAsReply} />
          </p>
        ) : null}
      </article>
    );
  };

  const taskEdit = task && task.index !== null ? (steps[task.index] ?? null) : null;
  const taskBefore = task ? (task.index ?? task.insert?.at ?? steps.length) : 0;

  return (
    <div className="dyn">
      <section className="dyn-stats" aria-label="Sequence summary">
        <div>
          <span>Automated steps</span>
          <strong>{emails.length}</strong>
        </div>
        <div>
          <span>Days to complete</span>
          <strong>{autoDays}</strong>
        </div>
        <div>
          <span>Manual steps</span>
          <strong>{repTasks.length}</strong>
        </div>
        <div>
          <span>
            Unenroll criteria{' '}
            <span className="dyn-tip">
              <span className="seqa-info" tabIndex={0} aria-label="About unenroll criteria">
                ⓘ
              </span>
              <span className="dyn-tip__pop" role="tooltip">
                {onOpenAutomate ? (
                  <button type="button" className="dyn-link-btn" onClick={onOpenAutomate}>
                    Go to the automate tab
                  </button>
                ) : (
                  'Go to the automate tab'
                )}{' '}
                to add and review custom criteria.
              </span>
            </span>
          </span>
          <strong>2</strong>
        </div>
      </section>

      {emails.length === 0 ? (
        <section className="dyn-initial">
          <span className="dyn-initial__line" aria-hidden />
          <div className="dyn-initial__card">
            <h3>Configure your initial step</h3>
            <p>All contacts will receive this first step</p>
            <button
              type="button"
              className="dyn-choice"
              disabled={!canEdit}
              onClick={() => setEmailTarget({ insertAt: autoBody.length })}
            >
              <Icon kind="send" />
              <span>
                <strong>Automated email</strong>
                <small>Automatically send an email for me</small>
              </span>
            </button>
          </div>
        </section>
      ) : (
        <div className="dyn-lanes">
          <section className="dyn-lane" aria-label="Automated outreach">
            <header className="dyn-lane__head dyn-lane__head--auto">
              <strong>Automated outreach</strong>
              <span>Leads will receive automated steps until they engage</span>
            </header>
            {autoBody.map((step, i) => {
              if (step.type !== 'automated_email') return waitChip(step, i);
              return (
                <Fragment key={i}>
                  {emailCard(step, i)}
                  {autoGap === i + 1 ? (
                    <div className="dyn-initial__card dyn-next">
                      <h3>Configure your next step</h3>
                      <p>Any contacts that have not engaged will receive this step</p>
                      <button
                        type="button"
                        className="dyn-choice"
                        onClick={() => setEmailTarget({ insertAt: i + 1 })}
                      >
                        <Icon kind="send" />
                        <span>
                          <strong>Automated email</strong>
                          <small>Automatically send an email for me</small>
                        </span>
                      </button>
                      <button
                        type="button"
                        className="btn-crm btn-crm--outline"
                        onClick={() => setAutoGap(null)}
                      >
                        Remove step
                      </button>
                    </div>
                  ) : (
                    plus(() => setAutoGap(i + 1))
                  )}
                </Fragment>
              );
            })}
            <span className="dyn-done" aria-hidden>
              ✓
            </span>
            <div className="dyn-end">
              <DelayPill
                prefix="End enrollment in"
                step={endWait ?? END_WAIT}
                canEdit={canEdit}
                open={delayOpen === 'end'}
                onOpen={() => setDelayOpen('end')}
                onClose={() => setDelayOpen(null)}
                onSave={setEndWait}
              />
            </div>
          </section>

          <div className="dyn-signal">
            <div className="dyn-signal__row">
              <span className="dyn-signal__dot" aria-hidden />
              <span className="dyn-signal__line" aria-hidden />
              <div className="dyn-signal__box">
                <button
                  type="button"
                  className="dyn-signal__btn"
                  aria-haspopup="dialog"
                  onClick={() => setSignalOpen(true)}
                  disabled={!canEdit}
                >
                  Signals:{' '}
                  {[
                    signal.signalOpens !== null
                      ? `${signal.signalOpens} open${signal.signalOpens === 1 ? '' : 's'}`
                      : null,
                    signal.signalClicks !== null
                      ? `${signal.signalClicks} click${signal.signalClicks === 1 ? '' : 's'}`
                      : null,
                  ]
                    .filter(Boolean)
                    .join(' or ')}{' '}
                  <CrmIcon name="settings" className="iconSize-14" />
                </button>
              </div>
              <span className="dyn-signal__line" aria-hidden />
            </div>
            <span className="dyn-signal__elbow" aria-hidden />
          </div>

          <section className="dyn-lane dyn-lane--rep" aria-label="Rep-led outreach">
            <header className="dyn-lane__head dyn-lane__head--rep">
              <strong>Rep-led outreach</strong>
              <span>
                As soon as a lead engages, the sequence will start to queue up manual steps
              </span>
            </header>
            {repTasks.map(({ step, index }, n) => {
              const delayBefore = steps[index - 1];
              const hasDelay = delayBefore?.type === 'wait' && isRep(delayBefore);
              return (
                <Fragment key={index}>
                  {n > 0 ? (
                    <div className="dyn-gap">
                      <span className="dyn-gap__line" aria-hidden />
                      <DelayPill
                        prefix="Delay"
                        step={hasDelay ? delayBefore : REP_WAIT}
                        none={!hasDelay}
                        canEdit={canEdit}
                        open={delayOpen === `n${index}`}
                        onOpen={() => setDelayOpen(`n${index}`)}
                        onClose={() => setDelayOpen(null)}
                        onSave={(amount) => setRepDelay(index, amount)}
                      />
                      <span className="dyn-gap__line" aria-hidden />
                    </div>
                  ) : null}
                  {repCard(step, index, n)}
                  {repGap === n + 1 ? (
                    <div className="dyn-followups dyn-next">
                      <h3>Create the next dynamic follow-up step</h3>
                      <p>
                        Choose the next step that the sequence will perform for engaged contacts
                      </p>
                      {followupChoices(repInsertAt(n))}
                      <button
                        type="button"
                        className="btn-crm btn-crm--outline"
                        onClick={() => setRepGap(null)}
                      >
                        Remove step
                      </button>
                    </div>
                  ) : (
                    plus(() => setRepGap(n + 1))
                  )}
                </Fragment>
              );
            })}
            {repTasks.length === 0 ? (
              <div className="dyn-followups">
                <h3>Create dynamic follow-up steps</h3>
                <p>
                  Configure a series of task steps that starts as soon as a contact engages with
                  your automated outreach
                </p>
                {followupChoices({ at: steps.length, withWait: false })}
              </div>
            ) : (
              <>
                <span className="dyn-done" aria-hidden>
                  ✓
                </span>
                <span className="dyn-completed">Completed</span>
              </>
            )}
          </section>
        </div>
      )}

      <SignalsDrawer
        open={signalOpen}
        signal={signal}
        onClose={() => setSignalOpen(false)}
        onSave={(next) => {
          onSettingsChange({ ...settings, dynamic: next });
          setSignalOpen(false);
        }}
      />
      <StepEmailEditor
        steps={steps}
        index={editEmail}
        templates={templates}
        meName={meName}
        onClose={() => setEditEmail(null)}
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onStepsChange={onStepsChange}
      />
      <AddEmailDrawer
        open={emailTarget !== undefined && 'insertAt' in emailTarget}
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        emailSteps={
          emailTarget && 'insertAt' in emailTarget ? emailOptionsBefore(emailTarget.insertAt) : []
        }
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onClose={() => setEmailTarget(undefined)}
        onAdd={(template, threading) =>
          emailTarget && 'insertAt' in emailTarget
            ? addEmail(template, threading, emailTarget.insertAt)
            : undefined
        }
      />
      <TemplatePickerDrawer
        open={emailTarget !== undefined && 'replace' in emailTarget}
        title="Choose email template"
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        currentId={
          emailTarget && 'replace' in emailTarget
            ? (() => {
                const s = steps[emailTarget.replace];
                return s && 'templateId' in s ? s.templateId : null;
              })()
            : null
        }
        onClose={() => setEmailTarget(undefined)}
        onTemplateCreated={onTemplateCreated}
        onPick={(template) =>
          emailTarget && 'replace' in emailTarget
            ? replaceTemplate(emailTarget.replace, template)
            : undefined
        }
      />
      <EmailTypeDrawer
        open={threadEdit !== null}
        emailSteps={threadEdit === null ? [] : emailOptionsBefore(threadEdit)}
        value={{
          reply: (() => {
            const s = threadEdit === null ? null : steps[threadEdit];
            return s?.type === 'automated_email' ? s.threadAsReply : false;
          })(),
          replyToStepId: null,
        }}
        onClose={() => setThreadEdit(null)}
        onSave={({ reply }) => {
          set(
            steps.map((s, i) =>
              i === threadEdit && s.type === 'automated_email' ? { ...s, threadAsReply: reply } : s,
            ),
          );
          setThreadEdit(null);
        }}
      />
      <TaskStepDrawer
        open={task !== null}
        kind={task?.kind ?? 'call_task'}
        initial={taskEdit}
        templates={templates}
        ownerNameOf={ownerNameOf}
        meName={meName}
        emailSteps={emailOptionsBefore(taskBefore)}
        onTemplateCreated={onTemplateCreated}
        onTemplateUpdated={onTemplateUpdated}
        onClose={() => setTask(null)}
        onSave={saveTask}
      />
    </div>
  );
}

/** The step before (-1) or after (1) `index` that `match`es, in `list`; null at the end. */
function neighbour(
  list: SequenceStep[],
  index: number,
  by: -1 | 1,
  match: (step: SequenceStep) => boolean,
): number | null {
  for (let i = index + by; i >= 0 && i < list.length; i += by) {
    if (match(list[i]!)) return i;
  }
  return null;
}

type Signal = NonNullable<SequenceSettings['dynamic']>;

/**
 * Sequences QA steps BUG-09: "Edit Engagement Signals", the design's and HubSpot's drawer (was a
 * popover): its text with the warning about enrollments in progress, Email opens / Clicks with an
 * ON / OFF switch and a Count each, and Save / Cancel. Save waits for a change. Saved into the
 * editor's settings; the editor's Save keeps them.
 */
function SignalsDrawer({
  open,
  signal,
  onClose,
  onSave,
}: {
  open: boolean;
  signal: Signal;
  onClose: () => void;
  onSave: (signal: Signal) => void;
}) {
  const [draft, setDraft] = useState<Signal>(signal);
  // Starts from the saved signal each time it opens (not on every render: `signal` may be a
  // new default object each time).
  useEffect(() => {
    if (open) setDraft(signal);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);
  const changed =
    draft.signalOpens !== signal.signalOpens || draft.signalClicks !== signal.signalClicks;
  const id = 'dynSignalsDrawer';
  return (
    <CrmModal id={id} open={open} onClose={onClose} drawer plainBackdrop>
      <ModalHeader id={id} title="Edit Engagement Signals" onClose={onClose} />
      <div className="modal__body dyn-task">
        <section>
          <p className="dyn-group crm-mb-0">Engagement signals</p>
          <p className="crm-fs-8 crm-text-muted crm-mb-0">
            Rep-led outreach will start when a contact meets any of the following criteria. Changing
            engagement signals will impact enrollments currently in progress.
          </p>
        </section>
        {(
          [
            ['signalOpens', 'Email opens', 2],
            ['signalClicks', 'Clicks', 1],
          ] as const
        ).map(([key, label, start]) => {
          const on = draft[key] !== null;
          const other = key === 'signalOpens' ? 'signalClicks' : 'signalOpens';
          // QA 14 Oct #65: each signal can be off, but not both.
          const lastOn = on && draft[other] === null;
          return (
            <div key={key} className="dyn-task__row">
              <div className="field">
                <span className="field__label">{label}</span>
                <span title={lastOn ? 'You must have at least one signal enabled.' : undefined}>
                  <HsSwitch
                    checked={on}
                    disabled={lastOn}
                    onChange={(next) => setDraft({ ...draft, [key]: next ? start : null })}
                  />
                </span>
              </div>
              <div className="field">
                <label className="field__label" htmlFor={`${id}-${key}`}>
                  Count
                </label>
                <input
                  id={`${id}-${key}`}
                  className="input"
                  type="number"
                  min={1}
                  max={20}
                  disabled={!on}
                  value={draft[key] ?? ''}
                  onChange={(e) =>
                    setDraft({
                      ...draft,
                      [key]: Math.max(0, Math.min(20, Math.round(Number(e.target.value)) || 0)),
                    })
                  }
                  // 0 snaps back to 1 when the field is left (HubSpot).
                  onBlur={() => draft[key] === 0 && setDraft({ ...draft, [key]: 1 })}
                />
              </div>
            </div>
          );
        })}
      </div>
      <div className="modal__footer">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          disabled={!changed || draft.signalOpens === 0 || draft.signalClicks === 0}
          onClick={() => onSave(draft)}
        >
          Save
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </CrmModal>
  );
}

export { Icon as StepIcon, PencilIcon, TokenText };
