import { FC, useCallback, useEffect, useRef } from 'react'
import Quill from 'quill'
import VideoBlot, { getEmbedUrl } from './VideoBlot'
import 'quill/dist/quill.snow.css'

// ثبت VideoBlot در Quill
Quill.register('formats/video', VideoBlot)

interface QuillEditorProps {
    value?: string
    onChange?: (content: string) => void
    placeholder?: string
    className?: string
    minHeight?: string
    id?: string
    defaultAltText?: string // عنوان مقاله یا متن پیش‌فرض برای alt
}

const QuillEditor: FC<QuillEditorProps> = ({
    value = '',
    onChange,
    placeholder = '',
    className = '',
    minHeight = '200px',
    id = 'quill-editor',
    defaultAltText = 'تصویر'
}) => {
    const editorRef = useRef<HTMLDivElement>(null)
    const quillRef = useRef<Quill | null>(null)
    const defaultAltTextRef = useRef(defaultAltText)
    const onChangeRef = useRef(onChange)

    useEffect(() => {
        defaultAltTextRef.current = defaultAltText || 'تصویر'
    }, [defaultAltText])

    useEffect(() => {
        onChangeRef.current = onChange
    }, [onChange])

    const imageHandler = useCallback(() => {
        const input = document.createElement('input')
        input.setAttribute('type', 'file')
        input.setAttribute('accept', 'image/*')
        input.click()

        input.onchange = async () => {
            const file = input.files?.[0]
            if (file && quillRef.current) {
                const altText = prompt('متن جایگزین (Alt Text) تصویر را وارد کنید:', defaultAltTextRef.current)

                if (altText !== null) {
                    const reader = new FileReader()
                    reader.onload = (e) => {
                        const imageUrl = e.target?.result as string
                        const range = quillRef.current?.getSelection(true)

                        if (range && quillRef.current) {
                            quillRef.current.insertEmbed(range.index, 'image', imageUrl)

                            setTimeout(() => {
                                const images = quillRef.current?.root.querySelectorAll('img')
                                if (images && images.length > 0) {
                                    const lastImage = images[images.length - 1]
                                    const cleanedAlt = altText.trim()
                                    lastImage.setAttribute('alt', cleanedAlt || defaultAltTextRef.current)
                                }

                                if (quillRef.current) {
                                    onChangeRef.current?.(quillRef.current.root.innerHTML)
                                }
                            }, 0)

                            quillRef.current.setSelection(range.index + 1)
                        }
                    }
                    reader.readAsDataURL(file)
                }
            }
        }
    }, [])

    useEffect(() => {
        if (!editorRef.current || quillRef.current) return

        const toolbarOptions = [
            ['bold', 'italic', 'underline'],
            [{ 'header': 1 }, { 'header': 2 }, { 'header': 3 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'direction': 'rtl' }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'align': [] }],
            ['link', 'image'],
            ['clean']
        ]

        const quill = new Quill(editorRef.current, {
            theme: 'snow',
            placeholder,
            modules: {
                toolbar: {
                    container: toolbarOptions,
                    handlers: {
                        image: imageHandler
                    }
                }
            }
        })

        if (value) {
            quill.clipboard.dangerouslyPasteHTML(value)
        }

        const handleTextChange = () => {
            const html = quill.root.innerHTML
            onChangeRef.current?.(html)
        }

        quill.on('text-change', handleTextChange)

        quillRef.current = quill

        return () => {
            quill.off('text-change', handleTextChange)
            quillRef.current = null
            if (editorRef.current) {
                editorRef.current.innerHTML = ''
            }
        }
    }, [imageHandler, placeholder])

    useEffect(() => {
        if (quillRef.current && value !== quillRef.current.root.innerHTML) {
            quillRef.current.root.innerHTML = value
        }
    }, [value])

    const handleYouTubeClick = () => {
        const url = prompt('لینک ویدیو یوتیوب را وارد کنید:')
        if (url && quillRef.current) {
            const embedUrl = getEmbedUrl(url)
            if (embedUrl) {
                const range = quillRef.current.getSelection() || { index: 0, length: 0 }
                quillRef.current.insertEmbed(range.index, 'video', {
                    url: embedUrl,
                    width: '100%',
                    height: 'auto'
                })
                quillRef.current.setSelection(range.index + 1)
            } else {
                alert('لینک ویدیو معتبر نیست')
            }
        }
    }

    const handleAparatClick = () => {
        const url = prompt('لینک ویدیو آپارات را وارد کنید:')
        if (url && quillRef.current) {
            const embedUrl = getEmbedUrl(url)
            if (embedUrl) {
                const range = quillRef.current.getSelection() || { index: 0, length: 0 }
                quillRef.current.insertEmbed(range.index, 'video', {
                    url: embedUrl,
                    width: '100%',
                    height: 'auto'
                })
                quillRef.current.setSelection(range.index + 1)
            } else {
                alert('لینک ویدیو معتبر نیست')
            }
        }
    }

    return (
        <div className={className}>
            {/* دکمه‌های ویدیو بالای ادیتور */}
            <div className="flex gap-2 mb-2">
                <button
                    type="button"
                    onClick={handleYouTubeClick}
                    className="px-3 py-1 text-xs font-bold text-red-600 border border-gray-300 rounded hover:bg-gray-50"
                    title="درج ویدیو یوتیوب"
                >
                    📺 YouTube
                </button>
                <button
                    type="button"
                    onClick={handleAparatClick}
                    className="px-3 py-1 text-xs font-bold text-blue-600 border border-gray-300 rounded hover:bg-gray-50"
                    title="درج ویدیو آپارات"
                >
                    🎬 آپارات
                </button>
            </div>

            <div
                ref={editorRef}
                id={id}
                style={{ minHeight }}
                className="quill-editor-container"
            />
            <style dangerouslySetInnerHTML={{
                __html: `
                    .ql-video-wrapper {
                        margin: 1em 0;
                        text-align: center;
                        position: relative;
                        width: 100%;
                        aspect-ratio: 16/9;
                    }
                    .ql-video-wrapper iframe {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        border-radius: 8px;
                        border: none;
                    }
                `
            }} />
        </div>
    )
}

export default QuillEditor
