"use client"

import TreeSelect from "@/components/tree-select"
import { getCityTree } from "@/components/tree-select/api"
import { TreeNode } from "@/components/tree-select/api/type"
import { VirtualTreeSelect } from "@/components/tree-select/tree"
import {
  Breadcrumbs,
  Flex,
  Paper,
  Stack,
  TreeNodeData,
  UnstyledButton,
} from "@mantine/core"
import { useCallback, useEffect, useState } from "react"

const convertTreeNodeToTreeNodeData = (
  list: TreeNode[],
  level: number = 1
): TreeNodeData[] =>
  list.map((g) => ({
    label: g.label,
    value: g.value,
    nodeProps: { level: level },
    children:
      g.children && g.children.length
        ? convertTreeNodeToTreeNodeData(g.children, level + 1)
        : [],
  }))

export default function ComponentBaseSelectPage() {
  const items = [{ title: "选择组件" }].map((item) => (
    <UnstyledButton key={item.title}>{item.title}</UnstyledButton>
  ))

  const [value, setValue] = useState<string>("")

  const [treeData, setTreeData] = useState<TreeNodeData[]>([])
  const asyncGetCityTree = useCallback(async () => {
    const res = await getCityTree()
    setTreeData(convertTreeNodeToTreeNodeData(res))
  }, [])

  useEffect(() => {
    queueMicrotask(() => asyncGetCityTree())
  }, [asyncGetCityTree])

  return (
    <>
      <Stack w="100%" h="calc(100vh - 56px)" p="md">
        <Breadcrumbs>{items}</Breadcrumbs>
        <Paper shadow="xs" p={"md"} flex={1} display="flex">
          <Flex h={"fit-content"} gap={"lg"}>
            <TreeSelect treeData={treeData} />

            <VirtualTreeSelect
              data={treeData}
              value={value}
              onChange={setValue}
              setCurrCityCode={() => {}}
              w={"200px"}
            />
          </Flex>
          <Flex>{value}</Flex>
        </Paper>
      </Stack>
    </>
  )
}
