import { DeleteOutlined, FormOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { ModalForm, ProFormText } from '@ant-design/pro-form'
import { useRequest } from '@umijs/max'
import type { ProFormInstance } from '@ant-design/pro-form'
import { Button, Input, message, Popconfirm, Tree } from 'antd'
import type { DirectoryTreeProps } from 'antd/lib/tree'
import { addDataSource, delDataSourceID, updateDataSourceItem } from '@/services/api/schema'
import { useRef, useState } from 'react'
import '@/pages/Permission/FrontRole/components/RoleLeftMenu/index.less'

const { DirectoryTree } = Tree

type LeftMenuProps = {
  onSelect: (key: string) => void
  defaultActiveID: string
  options: API.DataSourceMenuItem[]
  initFn: () => Promise<void>
}

const LeftMenu: React.FC<LeftMenuProps> = ({ onSelect, defaultActiveID, options, showDelIcon, initFn }) => {
  const [activeID, setActiveID] = useState<Nullable<string>>(null)
  const formRef = useRef<ProFormInstance>(null)
  const handleOnSelect: DirectoryTreeProps['onSelect'] = (keys, node) => {
    // console.log('Trigger Select', node)
    onSelect?.(keys[0], node)
  }
  const { run: tryUpdateDataSourceItem } = useRequest(
    (params: Partial<API.UpdateRoleParams>) => updateDataSourceItem(params),
    {
      manual: true,
      onSuccess: () => {
        message.success('修改成功')
        initFn()
      }
    }
  )
  const { run: tryAddDataSource } = useRequest((params: API.CreateRoleParams) => addDataSource(params), {
    manual: true,
    onSuccess: () => {
      initFn()
    }
  })
  const { run: tryDelRole } = useRequest((ID: string) => delDataSourceID({ ID }), {
    manual: true,
    onSuccess: () => {
      message.success('删除成功')
      initFn()
    }
  })

  const handleOnFocus = async (
    e: React.FocusEvent<HTMLInputElement> | React.KeyboardEvent<HTMLElement>,
    oldTitle: string,
    ID: string
  ) => {
    const val = e.currentTarget.value || e.currentTarget.nodeValue
    if (val !== oldTitle) {
      await tryUpdateDataSourceItem({ ID, name: val })
    }
    setActiveID(null)
  }

  const renderTreeNode = tree => {
    return tree.map((item: API.DataSourceMenuItem & { title: string; key: string }) => {
      const newItem = {
        ...item,
        title: (
          <div className="department-node py-1">
            {item.ID === activeID ? (
              <Input
                autoFocus
                defaultValue={item.name}
                bordered={false}
                size="small"
                style={{ width: '70%', backgroundColor: 'white' }}
                onBlur={e => handleOnFocus(e, item.name, item.ID)}
                onPressEnter={e => handleOnFocus(e, item.name, item.ID)}
              />
            ) : (
              <div className="title">{item.name}</div>
            )}
            <div className="extra">
              <FormOutlined className="pr-2" onClick={() => setActiveID(item.ID)} />
              {item.ID === defaultActiveID ? (
                <Popconfirm
                  disabled={!showDelIcon}
                  title="确认删除吗？"
                  onText="确认"
                  cancelText="取消"
                  onConfirm={() => tryDelRole(item.ID)}
                  icon={<QuestionCircleOutlined style={{ color: 'red' }} />}>
                  <DeleteOutlined
                    onClick={() => {
                      !showDelIcon && message.warning('该数据源已绑定子项，不允许删除')
                    }}
                  />
                </Popconfirm>
              ) : null}
            </div>
          </div>
        )
      }
      if (newItem.children?.length) {
        newItem.children = renderTreeNode(newItem.items)
      }
      return newItem
    })
  }
  const virtualHeigh = document.getElementById('role-list')?.clientHeight
  return (
    <div
      className="min-w-54 rounded-20px flex flex-col bg-white "
      style={{ height: 'calc(100vh - 122px)', background: '#ffffff' }}>
      <div className="menu-title flex items-center justify-around">
        <div className="py-4 text-base text-opacity-85">数据源列表</div>
        <ModalForm
          layout="horizontal"
          title="新增数据源"
          width="30%"
          formRef={formRef}
          onVisibleChange={visible => !visible && formRef.current?.resetFields()}
          isKeyPressSubmit
          labelCol={{ span: 5 }}
          trigger={
            <Button size="small" type="primary" ghost>
              <PlusOutlined />
              添加
            </Button>
          }
          onFinish={async values => {
            await tryAddDataSource(values)
            message.success('添加成功')
            return true
          }}>
          <ProFormText
            label="数据源名称"
            name="name"
            rules={[{ required: true, message: '请输入数据源名称' }]}
          />
          {/* <ProFormText label="URL" name="url" required disabled placeholder="自动生成" /> */}
        </ModalForm>
      </div>
      <div
        id="role-list"
        className="p-4 bg-white rounded-b-20px"
        style={{ height: 'calc(100% - 1rem*2 - 20px)' }}>
        {options.length ? (
          <DirectoryTree
            treeData={renderTreeNode(options.map(item => ({ title: item.name, key: item.ID, ...item })))}
            height={virtualHeigh - 32}
            defaultSelectedKeys={[options[0]?.ID]}
            onSelect={handleOnSelect}
            showIcon={false}
            defaultExpandAll
          />
        ) : null}
      </div>
    </div>
  )
}

export default LeftMenu
