import {useState} from "react";
import type {MenuTreeItem} from "../type/authorRoleMenu.types.ts";

type TreeItemProps = {
    node: MenuTreeItem;
    isChecked: (menuNo: MenuTreeItem["menuNo"]) => boolean;
    onCheck: (menuNo: MenuTreeItem["menuNo"], checked: boolean) => void;
};

export const AuthorRoleMenuTreeItem = ({
                                           node,
                                           isChecked,
                                           onCheck,
                                       }: TreeItemProps) => {

    const [open, setOpen] = useState(true);

    const hasChildren =
        node.children.length > 0;

    return (
        <div className={`tree-node ${hasChildren ? 'folder' : 'file'}`}>

            <label className={"tree-label"}>

                {hasChildren && (
                    <button
                        type={"button"}
                        onClick={() => setOpen(prev => !prev)}
                    >
                        {open ? "-" : "+"}
                    </button>
                )}

                <input
                    type={"checkbox"}
                    checked={isChecked(node.menuNo)}
                    onChange={(event) => onCheck(node.menuNo, event.target.checked)}
                />

                <span>
                    {node.menuNm}
                </span>
            </label>

            {open && hasChildren && (
                <div className={"tree-children"}>
                    {node.children.map((child) => (
                        <AuthorRoleMenuTreeItem
                            key={child.menuNo}
                            node={child}
                            isChecked={isChecked}
                            onCheck={onCheck}
                        />
                    ))}
                </div>
            )}
        </div>
    );
};
