'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState, type KeyboardEvent, type ReactNode } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { Alert } from '@/components/crm/Alert';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText } from '@/lib/api/errors';
import { listSequenceTemplates } from '../api.client';
import type { SequenceStep, SequenceTemplate } from '../types';
import { cn } from '@/lib/utils/cn';
import { StepIcon } from './DynamicSequenceCanvas';
import { SequenceStartPicker, type FirstStepKind } from './SequenceStartPicker';

type Kind = 'dynamic' | 'scratch' | 'template';

/** The pre-made sequences' keys (HUB-239), so ?template= can preselect one. */
const TEMPLATE_PARAM = 'template';

/** HubSpot's dynamic explainer (IDX-04), word for word. */
const BENEFITS = [
  [
    'Automated emails for efficiency:',
    'Let automated emails handle your outreach so your team can focus on the contacts who matter.',
  ],
  [
    'Rep-led tasks when contacts engage:',
    'Switch to manual tasks when a contact engages, so no interested lead slips through.',
  ],
  [
    'More replies and meetings:',
    'Catch engaged contacts at the right moment and turn their interest into opportunities.',
  ],
] as const;

/** The example lanes of the dynamic explainer (the last row fades out). */
const EXAMPLE_REP = [
  'call_task',
  'manual_email',
  'todo',
  'linkedin_connect',
  'linkedin_message',
] as const;
const REP_LABEL: Record<(typeof EXAMPLE_REP)[number], string> = {
  call_task: 'Call Task',
  manual_email: 'Manual Email Task',
  todo: 'General Task',
  linkedin_connect: 'LinkedIn Connect Task',
  linkedin_message: 'LinkedIn InMail Task',
};

function SparkIcon() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" aria-hidden>
      <path
        d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"
        strokeWidth="1.8"
        strokeLinecap="round"
      />
    </svg>
  );
}

function PencilIcon() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" aria-hidden>
      <path d="M15.5 4.5l4 4L8 20H4v-4L15.5 4.5z" strokeWidth="1.8" strokeLinejoin="round" />
    </svg>
  );
}

/**
 * Sequences QA manage BUG-07: a radiogroup's arrow keys (design sequence-create.js, the ARIA radio
 * pattern): Down/Right and Up/Left move to the next / previous option of the same group, wrapping,
 * and pick it. With the roving tabIndex, each group is one tab stop.
 */
function onRadioKeys(e: KeyboardEvent<HTMLElement>) {
  const step =
    e.key === 'ArrowDown' || e.key === 'ArrowRight'
      ? 1
      : e.key === 'ArrowUp' || e.key === 'ArrowLeft'
        ? -1
        : 0;
  if (!step) return;
  const group = e.currentTarget;
  const radios = [...group.querySelectorAll<HTMLElement>('[role="radio"]')].filter(
    (radio) => radio.closest('[role="radiogroup"]') === group,
  );
  const at = radios.indexOf(e.target as HTMLElement);
  if (at < 0) return;
  e.preventDefault();
  const next = radios[(at + step + radios.length) % radios.length]!;
  next.focus();
  next.click();
}

/**
 * Create a sequence (design sequence-create.php:"New Dynamic Sequence" / "New Sequence"): pick
 * dynamic, from scratch or one of HubSpot's pre-made sequences on the left (HUB-239), see it on
 * the right, then Create sequence. Dynamic and scratch open the builder, where nothing is saved
 * until Save (QA 16 Oct #106); a pre-made one opens it too, with its steps (IDX-07). The preview is
 * read-only, as in HubSpot (#80): its step cards are not buttons.
 */
