
import { memo } from 'react'
import { MenuItem } from '@/global'
import { Popconfirm, Space, TreeDataNode } from 'antd'
import { FormInstance } from 'antd/lib'
import { useTranslation } from '@/i18n.ts'
import { useStyle } from '../style.ts'
import { useAtomValue, useSetAtom } from 'jotai'
import { defaultMenu, deleteMenuAtom, selectedMenuAtom } from '@/store/menu.ts'
import { PlusOutlined } from '@ant-design/icons'
import ActionIcon, { DeleteAction } from '@/components/icon/action'

export const TreeNodeRender = memo(({ node, form }: { node: MenuItem & TreeDataNode, form: FormInstance }) => {
  const { title } = node
  const { t } = useTranslation()
  const { styles } = useStyle()
  const { mutate } = useAtomValue(deleteMenuAtom)

  const setMenuData = useSetAtom(selectedMenuAtom)

  return (
    <div className={styles.treeNode}>
      <span>{title as any}</span>
      <span className={'actions'}>
                    <Space size={'middle'}>
                        <ActionIcon
                          size={12}
                          icon={<PlusOutlined/>}
                          title={t('actions.add', '添加')}
                          onClick={(e) => {
                            // console.log('add')
                            e.stopPropagation()
                            e.preventDefault()
                            const menu = {
                              ...defaultMenu,
                              parent_id: node.id,
                            }
                            setMenuData(menu)
                            form.setFieldsValue(menu)

                          }}/>
                        <Popconfirm
                          title={t('message.deleteConfirm', '确定要删除吗？')}
                          onConfirm={() => {
                            mutate([ (node as any).id ])
                          }}
                        >
                          <DeleteAction
                            size={12}
                            onClick={(e) => {
                              e.stopPropagation()
                              e.stopPropagation()
                            }}/>
                        </Popconfirm>
                    </Space>
                </span>
    </div>
  )
})