
"use client";

import { useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Bold, Italic, Strikethrough, Underline } from "lucide-react";
import { MDXEditor } from "@mdxeditor/editor"; // Assuming react-mdx-editor or similar
import DOMPurify from "isomorphic-dompurify";

export default function NewBlog() {
  const [text, setText] = useState("");
  const [cursor, setCursor] = useState<{ line: number; column: number }>({
    line: 0,
    column: 0,
  });

  // Function to update the cursor position
  const getCursorPosition = (newText: string) => {
    const cursorPos = newText.length;
    const lines = newText.substring(0, cursorPos).split("\n");
    const line = lines.length; // Current line number
    const column = lines[lines.length - 1].length + 1; // Current column number

    setCursor({ line, column });
  };

  const execCommand = (command: string) => {
    const pre = text.slice(0, cursor.column);
    const post = text.slice(cursor.column);

    setText(pre + command + post);
    getCursorPosition(pre + command + post); // Update cursor position after change
  };

  // Sanitize the MDX text before rendering
  const sanitized = DOMPurify.sanitize(text);

  return (
    <section className="flex m-5">
      <div className="flex-1">
        <div className="flex gap-2 mb-2 border-b pb-2">
          <Button variant="outline" size="icon" onClick={() => execCommand("**")}>
            <Bold size={16} />
          </Button>
          <Button variant="outline" size="icon" onClick={() => execCommand("*")}>
            <Italic size={16} />
          </Button>
          <Button variant="outline" size="icon" onClick={() => execCommand("__")}>
            <Underline size={16} />
          </Button>
          <Button variant="outline" size="icon" onClick={() => execCommand("~~")}>
            <Strikethrough size={16} />
          </Button>
        </div>
        
        {/* Using MDXEditor instead of a basic Textarea */}
        <MDXEditor
          onChange={setText}
          onBlur={() => getCursorPosition(text)}
		  markdown="ok"
        />
        
        <div>
          Line: {cursor.line}; Column: {cursor.column}
        </div>
      </div>
      
      <div
        className="mt-4 p-2 bg-gray-100 border rounded-md text-sm text-black"
        dangerouslySetInnerHTML={{
          __html: sanitized,
        }}
      />
    </section>
  );
}