export function SequenceCreateView() {
  const me = useCurrentUser();
  const canUse = Boolean(me.permissionSet.rules.app.use_sequences);
  const router = useRouter();
  const searchParams = useSearchParams();
  const [kind, setKind] = useState<Kind>(
    searchParams.get(TEMPLATE_PARAM)
      ? 'template'
      : searchParams.get('type') === 'dynamic'
        ? 'dynamic'
        : 'scratch',
  );
  // HUB-239: the pre-made sequences, listed under the two options (design).
  const [templates, setTemplates] = useState<SequenceTemplate[] | null>(null);
  const [templateError, setTemplateError] = useState<string | null>(null);
  const [picked, setPicked] = useState<string | null>(searchParams.get(TEMPLATE_PARAM));
  useEffect(() => {
    listSequenceTemplates().then(setTemplates, (err: unknown) => setTemplateError(errorText(err)));
  }, []);
  const template = kind === 'template' ? templates?.find((t) => t.key === picked) : undefined;
  const pickTemplate = (key: string) => {
    setKind('template');
    setPicked(key);
  };
  const folder = searchParams.get('folder')?.trim() || null;

  const create = (start?: FirstStepKind) => {
    const params = new URLSearchParams({ type: kind });
    if (folder) params.set('folder', folder);
    if (start) params.set('start', start);
    // A pre-made sequence opens the editor with its steps, unsaved until Save (IDX-07).
    if (kind === 'template' && template) params.set(TEMPLATE_PARAM, template.key);
    router.push(`/sequences/new/edit?${params.toString()}`);
  };

  if (!canUse) {
    return (
      <div className="companies-page">
        <Alert tone="warning">Your permissions do not allow using sequences.</Alert>
      </div>
    );
  }

  return (
    <div className="seqc">
      <header className="seq-ed-head__bar seqc__bar">
        <Link className="seq-ed-head__back" href="/sequences">
          <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden>
            <path d="M10 3 5 8l5 5" fill="none" stroke="currentColor" strokeWidth="1.8" />
          </svg>
          Back to Sequences
        </Link>
        <div className="seq-ed-head__title">
          <h1 className="seq-ed-head__name">
            {kind === 'dynamic'
              ? 'New Dynamic Sequence'
              : kind === 'template' && template
                ? template.name
                : 'New Sequence'}
          </h1>
        </div>
        <div className="seq-ed-head__right">
          <button
            type="button"
            className="seq-ed-head__save"
            disabled={kind === 'template' && !template}
            onClick={() => create()}
          >
            Create sequence
          </button>
        </div>
      </header>

      <div className="seqc__body">
        <aside
          className="seqc__options"
          role="radiogroup"
          aria-label="Sequence type"
          onKeyDown={onRadioKeys}
        >
          <button
            type="button"
            role="radio"
            aria-checked={kind === 'scratch'}
            tabIndex={kind === 'scratch' ? 0 : -1}
            className={cn('seqc-option', kind === 'scratch' && 'is-active')}
            onClick={() => setKind('scratch')}
          >
            <span className="seqc-option__icon seqc-option__icon--scratch">
              <PencilIcon />
            </span>
            <span>
              <strong>Start from scratch</strong>
              <small>Start with a blank sequence and add your own emails and tasks.</small>
            </span>
          </button>
          <button
            type="button"
            role="radio"
            aria-checked={kind === 'dynamic'}
            tabIndex={kind === 'scratch' ? -1 : 0}
            className={cn('seqc-option', kind === 'dynamic' && 'is-active')}
            onClick={() => setKind('dynamic')}
          >
            <span className="seqc-option__icon seqc-option__icon--dynamic">
              <SparkIcon />
            </span>
            <span>
              <strong>Create a dynamic sequence</strong>
              <small>Automated emails, then manual tasks when contacts engage.</small>
            </span>
          </button>
          <h2 className="seqc__premade-h" id="seqcPremadeH">
            Start with a pre-made sequence
          </h2>
          <div
            className="seqc__premade"
            role="radiogroup"
            aria-labelledby="seqcPremadeH"
            onKeyDown={onRadioKeys}
          >
            {templateError ? <Alert tone="danger">{templateError}</Alert> : null}
            {templates === null && !templateError ? (
              <p className="seqc__lead crm-mb-0">Loading pre-made sequences…</p>
            ) : null}
            {(templates ?? []).map((t, i) => {
              const on = kind === 'template' && picked === t.key;
              // The picked one is the group's tab stop; none picked, the first.
              const stop = template ? on : i === 0;
              return (
                <button
                  key={t.key}
                  type="button"
                  role="radio"
                  aria-checked={on}
                  tabIndex={stop ? 0 : -1}
                  className={cn('seqc-option seqc-option--premade', on && 'is-active')}
                  onClick={() => pickTemplate(t.key)}
                >
                  <span>
                    <strong>{t.name}</strong>
                    <small>{t.description}</small>
                  </span>
                </button>
              );
            })}
          </div>
        </aside>

        <main className="seqc__main">
          {kind === 'template' ? (
            <>
              <h2 className="seqc__title">{template ? template.name : 'Preview'}</h2>
              {template ? <p className="seqc__lead">{template.description}</p> : null}
              {template ? (
                <TemplatePreview t={template} />
              ) : (
                <p className="seqc__lead">Pick a pre-made sequence on the left to see its steps.</p>
              )}
            </>
          ) : kind === 'dynamic' ? (
            <>
              <h2 className="seqc__title">Create a dynamic sequence</h2>
              <DynamicExplainer />
            </>
          ) : (
            <>
              <h2 className="seqc__title">Preview</h2>
              {/* #80: read-only, as HubSpot's preview: the first step is picked in the builder. */}
              <SequenceStartPicker />
            </>
          )}
        </main>
      </div>
    </div>
  );
}

