import React, { useCallback, useRef, useState } from 'react'
import ReactMarkdown from 'react-markdown'

function ToolbarButton({ title, onClick, children }) {
  return (
    <button
      type="button"
      title={title}
      onMouseDown={(event) => {
        event.preventDefault()
        onClick()
      }}
      className="inline-flex h-7 min-w-7 items-center justify-center rounded-md px-1.5 text-xs font-semibold text-white/55 transition hover:bg-white/10 hover:text-white"
    >
      {children}
    </button>
  )
}

export default function MarkdownEditor({ id, value, onChange, placeholder, error, rows = 5 }) {
  const [tab, setTab] = useState('write')
  const textareaRef = useRef(null)

  const wrapSelection = useCallback((before, after) => {
    const textarea = textareaRef.current
    if (!textarea) return

    const current = String(value || '')
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const selected = current.slice(start, end)
    const replacement = before + (selected || 'text') + after
    const next = current.slice(0, start) + replacement + current.slice(end)
    onChange?.(next)

    requestAnimationFrame(() => {
      textarea.focus()
      textarea.selectionStart = selected ? start + replacement.length : start + before.length
      textarea.selectionEnd = selected ? start + replacement.length : start + before.length + 4
    })
  }, [onChange, value])

  const prefixLines = useCallback((prefix) => {
    const textarea = textareaRef.current
    if (!textarea) return

    const current = String(value || '')
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const selected = current.slice(start, end)
    const lines = (selected || '').split('\n')
    const normalized = (lines.length ? lines : ['']).map((line) => `${prefix}${line}`).join('\n')
    const next = current.slice(0, start) + normalized + current.slice(end)
    onChange?.(next)

    requestAnimationFrame(() => {
      textarea.focus()
      textarea.selectionStart = start
      textarea.selectionEnd = start + normalized.length
    })
  }, [onChange, value])

  const insertLink = useCallback(() => {
    const textarea = textareaRef.current
    if (!textarea) return

    const current = String(value || '')
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const selected = current.slice(start, end)
    const replacement = selected && /^https?:\/\//i.test(selected)
      ? `[link](${selected})`
      : `[${selected || 'link'}](https://)`
    const next = current.slice(0, start) + replacement + current.slice(end)
    onChange?.(next)

    requestAnimationFrame(() => {
      textarea.focus()
    })
  }, [onChange, value])

  const handleKeyDown = useCallback((event) => {
    const withModifier = event.ctrlKey || event.metaKey
    if (!withModifier) return

    switch (event.key.toLowerCase()) {
      case 'b':
        event.preventDefault()
        wrapSelection('**', '**')
        break
      case 'i':
        event.preventDefault()
        wrapSelection('*', '*')
        break
      case 'k':
        event.preventDefault()
        insertLink()
        break
      case 'e':
        event.preventDefault()
        wrapSelection('`', '`')
        break
      default:
        break
    }
  }, [insertLink, wrapSelection])

  return (
    <div className={`rounded-xl border bg-white/10 ${error ? 'border-red-300/60' : 'border-white/15'}`}>
      <div className="flex items-center justify-between border-b border-white/10 px-2 py-1.5">
        <div className="flex items-center gap-1">
          <button
            type="button"
            onClick={() => setTab('write')}
            className={`rounded-md px-2.5 py-1 text-xs font-medium transition ${tab === 'write' ? 'bg-white/12 text-white' : 'text-white/55 hover:text-white/80'}`}
          >
            Write
          </button>
          <button
            type="button"
            onClick={() => setTab('preview')}
            className={`rounded-md px-2.5 py-1 text-xs font-medium transition ${tab === 'preview' ? 'bg-white/12 text-white' : 'text-white/55 hover:text-white/80'}`}
          >
            Preview
          </button>
        </div>
      </div>

      {tab === 'write' && (
        <>
          <div className="flex items-center gap-1 border-b border-white/10 px-2 py-1">
            <ToolbarButton title="Bold (Ctrl+B)" onClick={() => wrapSelection('**', '**')}>B</ToolbarButton>
            <ToolbarButton title="Italic (Ctrl+I)" onClick={() => wrapSelection('*', '*')}>I</ToolbarButton>
            <ToolbarButton title="Inline code (Ctrl+E)" onClick={() => wrapSelection('`', '`')}>{'</>'}</ToolbarButton>
            <ToolbarButton title="Link (Ctrl+K)" onClick={insertLink}>Link</ToolbarButton>
            <span className="mx-1 h-4 w-px bg-white/10" aria-hidden="true" />
            <ToolbarButton title="Bulleted list" onClick={() => prefixLines('- ')}>• List</ToolbarButton>
            <ToolbarButton title="Quote" onClick={() => prefixLines('> ')}>❝</ToolbarButton>
          </div>

          <textarea
            id={id}
            ref={textareaRef}
            value={value}
            onChange={(event) => onChange?.(event.target.value)}
            onKeyDown={handleKeyDown}
            rows={rows}
            className="w-full resize-y bg-transparent px-3 py-2 text-sm text-white placeholder-white/45 focus:outline-none"
            placeholder={placeholder}
          />

          <p className="px-3 pb-2 text-[11px] text-white/45">
            Markdown supported · Ctrl+B bold · Ctrl+I italic · Ctrl+K link
          </p>
        </>
      )}

      {tab === 'preview' && (
        <div className="min-h-[132px] px-3 py-2">
          {String(value || '').trim() ? (
            <div className="prose prose-invert prose-sm max-w-none text-white/85 [&_a]:text-sky-300 [&_a]:no-underline hover:[&_a]:underline [&_blockquote]:border-l-2 [&_blockquote]:border-white/20 [&_blockquote]:pl-3 [&_code]:rounded [&_code]:bg-white/10 [&_code]:px-1 [&_code]:py-0.5 [&_ul]:pl-4 [&_ol]:pl-4">
              <ReactMarkdown
                allowedElements={['p', 'strong', 'em', 'a', 'code', 'pre', 'ul', 'ol', 'li', 'blockquote', 'br']}
                unwrapDisallowed
                components={{
                  a: ({ href, children }) => (
                    <a href={href} target="_blank" rel="noopener noreferrer nofollow">{children}</a>
                  ),
                }}
              >
                {String(value || '')}
              </ReactMarkdown>
            </div>
          ) : (
            <p className="text-sm italic text-white/35">Nothing to preview</p>
          )}
        </div>
      )}
    </div>
  )
}
