'use client';

import { useEffect, useRef, useState } from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { NOT_AVAILABLE_YET } from '@/components/crm/ComposerSelect';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  createDocumentShare,
  createDocumentShareForEmail,
  listDocuments,
} from '@/features/documents/api.client';
import type { TrackedDocument } from '@/features/documents/types';
import type { EmailTemplate } from '@/features/inbox/types';
import { listQuotes } from '@/features/quotes/api.client';
import type { Quote } from '@/features/quotes/types';
import { listSequences } from '@/features/sequences/api.client';
import type { Sequence } from '@/features/sequences/types';
import { EnrollPreviewDialog } from '@/features/sequences/ui/EnrollPreviewDialog';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

type MenuKey = 'templates' | 'sequences' | 'documents' | 'quotes' | null;

function Caret() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden className="activity-popup__insert-caret">
      <path d="M7 10l5 5 5-5z" fill="currentColor" />
    </svg>
  );
}

function LockIcon() {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="activity-popup__insert-lock"
    >
      <rect x="5" y="10" width="14" height="11" rx="2" />
      <path d="M8 10V7a4 4 0 0 1 8 0v3" />
    </svg>
  );
}

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function linkHtml(url: string, label: string): string {
  return `<a href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">${escapeHtml(label)}</a>&nbsp;`;
}

/**
 * HubSpot-style insert row above the email editor: templates, sequences, documents, quotes.
 * `showMeetings` draws the design's Meetings menu, locked: booking links can't be shared yet.
 */