/** HubSpot's dynamic sequence explainer (IDX-04): the create page and "About dynamic sequences". */
export function DynamicExplainer() {
  return (
    <>
      <p className="seqc__lead">
        Let automated emails handle your outreach, then hand off to your team when a contact
        engages. You&apos;ll save time on sends and catch interested leads at the right moment.
      </p>
      <ul className="seqc__benefits">
        {BENEFITS.map(([title, text]) => (
          <li key={title}>
            <span className="seqc__arrow" aria-hidden>
              →
            </span>
            <span>
              <strong>{title}</strong> {text}
            </span>
          </li>
        ))}
      </ul>

      <div className="seqc-diagram" aria-hidden>
        <div className="seqc-diagram__head seqc-diagram__head--auto">
          Leads will receive automated emails until they engage
        </div>
        <span className="seqc-diagram__link">
          <span>Engagement signals</span>
        </span>
        <div className="seqc-diagram__head seqc-diagram__head--rep">
          As soon as a lead engages, the sequence will start to queue up manual tasks
        </div>
        {EXAMPLE_REP.map((rep, i) => (
          <div
            key={i}
            className={cn('seqc-diagram__row', i === EXAMPLE_REP.length - 1 && 'is-faded')}
          >
            <div className="seqc-diagram__card">
              <StepIcon kind="send" />
              Automated Email
            </div>
            <span
              className={cn(
                'seqc-diagram__branch',
                i === 0 && 'is-first',
                i === EXAMPLE_REP.length - 1 && 'is-last',
              )}
            />
            <div className="seqc-diagram__card">
              <StepIcon kind={rep} />
              {REP_LABEL[rep]}
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

/** HubSpot's step names in the pre-made preview (IDX-05). */
const STEP_LABEL: Record<Exclude<SequenceStep['type'], 'wait'>, string> = {
  automated_email: 'Automated Email',
  manual_email: 'Manual Email Task',
  call_task: 'Call Task',
  task: 'General Task',
};

/** HubSpot's names of the merge fields the pre-made sequences use, as its preview shows them. */
const TOKEN_LABEL: Record<string, string> = {
  'contact.firstName': 'Contact: First Name',
  'company.name': 'Company: Company name',
  'company.industry': 'Company: Industry',
};

/** An email's text, without its markup; merge fields stay as `{{path}}` for `WithChips`. */
const textOf = (html: string | null) =>
  (html ?? '')
    .replace(/<\/(p|li|div)>/gi, '\n')
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<li>/gi, '• ')
    .replace(/<[^>]*>/g, '')
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/\n{2,}/g, '\n')
    .trim();

/**
 * A pre-made sequence's text as HubSpot's preview shows it: merge fields as chips ("Contact: First
 * Name") and [placeholders] as chips reading "Placeholder: X CONTENT" (Sequences QA manage
 * BUG-01), so the rep sees what to replace.
 */
function WithChips({ text }: { text: string }) {
  return (
    <>
      {text.split(/(\{\{\s*[\w.]+\s*(?:\|[^}]*)?\}\}|\[[^[\]<>]+\])/g).map((part, i) => {
        if (i % 2 === 0) return part;
        if (part.startsWith('[')) {
          return (
            <span key={i} className="mt-token seq-token">
              Placeholder: {part.slice(1, -1).trim()}
            </span>
          );
        }
        const path = /\{\{\s*([\w.]+)/.exec(part)?.[1] ?? part;
        return (
          <span key={i} className="mt-token seq-token">
            {TOKEN_LABEL[path] ?? path}
          </span>
        );
      })}
    </>
  );
}

/** A step of the pre-made preview: a card that folds (open at first), as in HubSpot. */
function TemplateStep({
  n,
  title,
  badge,
  children,
}: {
  n: number;
  title: string;
  badge: boolean;
  children: ReactNode;
}) {
  const [open, setOpen] = useState(true);
  return (
    <section className="seqc-tpl__step" aria-label={`Step ${n}`}>
      <button
        type="button"
        className="seqc-tpl__toggle"
        aria-expanded={open}
        onClick={() => setOpen((on) => !on)}
      >
        <CrmIcon name="chevron-down" className="iconSize-14 seqc-tpl__chev" />
        <h3>
          {title}
          {badge ? <span className="seqc-tpl__badge">Pauses sequence</span> : null}
        </h3>
      </button>
      {open ? children : null}
    </section>
  );
}

/** An email's body, three lines and "See more", as in HubSpot. */
function ClampedBody({ text }: { text: string }) {
  const [more, setMore] = useState(false);
  return (
    <>
      <p className={cn('seqc-tpl__body', !more && 'is-clamped')}>
        <WithChips text={text} />
      </p>
      <button type="button" className="seqc-tpl__more" onClick={() => setMore((on) => !on)}>
        {more ? 'See less' : 'See more'}
      </button>
    </>
  );
}

/**
 * HUB-239: a pre-made sequence's steps as HubSpot's create page shows them: its name and
 * description, the summary, then each step (a card that folds) with its day, "Pauses sequence",
 * the task title, the email's version, subject and body, and the delay before the next one
 * ("Delay: None" with no wait between two). Nothing in it is a control that changes the sequence
 * (#80).
 */
function TemplatePreview({ t }: { t: SequenceTemplate }) {
  const actions = t.steps.filter((step) => step.type !== 'wait');
  const automated = actions.filter((step) => step.type === 'automated_email').length;
  let day = 1;
  let n = 0;
  let emails = 0;
  /** A reply keeps the subject of the email it replies to (HubSpot shows it with "Reply"). */
  let subject = '';
  const cards: ReactNode[] = [];
  t.steps.forEach((step, i) => {
    if (step.type === 'wait') {
      day += step.amount;
      cards.push(
        <div key={i} className="seqc-tpl__delay">
          Delay: {step.amount} {step.unit === 'business_days' ? 'business ' : ''}day
          {step.amount === 1 ? '' : 's'}
        </div>,
      );
      return;
    }
    // Two steps with no wait between them.
    if (n > 0 && t.steps[i - 1]?.type !== 'wait') {
      cards.push(
        <div key={`gap${i}`} className="seqc-tpl__delay">
          Delay: None
        </div>,
      );
    }
    n += 1;
    const email = step.type === 'automated_email' || step.type === 'manual_email';
    const title = 'title' in step ? step.title : null;
    if (email) emails += 1;
    if (email && !step.threadAsReply) subject = step.subject ?? '';
    cards.push(
      <TemplateStep
        key={i}
        n={n}
        title={`${n}. ${STEP_LABEL[step.type]} - Day ${day}`}
        badge={'pauseUntilDone' in step && Boolean(step.pauseUntilDone)}
      >
        {title ? <p className="seqc-tpl__line">Task title: {title}</p> : null}
        {email ? (
          <div className="seqc-tpl__email">
            <p className="seqc-tpl__line">
              <strong>Version A</strong> {t.name} (Email #{emails})
              {step.threadAsReply ? <span className="seqc-tpl__badge">Reply</span> : null}
            </p>
            <p className="seqc-tpl__line">
              <strong>Subject:</strong> <WithChips text={subject} />
            </p>
            <ClampedBody text={textOf(step.bodyHtml)} />
          </div>
        ) : null}
      </TemplateStep>,
    );
  });
  return (
    <div className="seqc-preview" aria-label={`${t.name} steps`}>
      <section className="dyn-stats" aria-label="Sequence summary">
        <div>
          <span>Total steps</span>
          <strong>{t.stepCount}</strong>
        </div>
        <div>
          <span>Days to complete</span>
          <strong>{t.days}</strong>
        </div>
        <div>
          <span>Automated steps</span>
          <strong>{actions.length ? Math.round((automated / actions.length) * 100) : 0}%</strong>
        </div>
        <div>
          <span>Unenroll criteria</span>
          <strong>2</strong>
        </div>
      </section>
      <div className="seqc-tpl">{cards}</div>
      <div className="seqc-step__done">
        <span className="seqc-step__line seqc-step__line--arrow" aria-hidden />
        <span className="dyn-done" aria-hidden>
          ✓
        </span>
        Completed
      </div>
    </div>
  );
}
