import {
  AlignCenter,
  AlignLeft,
  AlignRight,
  Bold,
  Code,
  FileImage,
  FileVideo,
  Grid2x2Plus,
  Grid2x2X,
  Heading1,
  Heading2,
  Heading3,
  Highlighter,
  Italic,
  Link2,
  List,
  ListOrdered,
  Minus,
  Redo,
  Strikethrough,
  Table,
  Trash2,
  Undo,
} from "lucide-react";
import { Toggle } from "@/app/components/admin/toggle";
import { Editor } from "@tiptap/react";
import { Tooltip } from "@/app/components/admin/tooltip"; // Adjust path based on your structure

export default function MenuBar({ editor }: { editor: Editor | null }) {
  if (!editor) {
    return null;
  }

  const Options = [
    // Heading and Text Formatting Group
    {
      icon: <Heading1 className="size-4" />,
      title: "Heading 1",
      onClick: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
      preesed: editor.isActive("heading", { level: 1 }),
    },
    {
      icon: <Heading2 className="size-4" />,
      title: "Heading 2",
      onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
      preesed: editor.isActive("heading", { level: 2 }),
    },
    {
      icon: <Heading3 className="size-4" />,
      title: "Heading 3",
      onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
      preesed: editor.isActive("heading", { level: 3 }),
    },
    { type: "separator" }, // Adds a divider between groups
    {
      icon: <Bold className="size-4" />,
      title: "Bold",
      onClick: () => editor.chain().focus().toggleBold().run(),
      preesed: editor.isActive("bold"),
    },
    {
      icon: <Italic className="size-4" />,
      title: "Italic",
      onClick: () => editor.chain().focus().toggleItalic().run(),
      preesed: editor.isActive("italic"),
    },
    {
      icon: <Strikethrough className="size-4" />,
      title: "Strikethrough",
      onClick: () => editor.chain().focus().toggleStrike().run(),
      preesed: editor.isActive("strike"),
    },
    { type: "separator" },
  
    // Text Alignment Group
    {
      icon: <AlignLeft className="size-4" />,
      title: "Align Left",
      onClick: () => editor.chain().focus().setTextAlign("left").run(),
      preesed: editor.isActive({ textAlign: "left" }),
    },
    {
      icon: <AlignCenter className="size-4" />,
      title: "Align Center",
      onClick: () => editor.chain().focus().setTextAlign("center").run(),
      preesed: editor.isActive({ textAlign: "center" }),
    },
    {
      icon: <AlignRight className="size-4" />,
      title: "Align Right",
      onClick: () => editor.chain().focus().setTextAlign("right").run(),
      preesed: editor.isActive({ textAlign: "right" }),
    },
    { type: "separator" },
  
    // List Formatting Group
    {
      icon: <List className="size-4" />,
      title: "Bullet List",
      onClick: () => editor.chain().focus().toggleBulletList().run(),
      preesed: editor.isActive("bulletList"),
    },
    {
      icon: <ListOrdered className="size-4" />,
      title: "Ordered List",
      onClick: () => editor.chain().focus().toggleOrderedList().run(),
      preesed: editor.isActive("orderedList"),
    },
    { type: "separator" },

    {
      icon: <Highlighter className="size-4" />,
      title: "Highlight",
      onClick: () => editor.chain().focus().toggleHighlight().run(),
      preesed: editor.isActive("highlight"),
    },
  
    { type: "separator" },
    // Table Group
    {
      icon: <Table className="size-4" />,
      title: "Insert Table",
      onClick: () => {
        const rows = parseInt(prompt("Enter number of rows:", "3") || "3", 10);
        const cols = parseInt(prompt("Enter number of columns:", "3") || "3", 10);
  
        if (isNaN(rows) || isNaN(cols) || rows < 1 || cols < 1) {
          alert("Please enter valid numbers for rows and columns.");
          return;
        }
  
        editor.chain().focus().insertTable({ rows, cols, withHeaderRow: true }).run();
      },
      preesed: editor.isActive("table"),
    },
    {
      icon: <Grid2x2Plus className="size-4" />,
      title: "Add Row",
      onClick: () => editor.chain().focus().addRowAfter().run(),
      preesed: false,
    },
    {
      icon: <Grid2x2X className="size-4" />,
      title: "Remove Row",
      onClick: () => editor.chain().focus().deleteRow().run(),
      preesed: false,
    },
    {
      icon: <Grid2x2Plus  className="size-4" />, // Rotated to differentiate from row
      title: "Add Column",
      onClick: () => editor.chain().focus().addColumnAfter().run(),
      preesed: false,
    },
    {
      icon: <Grid2x2X className="size-4" />, // Rotated to differentiate from row
      title: "Remove Column",
      onClick: () => editor.chain().focus().deleteColumn().run(),
      preesed: false,
    },
    {
      icon: <Trash2 className="size-4 text-red-500" />,
      title: "Delete Table",
      onClick: () => editor.chain().focus().deleteTable().run(),
      preesed: false,
    },
    { type: "separator" },
    {
      icon: <FileImage className="size-4" />,
      title: "Insert Image",
      onClick: () => {
        const url = window.prompt("Enter Image URL");
        const altText = window.prompt("Enter Image Alt Text", "Image");
  
        if (url && altText) {
          editor.chain().focus().setImage({ src: url, alt: altText }).run();
        }
      },
      preesed: false,
    },
    {
      icon: <FileVideo className="size-4" />,
      title: "Insert Video",
      onClick: () => {
        const url = window.prompt("Enter Video URL");
  
        if (url) {
          editor.chain().focus().setYoutubeVideo({ src: url, width: 640, height: 480 }).run();
        }
      },
      preesed: false,
    },
    { type: "separator" },
    {
      icon: <Undo className="size-4" />,
      title: "Undo",
      onClick: () => editor.chain().focus().undo().run(),
      preesed: false,
    },
    {
      icon: <Redo className="size-4" />,
      title: "Redo",
      onClick: () => editor.chain().focus().redo().run(),
      preesed: false,
    },
    { type: "separator" },
    {
      icon: <Link2 className="size-4" />,
      title: "Insert Link",
      onClick: () => {
        const previousUrl = editor.getAttributes('link').href
        const url = window.prompt('URL', previousUrl)
    
        // cancelled
        if (url === null) {
          return
        }
    
        // empty
        if (url === '') {
          editor.chain().focus().extendMarkRange('link').unsetLink()
            .run()
    
          return
        }
  
          editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
      },
      preesed: editor.isActive("link"),
    },
    {
      icon: <Minus className="size-4" />,
      title: "Horizontal Line",
      onClick: () => editor.chain().focus().setHorizontalRule().run(),
      preesed: false,
    },
    {
      icon: <Code className="size-4" />,
      title: "View Source Code",
      onClick: () => {
        const sourceCode = editor.getHTML(); // Get current HTML
    
        // Create modal container
        const modal = document.createElement("div");
        modal.style.position = "fixed";
        modal.style.top = "50%";
        modal.style.left = "50%";
        modal.style.transform = "translate(-50%, -50%)";
        modal.style.background = "white";
        modal.style.padding = "20px";
        modal.style.borderRadius = "10px";
        modal.style.border = "1px solid #ccc";
        modal.style.boxShadow = "0px 4px 20px rgba(0, 0, 0, 0.2)";
        modal.style.zIndex = "9999";
        modal.style.width = "500px"; // Adjust modal width
        modal.style.maxWidth = "90vw";
    
        // Create heading
        const heading = document.createElement("h3");
        heading.innerText = "Source Code";
        heading.style.fontSize = "18px";
        heading.style.marginBottom = "10px";
        heading.style.textAlign = "center";
        heading.style.fontWeight = "bold";
    
        // Create textarea
        const textarea = document.createElement("textarea");
        textarea.value = sourceCode;
        textarea.style.width = "100%";
        textarea.style.height = "250px";
        textarea.style.padding = "10px";
        textarea.style.border = "1px solid #ccc";
        textarea.style.borderRadius = "6px";
        textarea.style.background = "#f9f9f9";
        textarea.style.fontFamily = "monospace";
        textarea.style.fontSize = "14px";
        textarea.style.resize = "none";
    
        // Create copy button
        const copyButton = document.createElement("button");
        copyButton.innerText = "Copy to Clipboard";
        copyButton.style.marginTop = "10px";
        copyButton.style.padding = "8px 12px";
        copyButton.style.border = "none";
        copyButton.style.background = "#4CAF50";
        copyButton.style.color = "white";
        copyButton.style.borderRadius = "6px";
        copyButton.style.cursor = "pointer";
        copyButton.style.fontSize = "14px";
        copyButton.style.fontWeight = "bold";
        copyButton.style.width = "100%";
        
        copyButton.onclick = () => {
          navigator.clipboard.writeText(textarea.value);
          copyButton.innerText = "Copied!";
          setTimeout(() => (copyButton.innerText = "Copy to Clipboard"), 2000);
        };
    
        // Create update button
        const updateButton = document.createElement("button");
        updateButton.innerText = "Update Content";
        updateButton.style.marginTop = "10px";
        updateButton.style.padding = "8px 12px";
        updateButton.style.border = "none";
        updateButton.style.background = "#2196F3";
        updateButton.style.color = "white";
        updateButton.style.borderRadius = "6px";
        updateButton.style.cursor = "pointer";
        updateButton.style.fontSize = "14px";
        updateButton.style.fontWeight = "bold";
        updateButton.style.width = "100%";
    
        updateButton.onclick = () => {
          editor.chain().focus().setContent(textarea.value).run();
          document.body.removeChild(modal); // Close modal after updating
        };
    
        // Create close button
        const closeButton = document.createElement("button");
        closeButton.innerText = "Close";
        closeButton.style.marginTop = "10px";
        closeButton.style.padding = "8px 12px";
        closeButton.style.border = "none";
        closeButton.style.background = "#f44336";
        closeButton.style.color = "white";
        closeButton.style.borderRadius = "6px";
        closeButton.style.cursor = "pointer";
        closeButton.style.fontSize = "14px";
        closeButton.style.fontWeight = "bold";
        closeButton.style.width = "100%";
    
        closeButton.onclick = () => {
          document.body.removeChild(modal);
        };
    
        // Append elements to modal
        modal.appendChild(heading);
        modal.appendChild(textarea);
        modal.appendChild(copyButton);
        modal.appendChild(updateButton); // Append Update Content button
        modal.appendChild(closeButton);
    
        // Add modal to body
        document.body.appendChild(modal);
      },
      preesed: false,
    },

  ];

  return (
    <div className="border rounded-md p-2 mb-1 bg-slate-50 flex flex-wrap items-center space-x-2 z-50">
      {Options.map((option, index) =>
        option.type === "separator" ? (
          <span key={index} className="w-px h-6 bg-gray-300 mx-2"></span>
        ) : (
          <Tooltip key={index} content={option.title} side="top">
            <Toggle 
              className="w-9 h-10 flex items-center justify-center" 
              pressed={option.preesed} 
              onPressedChange={option.onClick}
            >
              {option.icon}
            </Toggle>
          </Tooltip>
        )
      )}
    </div>
  );
}