import PermissionGuard from "../PermissionGuard";
import PathNode from "./PathNode";
import "./SideNavigation.css";
import {useDeletePath, usePaths, useUpdatePath} from "../../utils/path-queries";
import React from 'react';

const SideNavigation = () => {
    const {data: paths, isLoading, error } = usePaths(1);
    const deletePath = useDeletePath();
    const updatePath = useUpdatePath();

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

    const handleSave = (id, newName) => {
        updatePath.mutate({ id, data: {name: newName }} , {
            onError: (err) => {
                alert("Failed to update path");
            }
        });
    };
    if(isLoading){
        return <aside className="menu"><p>Loading...</p></aside>;
    }

    if(error){
        return <aside className="menu"><p>Error...</p></aside>;
    }

    return (
        <aside className="menu">
            <p className="menu-label">Markdown Directory</p>
            <PermissionGuard rolesRequired={["admin", "creator"]}>
                <a
                    href="/markdown/create"
                    className="button is-primary is-small"
                >
                    Create New Markdown
                </a>
            </PermissionGuard>
            <ul className="menu-list">
                {isLoading && <p>Loading...</p>}
                {paths.map((path) => (
                    <PathNode
                        key={path.id}
                        path={path}
                        isRoot={false}
                        onSave={handleSave}
                        onDelete={handleDelete}
                    />
                ))}
            </ul>
        </aside>
    );
};

export default SideNavigation;