export function EmailInsertBar({
  templates,
  templatesLoading,
  onPickTemplate,
  hasTemplate,
  onClearTemplate,
  contactId,
  recipientEmail,
  contactName,
  dealId,
  mailboxId,
  mailboxReady,
  onInsertHtml,
  onToast,
  showMeetings = false,
}: {
  templates: EmailTemplate[] | null;
  templatesLoading?: boolean;
  onPickTemplate: (id: string) => void;
  hasTemplate?: boolean;
  onClearTemplate?: () => void;
  contactId?: string;
  /** #489: the first recipient's address, for a tracked link when no CRM contact is picked. */
  recipientEmail?: string;
  contactName?: string;
  dealId?: string;
  mailboxId?: string | null;
  mailboxReady: boolean;
  onInsertHtml: (html: string) => void;
  onToast: (message: string, tone?: 'danger' | 'info' | 'success') => void;
  showMeetings?: boolean;
}) {
  const me = useCurrentUser();
  const canUseSequences = Boolean(me.permissionSet.rules.app.use_sequences);
  const [open, setOpen] = useState<MenuKey>(null);
  const templatesRef = useRef<HTMLButtonElement>(null);
  const sequencesRef = useRef<HTMLButtonElement>(null);
  const documentsRef = useRef<HTMLButtonElement>(null);
  const quotesRef = useRef<HTMLButtonElement>(null);

  const [sequences, setSequences] = useState<Sequence[] | null>(null);
  const [documents, setDocuments] = useState<TrackedDocument[] | null>(null);
  const [quotes, setQuotes] = useState<Quote[] | null>(null);
  const [enrollSeq, setEnrollSeq] = useState<Sequence | null>(null);
  const [templateQuery, setTemplateQuery] = useState('');

  const sequenceLocked = !contactId || !canUseSequences || !mailboxReady || !mailboxId;
  const sequenceLockTitle = !canUseSequences
    ? 'Your permissions do not allow using sequences'
    : !contactId
      ? 'Sequences need a CRM contact as the recipient'
      : !mailboxReady || !mailboxId
        ? 'Connect Gmail to enroll in a sequence'
        : undefined;

  const loadMenu = (key: MenuKey) => {
    if (key === 'sequences' && sequences === null) {
      listSequences({ status: 'active', limit: 100 }).then(
        (res) => setSequences(res.data),
        (err) => {
          setSequences([]);
          onToast(errorText(err), 'danger');
        },
      );
    }
    if (key === 'documents' && documents === null) {
      listDocuments().then(
        (res) => setDocuments(res.data),
        (err) => {
          setDocuments([]);
          onToast(errorText(err), 'danger');
        },
      );
    }
    if (key === 'quotes' && quotes === null) {
      listQuotes({
        status: 'published',
        ...(dealId ? { dealId } : contactId ? { contactId } : {}),
      }).then(
        (res) => setQuotes(res.data),
        (err) => {
          setQuotes([]);
          onToast(errorText(err), 'danger');
        },
      );
    }
  };

  const toggle = (key: MenuKey) => {
    // Each time it opens, the templates list starts unfiltered.
    if (key === 'templates') setTemplateQuery('');
    setOpen((cur) => (cur === key ? null : key));
  };

  useEffect(() => {
    if (open) loadMenu(open);
    // loadMenu reads latest list state; opening a menu should fetch once.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    setOpen(null);
    setQuotes(null);
    setSequences(null);
  }, [contactId, dealId]);

  const pickDocument = async (doc: TrackedDocument) => {
    setOpen(null);
    if (!contactId && !recipientEmail) {
      onToast('Add a recipient to insert a tracked document', 'danger');
      return;
    }
    try {
      // The contact with the recipient's address (404 when the address is no CRM contact).
      const share = contactId
        ? await createDocumentShare(doc.id, contactId)
        : await createDocumentShareForEmail(doc.id, recipientEmail!);
      onInsertHtml(linkHtml(share.url, doc.name));
    } catch (err) {
      onToast(
        !contactId && isApiError(err) && err.isNotFound
          ? `${recipientEmail} is not a CRM contact yet, so views of the link cannot be tracked. Add them as a contact first.`
          : errorText(err),
        'danger',
      );
    }
  };

  const pickQuote = (quote: Quote) => {
    setOpen(null);
    if (!quote.publicUrl) {
      onToast('This quote is not published yet', 'danger');
      return;
    }
    onInsertHtml(linkHtml(quote.publicUrl, quote.title || quote.numberDisplay));
  };

  return (
    <>
      <div className="activity-popup__insert" role="toolbar" aria-label="Insert">
        <InsertButton
          label="Templates"
          buttonRef={templatesRef}
          expanded={open === 'templates'}
          onClick={() => toggle('templates')}
        />
        <AnchoredPopover
          open={open === 'templates'}
          label="Templates"
          anchorRef={templatesRef}
          onClose={() => setOpen(null)}
          className="activity-popup__insert-menu"
          width={280}
          maxHeight={320}
          preferred="down"
        >
          <TemplatesMenu
            templates={templates}
            loading={templates === null || Boolean(templatesLoading)}
            withClear={Boolean(hasTemplate && onClearTemplate)}
            query={templateQuery}
            onQueryChange={setTemplateQuery}
            onPick={(id) => {
              setOpen(null);
              if (!id) {
                onClearTemplate?.();
                return;
              }
              onPickTemplate(id);
            }}
          />
        </AnchoredPopover>

        <InsertButton
          label="Sequences"
          locked={sequenceLocked}
          lockTitle={sequenceLockTitle}
          buttonRef={sequencesRef}
          expanded={open === 'sequences'}
          onClick={() => {
            if (sequenceLocked) return;
            toggle('sequences');
          }}
        />
        <AnchoredPopover
          open={open === 'sequences' && !sequenceLocked}
          label="Sequences"
          anchorRef={sequencesRef}
          onClose={() => setOpen(null)}
          className="activity-popup__insert-menu"
          width={280}
          maxHeight={320}
          preferred="down"
        >
          <MenuList
            loading={sequences === null}
            empty="No active sequences yet"
            items={(sequences ?? []).map((s) => ({ id: s.id, label: s.name }))}
            onPick={(id) => {
              const seq = sequences?.find((s) => s.id === id) ?? null;
              setOpen(null);
              setEnrollSeq(seq);
            }}
          />
        </AnchoredPopover>

        <InsertButton
          label="Documents"
          buttonRef={documentsRef}
          expanded={open === 'documents'}
          onClick={() => toggle('documents')}
        />
        <AnchoredPopover
          open={open === 'documents'}
          label="Documents"
          anchorRef={documentsRef}
          onClose={() => setOpen(null)}
          className="activity-popup__insert-menu"
          width={280}
          maxHeight={320}
          preferred="down"
        >
          <MenuList
            loading={documents === null}
            empty="No documents yet"
            items={(documents ?? []).map((d) => ({
              id: d.id,
              label: d.folder ? `${d.folder} / ${d.name}` : d.name,
            }))}
            onPick={(id) => {
              const doc = documents?.find((d) => d.id === id);
              if (doc) void pickDocument(doc);
            }}
          />
        </AnchoredPopover>

        {showMeetings ? (
          <InsertButton
            label="Meetings"
            locked
            lockTitle={NOT_AVAILABLE_YET}
            expanded={false}
            onClick={() => {}}
          />
        ) : null}

        <InsertButton
          label="Quotes"
          buttonRef={quotesRef}
          expanded={open === 'quotes'}
          onClick={() => toggle('quotes')}
        />
        <AnchoredPopover
          open={open === 'quotes'}
          label="Quotes"
          anchorRef={quotesRef}
          onClose={() => setOpen(null)}
          className="activity-popup__insert-menu"
          width={280}
          maxHeight={320}
          preferred="down"
        >
          <MenuList
            loading={quotes === null}
            empty="No published quotes yet"
            items={(quotes ?? [])
              .filter((q) => q.publicUrl)
              .map((q) => ({
                id: q.id,
                label: q.numberDisplay ? `${q.numberDisplay} · ${q.title}` : q.title,
              }))}
            onPick={(id) => {
              const quote = quotes?.find((q) => q.id === id);
              if (quote) pickQuote(quote);
            }}
          />
        </AnchoredPopover>
      </div>

      {contactId ? (
        <EnrollPreviewDialog
          open={!!enrollSeq}
          onClose={() => setEnrollSeq(null)}
          sequence={enrollSeq}
          contact={{
            id: contactId,
            name: contactName ?? 'this contact',
            email: recipientEmail ?? null,
          }}
          onEnrolled={() => setEnrollSeq(null)}
        />
      ) : null}
    </>
  );
}

