'use client'

import { useState, useRef, RefObject } from 'react'

interface UseRichTextEditorResult {
  editorRef: RefObject<HTMLDivElement | null>
  fileInputRef: RefObject<HTMLInputElement | null>
  uploading: boolean
  uploadError: string | null
  setUploadError: (e: string | null) => void
  formatDoc: (cmd: string, value?: string | null) => void
  formatBlock: (tag: string) => void
  insertLink: () => void
  updateEditorContent: () => void
  handleWordUpload: (event: React.ChangeEvent<HTMLInputElement>) => Promise<void>
  handlePaste: (e: React.ClipboardEvent) => void
}

export function useRichTextEditor(
  setEditedContent: (content: string) => void,
): UseRichTextEditorResult {
  const editorRef = useRef<HTMLDivElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [uploadError, setUploadError] = useState<string | null>(null)

  const updateEditorContent = () => {
    if (editorRef.current) {
      setEditedContent(editorRef.current.innerHTML)
    }
  }

  const formatDoc = (cmd: string, value: string | null = null) => {
    if (editorRef.current) {
      editorRef.current.focus()
      document.execCommand(cmd, false, value || undefined)
      updateEditorContent()
    }
  }

  const formatBlock = (tag: string) => {
    if (editorRef.current) {
      editorRef.current.focus()
      document.execCommand('formatBlock', false, `<${tag}>`)
      updateEditorContent()
    }
  }

  const insertLink = () => {
    const url = prompt('Link-URL eingeben:', 'https://')
    if (url && editorRef.current) {
      editorRef.current.focus()
      document.execCommand('createLink', false, url)
      updateEditorContent()
    }
  }

  const cleanWordHtml = (html: string): string => {
    let cleaned = html
    cleaned = cleaned.replace(/\s*mso-[^:]+:[^;]+;?/gi, '')
    cleaned = cleaned.replace(/\s*style="[^"]*"/gi, '')
    cleaned = cleaned.replace(/\s*class="[^"]*"/gi, '')
    cleaned = cleaned.replace(/<o:p><\/o:p>/gi, '')
    cleaned = cleaned.replace(/<\/?o:[^>]*>/gi, '')
    cleaned = cleaned.replace(/<\/?w:[^>]*>/gi, '')
    cleaned = cleaned.replace(/<\/?m:[^>]*>/gi, '')
    cleaned = cleaned.replace(/<span[^>]*>\s*<\/span>/gi, '')
    return cleaned
  }

  const handleWordUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    setUploading(true)

    const formData = new FormData()
    formData.append('file', file)

    try {
      const response = await fetch('/api/admin/consent/versions/upload-word', {
        method: 'POST',
        body: formData
      })

      if (response.ok) {
        const data = await response.json()
        if (editorRef.current) {
          editorRef.current.innerHTML = data.html || '<p>Konvertierung fehlgeschlagen</p>'
          setEditedContent(editorRef.current.innerHTML)
        }
      } else {
        const errorData = await response.json().catch(() => ({}))
        setUploadError('Fehler beim Importieren: ' + (errorData.detail || 'Unbekannter Fehler'))
      }
    } catch (e) {
      setUploadError('Fehler beim Hochladen: ' + (e instanceof Error ? e.message : 'Unbekannter Fehler'))
    } finally {
      setUploading(false)
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  const handlePaste = (e: React.ClipboardEvent) => {
    const clipboardData = e.clipboardData
    const html = clipboardData.getData('text/html')

    if (html) {
      e.preventDefault()
      const cleanHtml = cleanWordHtml(html)
      document.execCommand('insertHTML', false, cleanHtml)
      updateEditorContent()
    }
  }

  return {
    editorRef,
    fileInputRef,
    uploading,
    uploadError,
    setUploadError,
    formatDoc,
    formatBlock,
    insertLink,
    updateEditorContent,
    handleWordUpload,
    handlePaste,
  }
}
