'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import type { EmailTemplate } from '@/features/inbox/types';
import { listTeamOptions, type TeamOption } from '@/features/members/api.client';
import {
  getTemplate,
  listTemplateFolders,
  type MessageTemplate,
  type TemplateFolder,
} from '@/features/message-templates/api.client';
import type { ShareOptions } from '@/features/message-templates/ui/ShareDrawer';
import { MTT_SPRITE } from '@/features/message-templates/ui/sprite';
import { TemplateEditorModal } from '@/features/message-templates/ui/TemplateEditorModal';
import { useOwners } from '@/features/owners/useOwners';
import { MtScopeContext } from '@/features/snippets/ui/mt';
import { errorText } from '@/lib/api/errors';
import { hydratePlaceholders, usePlaceholders } from '@/features/sequences/placeholders';

/** The sequences builder's template shape, from the template the editor saved. */
export function asEmailTemplate(t: MessageTemplate): EmailTemplate {
  return {
    id: t.id,
    name: t.name,
    subject: t.subject,
    bodyHtml: t.bodyHtml,
    folder: t.folder,
    visibility: t.visibility === 'personal' ? 'personal' : 'shared',
    canEdit: t.canEdit,
    ownerId: t.ownerId,
    createdAt: t.createdAt,
    updatedAt: t.updatedAt,
  };
}

/**
 * Sequences #59 / HUB-271 (DES-6 sequence-step-editor.php): a step's email in the app's template
 * editor (Templates' TemplateEditorModal): token chips, the full toolbar (font, size, colour,
 * quote, align, link, image), the signature line, "Preview example email" (Select a contact,
 * Generate, Hide / Show preview) and Save as new template / Update existing template. Generate
 * with AI stays as the editor has it (disabled, "Coming soon": the AI phase is later).
 *
 * `templateId`: the template to edit; null: a new template, started from `draft` (the step's own
 * subject and body, if it has them).
 */
export function SequenceTemplateEditor({
  templateId,
  draft = null,
  onClose,
  onSaved,
}: {
  templateId: string | null;
  draft?: { name: string; subject: string; bodyHtml: string } | null;
  onClose: () => void;
  onSaved: (template: EmailTemplate, created: boolean) => void;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const { owners } = useOwners(true);
  const [template, setTemplate] = useState<MessageTemplate | null | undefined>(
    templateId ? undefined : null,
  );
  const [folders, setFolders] = useState<TemplateFolder[]>([]);
  const [teams, setTeams] = useState<TeamOption[]>([]);

  useEffect(() => {
    let alive = true;
    if (templateId) {
      getTemplate(templateId).then(
        (t) => alive && setTemplate(t),
        (err: unknown) => {
          if (!alive) return;
          toast(errorText(err), 'danger');
          onClose();
        },
      );
    }
    listTemplateFolders().then(
      (res) => alive && setFolders(res.data),
      () => {
        // No folders: "No folder" only.
      },
    );
    listTeamOptions().then(
      (res) => alive && setTeams(res.data),
      () => {
        // No teams: sharing lists users only.
      },
    );
    return () => {
      alive = false;
    };
    // Loaded once per open.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [templateId]);

  const shareOptions: ShareOptions = useMemo(
    () => ({
      users: owners
        .filter((o) => o.active && o.userId)
        .map((o) => ({ id: o.userId, name: o.name })),
      teams: teams.map((t) => ({ id: t.id, name: t.name })),
    }),
    [owners, teams],
  );
  const ownerName = (id: string) =>
    owners.find((o) => o.userId === id)?.name ??
    (id === me.user.id ? me.user.name : 'Unknown user');

  // Sequences QA steps BUG-11: pre-made placeholders show as chips here too, as in RichBody.
  const placeholders = usePlaceholders();
  const hydrateBody = useCallback(
    (root: HTMLElement) => hydratePlaceholders(root, placeholders),
    [placeholders],
  );

  // The editor fills its body once, when it opens: not before the template is here.
  if (template === undefined) return null;
  return (
    <MtScopeContext.Provider value="mtt-page">
      <svg
        width="0"
        height="0"
        style={{ position: 'absolute' }}
        aria-hidden="true"
        focusable="false"
        dangerouslySetInnerHTML={{ __html: `<defs>${MTT_SPRITE}</defs>` }}
      />
      <TemplateEditorModal
        template={template}
        draft={template ? null : draft}
        hydrateBody={hydrateBody}
        folders={folders}
        shareOptions={shareOptions}
        me={me.user}
        ownerName={ownerName}
        // The API keeps the account's template limit (an error toast at the limit).
        atLimit={() => false}
        onClose={onClose}
        onSaved={(saved, created) => {
          // DES-6 toasts.
          toast(created ? `Template "${saved.name}" saved` : 'Template updated', 'success');
          onSaved(asEmailTemplate(saved), created);
        }}
      />
    </MtScopeContext.Provider>
  );
}
