import { useState } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Collapse from '@mui/material/Collapse';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import CheckIcon from '@mui/icons-material/Check';
import FolderIcon from '@mui/icons-material/Folder';
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
import Box from '@mui/material/Box';
import { getCategoryChildren, categoryDisplayName } from '../../store/categorySlice';
function CategoryNode({
categories,
categoryId,
rootCategoryId,
selectedId,
onSelect,
expandedIds,
onToggleExpand,
depth = 0,
}) {
const node = categories[String(categoryId)];
if (!node) return null;
const children = getCategoryChildren(categories, categoryId);
const hasChildren = children.length > 0;
const isSelected = selectedId != null && String(selectedId) === String(categoryId);
const isExpanded = expandedIds.has(categoryId);
const label = categoryDisplayName(node.name, node.id, rootCategoryId);
return (
<>
onSelect(categoryId)}
sx={{ pl: 1 + depth * 1.5 }}
>
{hasChildren ? (
isExpanded ? :
) : null}
{isSelected && }
{hasChildren && (
isExpanded ? (
{ e.stopPropagation(); onToggleExpand(categoryId, false); }} />
) : (
{ e.stopPropagation(); onToggleExpand(categoryId, true); }} />
)
)}
{hasChildren && (
{children.map((child) => (
))}
)}
>
);
}
function buildDefaultExpanded(categories, rootCategoryId, currentCategoryIds) {
const ids = new Set();
if (!categories || !rootCategoryId) return ids;
for (const catId of currentCategoryIds ?? []) {
let id = catId;
while (id != null) {
const node = categories[String(id)];
if (!node) break;
ids.add(id);
if (node.parentId == null || node.parentId === 0) break;
id = node.parentId;
}
}
return ids;
}
export default function CategoryPickerDialog({
open,
onClose,
categories,
rootCategoryId,
currentCategoryIds,
onSelect,
}) {
const [selectedId, setSelectedId] = useState(null);
const [expandedIds, setExpandedIds] = useState(
() => buildDefaultExpanded(categories, rootCategoryId, currentCategoryIds),
);
const handleToggleExpand = (id, expand) => {
setExpandedIds((prev) => {
const next = new Set(prev);
if (expand) next.add(id);
else next.delete(id);
return next;
});
};
const handleConfirm = () => {
if (selectedId == null) return;
const categoryIds = currentCategoryIds.filter((id) => String(id) !== String(selectedId));
categoryIds.push(selectedId);
onSelect?.(categoryIds);
onClose();
};
return (
);
}