import { useState, useRef, useCallback } from 'react'
import { Editor, rootCtx, defaultValueCtx } from '@milkdown/core'
import { commonmark, toggleStrongCommand, toggleEmphasisCommand, wrapInBulletListCommand, wrapInOrderedListCommand, wrapInBlockquoteCommand, insertHrCommand } from '@milkdown/preset-commonmark'
import { gfm, insertTableCommand, toggleStrikethroughCommand } from '@milkdown/preset-gfm'
import { history, undoCommand, redoCommand } from '@milkdown/plugin-history'
import { listener, listenerCtx } from '@milkdown/plugin-listener'
import { math } from '@milkdown/plugin-math'
import { nord } from '@milkdown/theme-nord'
import { Milkdown, MilkdownProvider, useEditor, useInstance } from '@milkdown/react'
import { callCommand } from '@milkdown/utils'
import '@milkdown/theme-nord/style.css'
import 'katex/dist/katex.min.css'

function Toolbar() {
  const [, getEditor] = useInstance()
  const call = (cmd, payload) => {
    const editor = getEditor()
    if (editor) editor.action(callCommand(cmd, payload))
  }

  const btn = { background: 'none', border: '1px solid #e2e8f0', borderRadius: 4, padding: '4px 8px', cursor: 'pointer', fontSize: '0.82rem', color: '#475569', lineHeight: 1 }
  const sep = { width: 1, height: 20, background: '#e2e8f0', margin: '0 4px' }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 3, padding: '6px 10px', borderBottom: '1px solid #e2e8f0', background: '#f8fafc', flexWrap: 'wrap' }}>
      <button style={btn} onClick={() => call(undoCommand.key)} title="Undo (Ctrl+Z)">↩</button>
      <button style={btn} onClick={() => call(redoCommand.key)} title="Redo (Ctrl+Shift+Z)">↪</button>
      <div style={sep} />
      <button style={{ ...btn, fontWeight: 700 }} onClick={() => call(toggleStrongCommand.key)} title="Bold (Ctrl+B)">B</button>
      <button style={{ ...btn, fontStyle: 'italic' }} onClick={() => call(toggleEmphasisCommand.key)} title="Italic (Ctrl+I)">I</button>
      <button style={{ ...btn, textDecoration: 'line-through' }} onClick={() => call(toggleStrikethroughCommand.key)} title="Strikethrough">S</button>
      <div style={sep} />
      <button style={btn} onClick={() => call(wrapInBulletListCommand.key)} title="Bullet list">&#8226; List</button>
      <button style={btn} onClick={() => call(wrapInOrderedListCommand.key)} title="Numbered list">1. List</button>
      <button style={btn} onClick={() => call(wrapInBlockquoteCommand.key)} title="Blockquote">&gt; Quote</button>
      <div style={sep} />
      <button style={btn} onClick={() => call(insertTableCommand.key)} title="Insert table">Table</button>
      <button style={btn} onClick={() => call(insertHrCommand.key)} title="Horizontal rule">― HR</button>
    </div>
  )
}

function MilkdownEditor({ value, onChange, placeholder }) {
  const isInternalChange = useRef(false)
  const lastValue = useRef(value)

  useEditor((root) =>
    Editor.make()
      .config(nord)
      .config((ctx) => {
        ctx.set(rootCtx, root)
        ctx.set(defaultValueCtx, value || '')
        const l = ctx.get(listenerCtx)
        l.markdownUpdated((_, md) => {
          isInternalChange.current = true
          lastValue.current = md
          onChange(md)
        })
      })
      .use(commonmark)
      .use(gfm)
      .use(history)
      .use(math)
      .use(listener),
    [])

  return <Milkdown />
}

export default function RichEditor({ value, onChange, height = 350, placeholder = 'Start writing...' }) {
  const [editorKey, setEditorKey] = useState(0)
  const isInternalChange = useRef(false)
  const lastSetValue = useRef(value)

  if (value !== lastSetValue.current && !isInternalChange.current) {
    lastSetValue.current = value
    setEditorKey(k => k + 1)
  }
  isInternalChange.current = false

  const handleChange = useCallback((md) => {
    isInternalChange.current = true
    lastSetValue.current = md
    onChange(md)
  }, [onChange])

  return (
    <div className="milkdown-wrapper" style={{ border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden', background: '#fff' }}>
      <MilkdownProvider key={editorKey}>
        <Toolbar />
        <MilkdownEditor value={value} onChange={handleChange} placeholder={placeholder} />
      </MilkdownProvider>
      <style>{`
        .milkdown-wrapper .milkdown { min-height: ${height}px; }
        .milkdown-wrapper .editor { padding: 16px 20px; outline: none; font-family: Inter, -apple-system, sans-serif; font-size: 14px; line-height: 1.7; color: #1e293b; }
        .milkdown-wrapper .editor > * { margin-top: 0; margin-bottom: 0.5em; }
        .milkdown-wrapper .editor h2 { font-size: 1.3em; margin-top: 1.2em; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; }
        .milkdown-wrapper .editor h3 { font-size: 1.1em; margin-top: 1em; }
        .milkdown-wrapper .editor table { border-collapse: collapse; width: 100%; margin: 12px 0; }
        .milkdown-wrapper .editor td, .milkdown-wrapper .editor th { border: 1px solid #d1d5db; padding: 6px 10px; text-align: left; }
        .milkdown-wrapper .editor th { background: #f8fafc; font-weight: 600; }
        .milkdown-wrapper .editor a { color: #2563eb; text-decoration: underline; }
        .milkdown-wrapper .editor img { max-width: 100%; border-radius: 6px; }
        .milkdown-wrapper .editor blockquote { border-left: 3px solid #2563eb; padding-left: 12px; color: #64748b; margin: 8px 0; }
        .milkdown-wrapper .editor code { background: #f1f5f9; padding: 2px 5px; border-radius: 4px; font-size: 0.88em; }
        .milkdown-wrapper .editor pre { background: #f1f5f9; padding: 12px; border-radius: 8px; overflow-x: auto; }
        .milkdown-wrapper .editor hr { border: none; border-top: 1px solid #e2e8f0; margin: 1.5em 0; }
        .milkdown-wrapper .editor ul, .milkdown-wrapper .editor ol { padding-left: 1.5em; }
        .milkdown-wrapper .editor li { margin-bottom: 0.3em; }
        .milkdown-wrapper .editor p:empty::before { content: '${placeholder}'; color: #94a3b8; }
      `}</style>
    </div>
  )
}
