import { ControlButton } from '@/components/builder/common/ComponentControls';
import Wrapper from '@/components/common/Wrapper';
import { TextProps } from '@/types/common';
import TextColor from '@tiptap/extension-color';
import Highlight from '@tiptap/extension-highlight';
import Link from '@tiptap/extension-link';
import TextStyle from '@tiptap/extension-text-style';
import Underline from '@tiptap/extension-underline';
import { EditorContent, useEditor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import { usePathname } from 'next/navigation';
import React, { useState } from 'react';
import { ChromePicker, ColorResult } from 'react-color';
import { FaBold, FaHighlighter, FaItalic, FaLink, FaPalette, FaUnderline } from 'react-icons/fa';

export const Text = React.forwardRef<HTMLDivElement, TextProps>(
  ({ json, id, styling, onPropChange, isInSection, sectionId }, ref) => {
    const [isHighlightColorPickerOpen, setIsHighlightColorPickerOpen] = useState(false);
    const [highlightColor, setHighlightColor] = useState('#FFFF00');
    const [isTextColorPickerOpen, setIsTextColorPickerOpen] = useState(false);
    const [textColor, setTextColor] = useState('#000000');
    const pathname = usePathname();
    const isBuilder = pathname.includes('/portfolios/') && !pathname.includes('/preview');

    const editor = useEditor({
      extensions: [StarterKit, Underline, Link, Highlight, TextColor, TextStyle],
      content: json,
      editable: isBuilder,
      immediatelyRender: false,
      onUpdate: ({ editor }) => {
        const updatedJson = editor.getJSON();
        onPropChange?.('json', updatedJson);
      },
    });

    const handleLinkClick = () => {
      const previousUrl = editor?.getAttributes('link').href;
      const url = window.prompt('URL', previousUrl);

      if (url === null) {
        return;
      }

      if (url === '') {
        editor?.chain().focus().extendMarkRange('link').unsetLink().run();
      } else {
        editor?.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
      }
    };

    const handleHighlightClick = () => {
      setIsHighlightColorPickerOpen(!isHighlightColorPickerOpen);
    };

    const handleHighlightColorChange = (color: ColorResult) => {
      setHighlightColor(color.hex);
      editor?.chain().focus().setHighlight({ color: color.hex }).run();
    };

    const handleTextColorClick = () => {
      setIsTextColorPickerOpen(!isTextColorPickerOpen);
    };

    const handleTextColorChange = (color: ColorResult) => {
      setTextColor(color.hex);
      editor?.chain().focus().setColor(color.hex).run();
    };

    return (
      <Wrapper styling={styling} id={sectionId}>
        <div
          className={`absolute right-0 ${isInSection ? '-top-[2px] left-0 w-fit' : '-top-8'} flex gap-1 opacity-0 group-hover/item:opacity-100 transition-opacity z-[350]`}
        >
          {editor && (
            <div className='relative grid grid-cols-6 gap-1'>
              <ControlButton
                icon={FaBold}
                onClick={() => editor.chain().focus().toggleBold().run()}
                title='Bold'
                iconSize={isInSection ? 12 : 20}
              />
              <ControlButton
                icon={FaItalic}
                onClick={() => editor.chain().focus().toggleItalic().run()}
                title='Italic'
                iconSize={isInSection ? 12 : 20}
              />
              <ControlButton
                icon={FaUnderline}
                onClick={() => editor.chain().focus().toggleUnderline().run()}
                title='Underline'
                iconSize={isInSection ? 12 : 20}
              />
              <ControlButton icon={FaLink} onClick={handleLinkClick} title='Link' iconSize={isInSection ? 12 : 20} />

              <ControlButton
                icon={FaHighlighter}
                onClick={handleHighlightClick}
                title='Highlight'
                iconSize={isInSection ? 12 : 20}
              />
              {isHighlightColorPickerOpen && (
                <div className='absolute right-0 top-full mt-2'>
                  <ChromePicker color={highlightColor} onChange={handleHighlightColorChange} />
                </div>
              )}

              <ControlButton
                icon={FaPalette}
                onClick={handleTextColorClick}
                title='Text Color'
                iconSize={isInSection ? 12 : 20}
              />
              {isTextColorPickerOpen && (
                <div className='absolute right-0 top-full mt-2'>
                  <ChromePicker color={textColor} onChange={handleTextColorChange} />
                </div>
              )}
            </div>
          )}
        </div>
        <EditorContent
          ref={ref}
          editor={editor}
          id={id}
          className='builder'
          style={{ textAlign: styling?.align ?? 'left', color: styling?.color ?? 'var(--color-text)' }}
        />
      </Wrapper>
    );
  }
);

Text.displayName = 'Text';
