'use client'

import { useEditor, EditorContent, ResizableNodeView } from '@tiptap/react'
import { FloatingMenu, BubbleMenu } from '@tiptap/react/menus'
import StarterKit from '@tiptap/starter-kit'
import { useEffect, useRef, useState } from 'react'
import Post from '../Post/Post'
import { PostData } from '@/types/entities'
import TiptapToolbar from './TiptapToolbar'
import Text from '@tiptap/extension-text'
import Image from '@tiptap/extension-image'
import Paragraph from '@tiptap/extension-paragraph'
import { TaskItem, TaskList } from '@tiptap/extension-list'
import { Highlight } from '@tiptap/extension-highlight'
import FileHandler from '@tiptap/extension-file-handler'
import Underline from '@tiptap/extension-underline'
import Link from '@tiptap/extension-link'
import TextAlign from '@tiptap/extension-text-align'
import { Table, TableRow, TableCell, TableHeader } from '@tiptap/extension-table';
import Typography from '@tiptap/extension-typography';
import { Group, Panel, usePanelRef } from 'react-resizable-panels'
import { createPortal } from 'react-dom'
import PostSettings from '../Post/PostSettings'
import { Dropcursor } from '@tiptap/extensions'
import TiptapBubbleMenu from './TiptapBubbleMenu'
import TiptapFloatingMenu from './TiptapFloatingMenu'

const Tiptap = ({
    slug,
    data
}: {
    slug: string
    data: PostData
}) => {
    const [content, setContent] = useState(data.post_content)

    const [showPreview, setShowPreview] = useState(true)

    const previewModal = useRef<HTMLDialogElement>(null)

    const editor = useEditor({
        editorProps: {
            attributes: {
                class: 'prose lg:prose-xl p-4 focus:outline-none max-w-none',// focus:outline-none',
            },
        },
        extensions: [
            StarterKit.configure({
                codeBlock: false
            }),
            Link.configure({
                openOnClick: false
            }),
            Image.configure({
                resize: {
                    enabled: true,
                    alwaysPreserveAspectRatio: true,
                },
                inline: false,
            }),
            TextAlign.configure({
                types: ['heading', 'paragraph'],
            }),
            TaskList,
            TaskItem.configure({
                nested: true
            }),
            Table.configure({
                resizable: true
            }),
            FileHandler.configure({
                allowedMimeTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
                onDrop: (currentEditor, files, pos) => {
                    files.forEach(file => {
                        const fileReader = new FileReader()

                        fileReader.readAsDataURL(file)
                        fileReader.onload = () => {
                            currentEditor
                                .chain()
                                .insertContentAt(pos, {
                                    type: 'image',
                                    attrs: {
                                        src: fileReader.result,
                                    },
                                })
                                .focus()
                                .run()
                        }
                    })
                },
                onPaste: (currentEditor, files, htmlContent) => {
                    files.forEach(file => {
                        if (htmlContent) {
                            // if there is htmlContent, stop manual insertion & let other extensions handle insertion via inputRule
                            // you could extract the pasted file from this url string and upload it to a server for example
                            console.log(htmlContent) // eslint-disable-line no-console
                            return false
                        }

                        const fileReader = new FileReader()

                        fileReader.readAsDataURL(file)
                        fileReader.onload = () => {
                            currentEditor
                                .chain()
                                .insertContentAt(currentEditor.state.selection.anchor, {
                                    type: 'image',
                                    attrs: {
                                        src: fileReader.result,
                                    },
                                })
                                .focus()
                                .run()
                        }
                    })
                },
            }),
            TableRow, TableHeader, TableCell,
            Highlight,
            Typography,
            Underline,
            Text,
            Paragraph,
            Dropcursor
        ],
        content: content,
        // Don't render immediately on the server to avoid SSR issues
        immediatelyRender: false,
        onUpdate: (({ editor }) => {
            setContent(editor.getHTML())
        }),
    })

    useEffect(() => {
        if (editor && content !== editor.getHTML()) {
            editor.commands.setContent(content);
        }
    }, [content, editor]);

    const editorNavbar = useRef<HTMLElement | null>(null)
    const editorNavbarTitle = useRef<HTMLElement | null>(null)

    useEffect(() => {
        if (document) {
            editorNavbar.current = document.getElementById("editor-navbar")
            editorNavbarTitle.current = document.getElementById("editor-navbar-title")
        }
    }, [])

    const rightPanelRef = usePanelRef()

    return (
        <div className='w-full h-full'>
            {editorNavbarTitle.current &&
                createPortal(<span>{data.post_title}</span>, editorNavbarTitle.current)
            }

            {editorNavbar.current &&
                createPortal(
                    <div className='space-x-2'>
                        <button className="btn btn-sm" onClick={() => {
                            if (previewModal) {
                                previewModal.current?.showModal()
                            }
                        }}>
                            Предпросмотр
                        </button>
                        <button className="btn btn-sm" onClick={() => {
                            if (previewModal) {
                                previewModal.current?.showModal()
                            }
                        }}>
                            Опубликовать
                        </button>
                    </div>
                    , editorNavbar.current)}


            <Group orientation='horizontal' className='w-full max-h-screen'>
                <Panel className='border-r border-r-gray-300 overflow-auto'>
                    {editor &&
                        <TiptapToolbar editor={editor} />
                    }

                    {editor ?
                        <div className='relative'>
                            <EditorContent editor={editor} />
                            <TiptapFloatingMenu editor={editor}/>
                            <TiptapBubbleMenu editor={editor} />
                        </div>
                        :
                        <div className='loading'></div>
                    }

                </Panel>

                <Panel panelRef={rightPanelRef} defaultSize={'25%'} minSize={'15%'} maxSize={'40%'} className='p-4 overflow-auto'>
                    <PostSettings data={data} />
                </Panel>
            </Group>

            {
                <dialog ref={previewModal} id="preview_modal" className="modal">
                    <div className="modal-box w-full! max-w-full!">
                        <form method="dialog">
                            <button className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
                        </form>
                        <Post post={{ ...data, post_content: content }} />
                    </div>
                </dialog>
            }

        </div >
    )
}

export default Tiptap
