import { Box, IconButton, Typography, Radio } from "@mui/material"
import { Add, ExpandLess, Folder as FolderIcon } from "@mui/icons-material"
import { useState } from "react"
import type { FolderDTO } from "@/shared/types/document"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface Props {
  folder: FolderDTO
  selectedId: number | null
  onSelect: (folderId: number) => void
  currentFolderId: number
}

export default function FolderTreeNode({
  folder, selectedId, onSelect, currentFolderId,
}: Props) {
  const [expanded, setExpanded] = useState(false)

  const hasChildren = folder.subFolders && folder.subFolders.length > 0

  return (
    <Box sx={{ pl: 2, borderLeft: "1px dashed #ccc", mt: 1 }}>
      <Box sx={{ display: "flex", alignItems: "center" }}>
        <ConditionalComponent isValid={!!hasChildren} defaultComponent={<Box sx={{ width: 24 }} />}>
          <IconButton size="small" onClick={() => setExpanded(!expanded)}>
            {expanded ? <ExpandLess fontSize="small" /> : <Add fontSize="small" />}
          </IconButton>
        </ConditionalComponent>

        <FolderIcon sx={{ color: "primary.main", mr: 1 }} fontSize="small" />
        <Radio
          checked={selectedId === folder.id}
          onChange={() => onSelect(folder.id)}
          disabled={folder.id === currentFolderId}
        />
        <Typography variant="body2">{folder.name}</Typography>
      </Box>

      <ConditionalComponent isValid={expanded && !!hasChildren}>
        {folder.subFolders!.map((child) => (
          <FolderTreeNode
            key={child.id}
            folder={child}
            selectedId={selectedId}
            onSelect={onSelect}
            currentFolderId={currentFolderId}
          />
        ))}
      </ConditionalComponent>
    </Box>
  )
}
