"use client";

import { type Editor } from "@tiptap/react";
import {
    Bold,
    Italic,
    Strikethrough,
    Code,
    Heading1,
    Heading2,
    Heading3,
    List,
    ListOrdered,
    Quote,
    Undo,
    Redo,
    Minus,
    RemoveFormatting,
    AlignLeft,
    AlignCenter,
    AlignRight,
    CheckSquare,
    Link as LinkIcon,
    Image as ImageIcon,
    Table as TableIcon,
    Sparkles,
    FileDown,
    SquareCode,
    type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";

interface ToolbarProps {
    editor: Editor | null;
    onToggleAI?: () => void;
    onExport?: () => void;
}

type ToolbarItem = {
    icon?: LucideIcon;
    title?: string;
    action?: () => void;
    isActive?: boolean;
    disabled?: boolean;
    divider?: boolean;
};

export function Toolbar({ editor, onToggleAI, onExport }: ToolbarProps) {
    if (!editor) {
        return null;
    }

    const items: ToolbarItem[] = [
        { icon: Bold, title: "加粗", action: () => editor.chain().focus().toggleBold().run(), isActive: editor.isActive("bold") },
        { icon: Italic, title: "斜体", action: () => editor.chain().focus().toggleItalic().run(), isActive: editor.isActive("italic") },
        { icon: Strikethrough, title: "删除线", action: () => editor.chain().focus().toggleStrike().run(), isActive: editor.isActive("strike") },
        { icon: Code, title: "行内代码", action: () => editor.chain().focus().toggleCode().run(), isActive: editor.isActive("code") },
        { icon: SquareCode, title: "代码块", action: () => editor.chain().focus().toggleCodeBlock().run(), isActive: editor.isActive("codeBlock") },
        { divider: true },
        { icon: Heading1, title: "标题 1", action: () => editor.chain().focus().toggleHeading({ level: 1 }).run(), isActive: editor.isActive("heading", { level: 1 }) },
        { icon: Heading2, title: "标题 2", action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), isActive: editor.isActive("heading", { level: 2 }) },
        { icon: Heading3, title: "标题 3", action: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), isActive: editor.isActive("heading", { level: 3 }) },
        { divider: true },
        { icon: List, title: "无序列表", action: () => editor.chain().focus().toggleBulletList().run(), isActive: editor.isActive("bulletList") },
        { icon: ListOrdered, title: "有序列表", action: () => editor.chain().focus().toggleOrderedList().run(), isActive: editor.isActive("orderedList") },
        { icon: Quote, title: "引用", action: () => editor.chain().focus().toggleBlockquote().run(), isActive: editor.isActive("blockquote") },
        { divider: true },
        { icon: Minus, title: "分割线", action: () => editor.chain().focus().setHorizontalRule().run() },
        { icon: RemoveFormatting, title: "清除格式", action: () => editor.chain().focus().unsetAllMarks().clearNodes().run() },
        { divider: true },
        { icon: AlignLeft, title: "左对齐", action: () => editor.chain().focus().setTextAlign("left").run(), isActive: editor.isActive({ textAlign: "left" }) },
        { icon: AlignCenter, title: "居中", action: () => editor.chain().focus().setTextAlign("center").run(), isActive: editor.isActive({ textAlign: "center" }) },
        { icon: AlignRight, title: "右对齐", action: () => editor.chain().focus().setTextAlign("right").run(), isActive: editor.isActive({ textAlign: "right" }) },
        { divider: true },
        { icon: CheckSquare, title: "任务列表", action: () => editor.chain().focus().toggleTaskList().run(), isActive: editor.isActive("taskList") },
        {
            icon: LinkIcon,
            title: "链接",
            action: () => {
                const previousUrl = editor.getAttributes("link").href;
                const url = window.prompt("URL", previousUrl);
                if (url === null) return;
                if (url === "") {
                    editor.chain().focus().extendMarkRange("link").unsetLink().run();
                    return;
                }
                editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
            },
            isActive: editor.isActive("link"),
        },
        {
            icon: TableIcon,
            title: "插入表格",
            action: () => {
                editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();
            },
        },
        {
            icon: ImageIcon,
            title: "插入图片",
            action: () => {
                const url = window.prompt("Image URL");
                if (url) editor.chain().focus().setImage({ src: url }).run();
            },
        },
        { divider: true },
        { icon: Undo, title: "撤销", action: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo() },
        { icon: Redo, title: "重做", action: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo() },
        { divider: true },
        { icon: Sparkles, title: "AI 助手", action: () => onToggleAI?.() },
        { icon: FileDown, title: "导出 Markdown", action: () => onExport?.() },
    ];

    return (
        <div className="sticky top-0 z-20 -mx-1 mb-2 flex items-center gap-1 overflow-x-auto rounded-xl border border-border/60 bg-background/80 p-1 shadow-[0_1px_0_hsl(var(--border)/0.45),0_10px_20px_hsl(var(--background)/0.24)] backdrop-blur-md no-scrollbar supports-[backdrop-filter]:bg-background/68">
            {items.map((item, index) =>
                item.divider ? (
                    <div key={index} className="mx-1 h-6 w-px bg-border/80" />
                ) : (
                    <button
                        key={index}
                        onClick={item.action}
                        disabled={item.disabled}
                        className={cn(
                            "inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-transparent text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground md:h-9 md:w-9",
                            item.isActive && "border border-border/60 bg-accent text-accent-foreground shadow-sm",
                            item.disabled && "cursor-not-allowed opacity-50"
                        )}
                        title={item.title}
                    >
                        {item.icon && <item.icon size={16} />}
                    </button>
                )
            )}
        </div>
    );
}
