"use client"

import { useState } from "react"
import {
  Box,
  Combobox,
  Input,
  ScrollArea,
  Text,
  TreeNodeData,
  useCombobox,
} from "@mantine/core"

const TreeSelect = ({ treeData }: { treeData: TreeNodeData[] }) => {
  const combobox = useCombobox()
  const [value, setValue] = useState("")

  const renderTreeNodes = (nodes: TreeNodeData[]) =>
    nodes.map((node) => (
      <Box key={node.value}>
        {/* 这里的点击事件需要自己处理，例如展开子节点，更新输入框值 */}
        <Box
          onClick={() => {
            setValue(node.label as string)
            // combobox.closeDropdown()
          }}
          style={{
            padding: "8px",
            cursor: "pointer",
            "&:hover": { backgroundColor: "#f0f0f0" },
          }}>
          <Text>{node.label}</Text>
        </Box>
        {node.children && <Box ml="md">{renderTreeNodes(node.children)}</Box>}
      </Box>
    ))

  return (
    <Combobox
      store={combobox}
      onOptionSubmit={(val) => setValue(val)}
      withinPortal={false}>
      <Combobox.Target>
        <Input
          component="button"
          pointer
          rightSection={<Combobox.Chevron />}
          onClick={() => combobox.openDropdown()}
          style={{ width: 250 }}>
          {value || "请选择..."}
        </Input>
      </Combobox.Target>
      <Combobox.Dropdown>
        <Combobox.Options>
          <ScrollArea.Autosize mah={200} type="always">
            {renderTreeNodes(treeData)}
          </ScrollArea.Autosize>
        </Combobox.Options>
      </Combobox.Dropdown>
    </Combobox>
  )
}

export default TreeSelect