function InsertButton({
  label,
  locked,
  lockTitle,
  expanded,
  onClick,
  buttonRef,
}: {
  label: string;
  locked?: boolean;
  lockTitle?: string;
  expanded: boolean;
  onClick: () => void;
  buttonRef?: React.RefObject<HTMLButtonElement | null>;
}) {
  return (
    <button
      ref={buttonRef}
      type="button"
      className={cn('activity-popup__insert-btn', locked && 'is-locked')}
      aria-expanded={locked ? undefined : expanded}
      title={locked ? lockTitle : undefined}
      disabled={locked}
      onClick={onClick}
    >
      {locked ? <LockIcon /> : null}
      {label}
      {locked ? null : <Caret />}
    </button>
  );
}

/** More templates than this and the picker gets a search box (the snippet menu's `.acx-search`). */
export const TEMPLATE_SEARCH_MIN = 8;

const templateLabel = (t: Pick<EmailTemplate, 'folder' | 'name'>) =>
  t.folder ? `${t.folder} / ${t.name}` : t.name;

/** The picker's rows, "folder / name", those matching `query` by either. */
export function templateMenuItems(
  templates: Pick<EmailTemplate, 'id' | 'folder' | 'name'>[] | null,
  query: string,
  withClear: boolean,
): { id: string; label: string }[] {
  const q = query.trim().toLowerCase();
  return [
    ...(withClear && !q ? [{ id: '', label: 'No template' }] : []),
    ...(templates ?? [])
      .filter((t) => !q || templateLabel(t).toLowerCase().includes(q))
      .map((t) => ({ id: t.id, label: templateLabel(t) })),
  ];
}

/** The Templates menu's content: a search box over a long list, then the templates. */
export function TemplatesMenu({
  templates,
  loading,
  withClear,
  query,
  onQueryChange,
  onPick,
}: {
  templates: Pick<EmailTemplate, 'id' | 'folder' | 'name'>[] | null;
  loading: boolean;
  withClear: boolean;
  query: string;
  onQueryChange: (query: string) => void;
  onPick: (id: string) => void;
}) {
  const searchable = !loading && (templates?.length ?? 0) > TEMPLATE_SEARCH_MIN;
  const q = searchable ? query : '';
  return (
    <>
      {searchable ? (
        <label className="acx-search">
          <input
            type="search"
            placeholder="Search templates"
            autoComplete="off"
            autoFocus
            aria-label="Search templates"
            value={query}
            onChange={(e) => onQueryChange(e.target.value)}
          />
        </label>
      ) : null}
      <MenuList
        loading={loading}
        empty={q.trim() ? 'No matching templates' : 'No templates yet'}
        items={templateMenuItems(templates, q, withClear)}
        onPick={onPick}
      />
    </>
  );
}

export function MenuList({
  loading,
  empty,
  items,
  onPick,
}: {
  loading: boolean;
  empty: string;
  items: { id: string; label: string }[];
  onPick: (id: string) => void;
}) {
  if (loading) return <p className="activity-popup__insert-empty">Loading…</p>;
  if (!items.length) return <p className="activity-popup__insert-empty">{empty}</p>;
  return (
    <div role="listbox">
      {items.map((item) => (
        <button
          key={item.id}
          type="button"
          role="option"
          aria-selected={false}
          onClick={() => onPick(item.id)}
        >
          {item.label}
        </button>
      ))}
    </div>
  );
}
