import { useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { Eye, Edit2 } from 'lucide-react'

interface MarkdownEditorProps {
  value: string
  onChange: (value: string) => void
  height?: number
}

export function MarkdownEditor({ value, onChange, height = 250 }: MarkdownEditorProps) {
  const [mode, setMode] = useState<'edit' | 'preview'>('edit')

  return (
    <div className="border border-[var(--border)] rounded-lg overflow-hidden" style={{ height }}>
      <div className="flex items-center gap-1 px-3 py-2 bg-[var(--bg-secondary)] border-b border-[var(--border)]">
        <button
          onClick={() => setMode('edit')}
          className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs transition-colors ${
            mode === 'edit'
              ? 'bg-[var(--accent)] text-white'
              : 'hover:bg-[var(--bg-hover)] text-[var(--text-secondary)]'
          }`}
        >
          <Edit2 className="w-3.5 h-3.5" />
          编辑
        </button>
        <button
          onClick={() => setMode('preview')}
          className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs transition-colors ${
            mode === 'preview'
              ? 'bg-[var(--accent)] text-white'
              : 'hover:bg-[var(--bg-hover)] text-[var(--text-secondary)]'
          }`}
        >
          <Eye className="w-3.5 h-3.5" />
          预览
        </button>
      </div>
      <div className="h-[calc(100%-40px)] overflow-y-auto">
        {mode === 'edit' ? (
          <textarea
            value={value}
            onChange={(e) => onChange(e.target.value)}
            className="w-full h-full p-4 bg-[var(--bg-tertiary)] text-[var(--text-primary)] outline-none resize-none font-mono text-sm"
            style={{ height: height - 40 }}
          />
        ) : (
          <div className="p-4 prose prose-invert prose-sm max-w-none bg-[var(--bg-tertiary)]">
            <ReactMarkdown remarkPlugins={[remarkGfm]}>
              {value || '*无内容*'}
            </ReactMarkdown>
          </div>
        )}
      </div>
    </div>
  )
}
