import { Editor } from '@tiptap/core';
import Bold from '@tiptap/extension-bold';
import BulletList from '@tiptap/extension-bullet-list';
import Document from '@tiptap/extension-document';
import Heading from '@tiptap/extension-heading';
import Italic from '@tiptap/extension-italic';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import HardBreak from '@tiptap/extension-hard-break';
import ListItem from '@tiptap/extension-list-item';
import OrderedList from '@tiptap/extension-ordered-list';
import Underline from '@tiptap/extension-underline';
import TextAlign from '@tiptap/extension-text-align';
import { TextStyleKit } from '@tiptap/extension-text-style';
import Placeholder from '@tiptap/extension-placeholder';
import { LowerAlphaList } from './LowerAlphaList.js';
import { RomanList } from './RomanList.js';
import { UpperAlphaList } from './UpperAlphaList.js';

function setFontSize(editor, sizePx) {
  if (!editor) return;
  if (!sizePx) {
    editor.chain().focus().unsetMark('textStyle').run();
    return;
  }
  editor.chain().focus().setMark('textStyle', { fontSize: sizePx }).run();
}

// Función para aplicar / quitar color de fondo
function toggleHighlight(editor, color) {
  if (!editor) return;
  const currentColor = editor.getAttributes('textStyle').backgroundColor;
  if (currentColor === color) {
    editor.chain().focus().setMark('textStyle', { backgroundColor: null }).run();
  } else {
    editor.chain().focus().setMark('textStyle', { backgroundColor: color }).run();
  }
}

export function initTiptap({ elementId, inputId, placeholder, content, prefix }) {
  const el = document.getElementById(elementId);
  const input = document.getElementById(inputId);
  if (!el) return null;

  const editor = new Editor({
    element: el,
    content: content || (input ? input.value : ''),
    extensions: [
      UpperAlphaList,
      LowerAlphaList,
      RomanList,
      Document,
      Paragraph,
      Text,
      HardBreak,
      Heading.configure({ levels: [1, 2, 3, 4] }),
      Bold,
      Italic,
      Underline,
      ListItem,
      BulletList,
      OrderedList,
      TextStyleKit,
      TextAlign.configure({ types: ['heading', 'paragraph'] }),
      Placeholder.configure({ placeholder }),
    ],
    onUpdate: ({ editor }) => { if (input) input.value = editor.getHTML(); updateToolbarState(editor) },
    onSelectionUpdate: ({ editor }) => updateToolbarState(editor),
    onCreate: ({ editor }) => updateToolbarState(editor),
  });

  let elementVariable = document.getElementById("select-variable");
  if (elementVariable) {
    let selectVariable = elementVariable.querySelector("select");
    selectVariable.addEventListener('change', (e) => {
      const value = e.target.value;
      if (value) {
        editor.chain().focus().insertContent(value).run();
        selectVariable.selectedIndex = 0;
      }
    });
  }

  function qs(suf) { return document.getElementById(`${prefix}-${suf}`) }

  const btnBold = qs('btn-bold');
  const btnItalic = qs('btn-italic');
  const btnUnderline = qs('btn-underline');
  const alignLeft = qs('align-left');
  const alignCenter = qs('align-center');
  const alignRight = qs('align-right');
  const alignJustify = qs('align-justify');
  const blockType = qs('block-type');
  const fontSize = qs('font-size');

  // Botones de resaltado
  const highlightYellow = qs('highlight-yellow');
  const highlightGreen = qs('highlight-green');
  const highlightPink = qs('highlight-pink');
  const highlightRed = qs('highlight-red');
  const highlightBlue = qs('highlight-blue');

  const listDropdown = qs('list-dropdown');

  if (listDropdown) {
    listDropdown.addEventListener('change', (e) => {
      const type = e.target.value;

      if (!type) return;

      if (type === 'bulletList') {
        editor.chain().focus().toggleBulletList().run();
      }
      else if (type === 'orderedList') {
        editor.chain().focus().toggleOrderedList().run();
      }
      else if (type === 'roman') {
        editor.chain().focus().toggleRomanList().run();
      }
      else if (type === 'alphaLowerParens') {
        editor.chain().focus().toggleLowerAlphaList().run();
      }
      else if (type === 'alphaUpperDot') {
        editor.chain().focus().toggleUpperAlphaList().run();
      }

      listDropdown.value = ''; // reset
    });
  }

  if (btnBold) btnBold.addEventListener('click', () => editor.chain().focus().toggleBold().run());
  if (btnItalic) btnItalic.addEventListener('click', () => editor.chain().focus().toggleItalic().run());
  if (btnUnderline) btnUnderline.addEventListener('click', () => editor.chain().focus().toggleUnderline().run());
  if (alignLeft) alignLeft.addEventListener('click', () => editor.chain().focus().setTextAlign('left').run());
  if (alignCenter) alignCenter.addEventListener('click', () => editor.chain().focus().setTextAlign('center').run());
  if (alignRight) alignRight.addEventListener('click', () => editor.chain().focus().setTextAlign('right').run());
  if (alignJustify) alignJustify.addEventListener('click', () => editor.chain().focus().setTextAlign('justify').run());

  // Eventos para los botones de colores
  if (highlightYellow) highlightYellow.addEventListener('click', () => toggleHighlight(editor, '#f6eb14'));
  if (highlightGreen) highlightGreen.addEventListener('click', () => toggleHighlight(editor, '#4ade80'));
  if (highlightPink) highlightPink.addEventListener('click', () => toggleHighlight(editor, '#f472b6'));
  if (highlightRed) highlightRed.addEventListener('click', () => toggleHighlight(editor, '#fb7185'));
  if (highlightBlue) highlightBlue.addEventListener('click', () => toggleHighlight(editor, '#60a5fa'));

  if (blockType) blockType.addEventListener('change', (e) => {
    const v = e.target.value;
    const chain = editor.chain().focus();
    if (v === 'p') chain.setParagraph().run();
    else chain.toggleHeading({ level: parseInt(v.replace('h', '')) }).run();
  });

  if (fontSize) fontSize.addEventListener('change', (e) => {
    const val = e.target.value;
    if (!val) setFontSize(editor, null);
    else setFontSize(editor, `${val}px`);
  });

  // **Hacer clic en cualquier parte del editor enfoque el cursor**
  el.addEventListener('click', () => editor.chain().focus().run());

  function updateToolbarState(ed) {
    toggleActive(btnBold, ed.isActive('bold'));
    toggleActive(btnItalic, ed.isActive('italic'));
    toggleActive(btnUnderline, ed.isActive('underline'));

    toggleActive(alignLeft, ed.isActive({ textAlign: 'left' }));
    toggleActive(alignCenter, ed.isActive({ textAlign: 'center' }));
    toggleActive(alignRight, ed.isActive({ textAlign: 'right' }));
    toggleActive(alignJustify, ed.isActive({ textAlign: 'justify' }));

    if (blockType) {
      let current = 'p';
      if (ed.isActive('heading', { level: 1 })) current = 'h1';
      else if (ed.isActive('heading', { level: 2 })) current = 'h2';
      else if (ed.isActive('heading', { level: 3 })) current = 'h3';
      else if (ed.isActive('heading', { level: 4 })) current = 'h4';
      blockType.value = current;
    }
  }

  function toggleActive(el, isActive) {
    if (!el) return;
    el.classList.toggle('is-active', !!isActive);
  }

  return editor;
}