import PermissionGuard from "../../PermissionGuard";
import PathNode from "../PathNode";
import React from "react";
import { Link } from "react-router-dom";
import { Search, FilePlus2 } from "lucide-react";
import { useTree } from "../../../utils/queries/tree-queries";
import { useDeletePath, useUpdatePath } from "../../../utils/queries/path-queries";
import { Input } from "../../ui/input";
import { Button } from "../../ui/button";
import { Spinner } from "../../ui/misc";

const TreeTab = () => {
    const { data: tree, isLoading, error } = useTree();
    const deletePath = useDeletePath();
    const updatePath = useUpdatePath();
    const [keyword, setKeyword] = React.useState("");

    const handleDelete = (id) => {
        if (window.confirm("Are you sure you want to delete this path?")) {
            deletePath.mutate(id, {
                onError: () => alert("Failed to delete path"),
            });
        }
    };

    const filterTree = (t, k) => {
        if (t === undefined) return undefined;
        if (t.type === "path") {
            if (t.name.includes(k)) return { ...t };
            const filteredChildren = (t.children || [])
                .map(c => filterTree(c, k))
                .filter(Boolean);
            if (filteredChildren.length > 0) {
                return { ...t, children: filteredChildren };
            }
        } else if (t.type === "markdown") {
            if (t.title.includes(k)) return { ...t };
        }
        return undefined;
    };

    const filteredTree = filterTree(tree, keyword);

    const handleSave = (id, newName) => {
        updatePath.mutate({ id, data: { name: newName } }, {
            onError: () => alert("Failed to update path"),
        });
    };

    if (isLoading) return <Spinner label="Loading tree" />;
    if (error)
        return (
            <p className="font-mono text-xs text-destructive">
                Error loading tree
            </p>
        );

    return (
        <div className="space-y-3">
            <div className="relative">
                <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
                <Input
                    className="h-8 pl-8 text-xs"
                    type="text"
                    placeholder="Search…"
                    onChange={(e) => setKeyword(e.target.value)}
                />
            </div>

            <PermissionGuard rolesRequired={["admin", "creator"]}>
                <Button
                    asChild
                    size="sm"
                    variant="outline"
                    className="w-full"
                >
                    <Link to="/markdown/create">
                        <FilePlus2 className="h-4 w-4" /> New Markdown
                    </Link>
                </Button>
            </PermissionGuard>

            {!filteredTree || filteredTree.length === 0 ? (
                <p className="px-1 py-6 text-center font-mono text-xs text-muted-foreground">
                    No result
                </p>
            ) : (
                <PathNode
                    key={1}
                    path={filteredTree}
                    isRoot={true}
                    onSave={handleSave}
                    onDelete={handleDelete}
                />
            )}
        </div>
    );
};

export default TreeTab;
