// components/markdown/markdown-editor.tsx
"use client"

import { useState, useRef } from "react"
import { Bold, Italic, Code, Link, List, Quote, Hash } from "lucide-react"
import { MarkdownViewer } from "./markdown-viewer"

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

export function MarkdownEditor({
  value,
  onChange,
  placeholder = "Write your comment...",
  disabled = false,
  height = 150,
  className = "",
}: MarkdownEditorProps) {
  const [isPreview, setIsPreview] = useState(false)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  const insertMarkdown = (before: string, after: string = "") => {
    if (!textareaRef.current || disabled) return

    const textarea = textareaRef.current
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    const selectedText = value.substring(start, end)
    const newText = value.substring(0, start) + before + selectedText + after + value.substring(end)

    onChange(newText)

    // Reset cursor position
    setTimeout(() => {
      textarea.focus()
      const newCursorPos = start + before.length + selectedText.length
      textarea.setSelectionRange(newCursorPos, newCursorPos)
    }, 0)
  }

  const toolbarButtons = [
    { icon: Bold, action: () => insertMarkdown("**", "**"), title: "Bold" },
    { icon: Italic, action: () => insertMarkdown("*", "*"), title: "Italic" },
    { icon: Code, action: () => insertMarkdown("`", "`"), title: "Code" },
    { icon: Link, action: () => insertMarkdown("[", "](url)"), title: "Link" },
    { icon: Quote, action: () => insertMarkdown("> ", ""), title: "Quote" },
    { icon: List, action: () => insertMarkdown("- ", ""), title: "List" },
    { icon: Hash, action: () => insertMarkdown("### ", ""), title: "Heading" },
  ]

  return (
    <div className={`border border-border rounded-md overflow-hidden bg-background ${className}`}>
      {/* Toolbar */}
      <div className="flex items-center justify-between px-2 py-1 border-b border-border bg-muted/30">
        <div className="flex items-center gap-1">
          {toolbarButtons.map((button, index) => {
            const Icon = button.icon
            return (
              <button
                key={index}
                onClick={button.action}
                disabled={disabled || isPreview}
                title={button.title}
                className="p-1.5 rounded hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <Icon className="w-4 h-4" />
              </button>
            )
          })}
        </div>
        <div className="flex items-center gap-2 text-xs">
          <button
            onClick={() => setIsPreview(false)}
            className={`px-2 py-1 rounded transition-colors ${
              !isPreview ? "bg-primary text-primary-foreground" : "hover:bg-muted"
            }`}
          >
            Write
          </button>
          <button
            onClick={() => setIsPreview(true)}
            className={`px-2 py-1 rounded transition-colors ${
              isPreview ? "bg-primary text-primary-foreground" : "hover:bg-muted"
            }`}
          >
            Preview
          </button>
        </div>
      </div>

      {/* Editor/Preview */}
      <div style={{ height }} className="relative">
        {!isPreview ? (
          <textarea
            ref={textareaRef}
            value={value}
            onChange={e => onChange(e.target.value)}
            placeholder={placeholder}
            disabled={disabled}
            className="w-full h-full p-3 bg-transparent resize-none focus:outline-none text-sm font-mono"
            style={{ minHeight: height }}
          />
        ) : (
          <div className="p-3 overflow-y-auto h-full">
            {value ? (
              <MarkdownViewer content={value} />
            ) : (
              <p className="text-muted-foreground text-sm">Nothing to preview</p>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
