import React, { useEffect, useRef } from 'react'
import { Label } from 'flowbite-react'
import Quill from 'quill'
import formTheme from '../themes/form'

interface TextEditorProps {
  htmlFor: string
  labelText: string
  content: string
  setContent: (content: string) => void
}

const customStyles = `
  .ql-editor {
    font-family: 'Figtree', sans-serif !important;
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="figtree"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="figtree"]::before {
    content: "Figtree";
    font-family: "Figtree", sans-serif;
  }
`

const transformListContent = (content: string): string => {
  return (
    content?.replace(/<ul>(.*?)<\/ul>/g, (match, listContent) => {
      const items = listContent.match(/<li>(.*?)<\/li>/g) || []
      const transformedItems = items.map((item: string) => {
        return item.replace(/<li>(.*?)<\/li>/, '<li data-list="bullet">$1</li>')
      })
      return `<ol>${transformedItems.join('')}</ol>`
    }) ?? ''
  )
}

const TextEditor: React.FC<TextEditorProps> = ({
  content,
  htmlFor,
  labelText,
  setContent,
}) => {
  const editorRef = useRef<HTMLDivElement>(null)
  const quillRef = useRef<Quill | null>(null)
  const styleSheetRef = useRef<HTMLStyleElement | null>(null)

  useEffect(() => {
    // Add custom styles for Figtree font
    if (!styleSheetRef.current) {
      const styleSheet = document.createElement('style')
      styleSheet.textContent = customStyles
      document.head.appendChild(styleSheet)
      styleSheetRef.current = styleSheet
    }

    // Register Figtree font
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const Font = Quill.import('formats/font') as any
    Font.whitelist = ['figtree'] // Only allow Figtree font
    Quill.register(Font, true)

    if (editorRef.current && !quillRef.current) {
      quillRef.current = new Quill(editorRef.current, {
        theme: 'snow',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block'],
            [
              'link',
              // 'image',
              // 'video',
              'formula',
            ],

            [{ header: 1 }, { header: 2 }], // custom button values
            [{ list: 'ordered' }, { list: 'bullet' }, { list: 'check' }],
            [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
            [{ direction: 'rtl' }], // text direction

            [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
            [{ header: [1, 2, 3, 4, 5, 6, false] }],

            [{ color: [] }, { background: [] }], // dropdown with defaults from theme
            [{ align: [] }],

            ['clean'],
          ],
        },
        formats: [
          'bold',
          'italic',
          'underline',
          'strike',
          'blockquote',
          'code-block',
          'link',
          'image',
          'video',
          'header',
          'list',
          'script',
          'indent',
          'direction',
          'size',
          'color',
          'background',
          'align',
          // Note: 'font' is removed from formats to enforce Figtree
        ],
      })

      quillRef.current.root.style.fontFamily = 'Figtree, sans-serif'
      quillRef.current.root.innerHTML = transformListContent(content)

      quillRef.current.on('text-change', (delta, oldDelta, source) => {
        if (source === 'user') {
          const content = quillRef.current?.getText
            ? quillRef.current
                ?.getSemanticHTML()
                .replace(/\u00A0/g, ' ') // Replace non-breaking space with regular space
                .replace(/&nbsp;/g, ' ') // Replace HTML entity &nbsp; with regular space
            : ''
          setContent(content || '')
        }
      })
    }
  }, [content, setContent])

  return (
    <div className="mb-2 block mt-4">
      <Label theme={formTheme.label} htmlFor={htmlFor}>
        {labelText}
      </Label>

      <div className="mt-2 bg-gray-50">
        <div ref={editorRef}></div>
      </div>
    </div>
  )
}

export default TextEditor
