import { useEffect } from 'react'
import Box from '@mui/material/Box'
import { EditorContent, useEditor } from '@tiptap/react'
import TiptapStarterKit from '@tiptap/starter-kit'

type RichTextMessageContentProps = {
  value: string
  tone?: 'default' | 'review' | 'chat'
}

export function RichTextMessageContent({ value, tone = 'default' }: RichTextMessageContentProps) {
  const editor = useEditor({
    extensions: [
      TiptapStarterKit.configure({ heading: false, codeBlock: false, blockquote: false, horizontalRule: false }),
    ],
    content: value.trim() ? value : '<p></p>',
    editable: false,
  })

  useEffect(() => {
    if (!editor) return
    const normalizedValue = value.trim() ? value : '<p></p>'
    if (editor.getHTML() === normalizedValue) return
    editor.commands.setContent(normalizedValue, false)
  }, [editor, value])

  return (
    <Box
      sx={{
        '& .ProseMirror': {
          outline: 'none',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word',
          ...(tone === 'review'
            ? {
                fontSize: '0.875rem',
                lineHeight: 1.5,
              }
            : tone === 'chat'
              ? {
                  fontSize: '0.95rem',
                  lineHeight: 1.45,
                }
              : {}),
        },
        '& .ProseMirror p': {
          m: 0,
        },
        '& .ProseMirror p + p': {
          mt: tone === 'review' ? 0.75 : tone === 'chat' ? 0.5 : 0.5,
        },
        '& .ProseMirror ul, & .ProseMirror ol': {
          my: tone === 'review' ? 0.75 : tone === 'chat' ? 0.25 : 0,
          pl: 3,
        },
        '& .ProseMirror li + li': {
          mt: tone === 'review' ? 0.25 : tone === 'chat' ? 0.15 : 0,
        },
      }}
    >
      <EditorContent editor={editor} />
    </Box>
  )
}
