import { useEffect } from 'react'
import Placeholder from '@tiptap/extension-placeholder'
import Underline from '@tiptap/extension-underline'
import { EditorContent, useEditor } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import {
  Bold,
  Heading2,
  Heading3,
  Italic,
  List,
  ListOrdered,
  Quote,
  Redo2,
  Underline as UnderlineIcon,
  Undo2,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'

type RichTextEditorProps = {
  value: string
  onChange: (value: string) => void
  placeholder?: string
}

export function RichTextEditor({
  value,
  onChange,
  placeholder = 'İçeriği yazın...',
}: RichTextEditorProps) {
  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        heading: {
          levels: [2, 3],
        },
      }),
      Underline,
      Placeholder.configure({
        placeholder,
      }),
    ],
    content: value,
    immediatelyRender: false,
    editorProps: {
      attributes: {
        class:
          'min-h-52 rounded-b-2xl bg-background px-5 py-4 text-sm leading-7 text-foreground outline-none [&_.is-empty::before]:pointer-events-none [&_.is-empty::before]:float-left [&_.is-empty::before]:h-0 [&_.is-empty::before]:text-muted-foreground [&_.is-empty::before]:content-[attr(data-placeholder)] [&_blockquote]:border-s-4 [&_blockquote]:border-primary/30 [&_blockquote]:ps-4 [&_blockquote]:italic [&_h2]:mt-5 [&_h2]:text-xl [&_h2]:font-semibold [&_h3]:mt-4 [&_h3]:text-lg [&_h3]:font-semibold [&_ol]:list-decimal [&_ol]:ps-6 [&_p]:my-3 [&_ul]:list-disc [&_ul]:ps-6',
      },
    },
    onUpdate: ({ editor: currentEditor }) => {
      onChange(currentEditor.getHTML())
    },
  })

  useEffect(() => {
    if (!editor) {
      return
    }

    if (editor.getHTML() !== value) {
      editor.commands.setContent(value || '<p></p>', {
        emitUpdate: false,
      })
    }
  }, [editor, value])

  if (!editor) {
    return null
  }

  const toolbarButtons = [
    {
      label: 'Kalın',
      icon: Bold,
      isActive: editor.isActive('bold'),
      onClick: () => editor.chain().focus().toggleBold().run(),
    },
    {
      label: 'İtalik',
      icon: Italic,
      isActive: editor.isActive('italic'),
      onClick: () => editor.chain().focus().toggleItalic().run(),
    },
    {
      label: 'Altı çizili',
      icon: UnderlineIcon,
      isActive: editor.isActive('underline'),
      onClick: () => editor.chain().focus().toggleUnderline().run(),
    },
    {
      label: 'Başlık 2',
      icon: Heading2,
      isActive: editor.isActive('heading', { level: 2 }),
      onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
    },
    {
      label: 'Başlık 3',
      icon: Heading3,
      isActive: editor.isActive('heading', { level: 3 }),
      onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
    },
    {
      label: 'Madde listesi',
      icon: List,
      isActive: editor.isActive('bulletList'),
      onClick: () => editor.chain().focus().toggleBulletList().run(),
    },
    {
      label: 'Numaralı liste',
      icon: ListOrdered,
      isActive: editor.isActive('orderedList'),
      onClick: () => editor.chain().focus().toggleOrderedList().run(),
    },
    {
      label: 'Alıntı',
      icon: Quote,
      isActive: editor.isActive('blockquote'),
      onClick: () => editor.chain().focus().toggleBlockquote().run(),
    },
  ]

  return (
    <div className='overflow-hidden rounded-2xl border border-border/70 bg-muted/10'>
      <div className='flex flex-wrap gap-2 border-b border-border/70 bg-muted/30 p-3'>
        {toolbarButtons.map((item) => {
          const Icon = item.icon

          return (
            <Button
              key={item.label}
              type='button'
              variant='outline'
              size='sm'
              className={cn(
                'rounded-lg border-border/70 bg-background/80',
                item.isActive &&
                  'border-primary/40 bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary'
              )}
              onClick={item.onClick}
            >
              <Icon className='size-4' />
              {item.label}
            </Button>
          )
        })}

        <div className='mx-1 hidden h-8 w-px bg-border md:block' />

        <Button
          type='button'
          variant='outline'
          size='sm'
          className='rounded-lg border-border/70 bg-background/80'
          onClick={() => editor.chain().focus().undo().run()}
          disabled={!editor.can().chain().focus().undo().run()}
        >
          <Undo2 className='size-4' />
          Geri al
        </Button>
        <Button
          type='button'
          variant='outline'
          size='sm'
          className='rounded-lg border-border/70 bg-background/80'
          onClick={() => editor.chain().focus().redo().run()}
          disabled={!editor.can().chain().focus().redo().run()}
        >
          <Redo2 className='size-4' />
          İleri al
        </Button>
      </div>

      <EditorContent editor={editor} />
    </div>
  )
}
