"use client";

import { useRef, useCallback } from "react";
import { Bold, Italic, Heading1, Heading2, List, ListOrdered } from "lucide-react";

interface CanvasEditorProps {
  content: string;
  onChange: (content: string) => void;
  placeholder?: string;
}

export function CanvasEditor({ content, onChange, placeholder }: CanvasEditorProps) {
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const wrapSelection = useCallback(
    (before: string, after: string = before) => {
      const textarea = textareaRef.current;
      if (!textarea) return;
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const selectedText = content.substring(start, end);
      const newText = content.substring(0, start) + before + selectedText + after + content.substring(end);
      onChange(newText);
      // Restore selection after state update
      requestAnimationFrame(() => {
        textarea.focus();
        textarea.setSelectionRange(start + before.length, end + before.length);
      });
    },
    [content, onChange]
  );

  const insertLinePrefix = useCallback(
    (prefix: string) => {
      const textarea = textareaRef.current;
      if (!textarea) return;
      const start = textarea.selectionStart;
      const lineStart = content.lastIndexOf("\n", start - 1) + 1;
      const newText = content.substring(0, lineStart) + prefix + content.substring(lineStart);
      onChange(newText);
      requestAnimationFrame(() => {
        textarea.focus();
        textarea.setSelectionRange(start + prefix.length, start + prefix.length);
      });
    },
    [content, onChange]
  );

  const toolbarButtons = [
    { icon: Bold, label: "Bold", action: () => wrapSelection("**") },
    { icon: Italic, label: "Italic", action: () => wrapSelection("_") },
    { icon: Heading1, label: "Heading 1", action: () => insertLinePrefix("# ") },
    { icon: Heading2, label: "Heading 2", action: () => insertLinePrefix("## ") },
    { icon: List, label: "Bullet list", action: () => insertLinePrefix("- ") },
    { icon: ListOrdered, label: "Numbered list", action: () => insertLinePrefix("1. ") },
  ];

  return (
    <div className="flex flex-col h-full border border-gray-200 rounded-lg overflow-hidden">
      {/* Toolbar */}
      <div className="flex items-center gap-1 px-2 py-1.5 border-b border-gray-200 bg-gray-50">
        {toolbarButtons.map((btn) => {
          const Icon = btn.icon;
          return (
            <button
              key={btn.label}
              onClick={btn.action}
              title={btn.label}
              className="p-1.5 rounded text-gray-500 hover:text-gray-700 hover:bg-gray-200 transition-colors"
            >
              <Icon size={16} />
            </button>
          );
        })}
      </div>

      {/* Textarea */}
      <textarea
        ref={textareaRef}
        value={content}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder || "Start writing..."}
        className="flex-1 resize-none px-4 py-3 focus:outline-none text-sm text-gray-800 font-mono"
      />
    </div>
  );
}