import { FC, useEffect, useRef, useState } from "react";
import { Button } from "antd";
import { useNavigate } from "react-router-dom";
import {
  DageLoading,
  DageTreeActionData,
  DageTreeActions,
} from "@dage/pc-components";
import { PlusOutlined } from "@ant-design/icons";
import { deleteAssIndexApi, getAssIndexTreeApi } from "@/api";
import { AssIndexTreeItemType, ASS_INDEX_TYPE } from "@/types";
import style from "../../index.module.scss";
import { isNumber } from "lodash";

export interface SidebarProps {
  /**
   * 勾选模式
   */
  checkable?: boolean;
  type: ASS_INDEX_TYPE;
  currentId: null | number;
  setCurrentId: (id: number) => void;
}

export const Sidebar: FC<SidebarProps> = ({
  checkable,
  type,
  currentId,
  setCurrentId,
}) => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [treeData, setTreeData] = useState<AssIndexTreeItemType[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<number[]>([]);
  const lastCheckedItem = useRef<any>(null);

  const getAssIndexTree = async () => {
    try {
      setLoading(true);
      const data = await getAssIndexTreeApi(type);
      if (data.length) {
        data[0].disabled = true;
        setCurrentId(data[0].id);
        setCheckedKeys([data[0].id]);
        lastCheckedItem.current = data[0];
      }
      setTreeData(data);
    } finally {
      setLoading(false);
    }
  };

  const handleAddNode = (item: DageTreeActionData) => {
    navigate(`/assessment/index/create/${type}?parentId=${item.id}`);
  };

  const handleEditNode = (item: DageTreeActionData) => {
    navigate(`/assessment/index/edit/${type}/${item.id}`);
  };

  const handleDeleteNode = async (item: DageTreeActionData) => {
    await deleteAssIndexApi(item.id);
    getAssIndexTree();
  };

  useEffect(() => {
    getAssIndexTree();
  }, [type]);

  return (
    <div className={style.sidebar}>
      <div className={style.sidebarHeader}>
        <h4>指标列表</h4>

        {!checkable && (
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => navigate("/assessment/index/create/" + type)}
          >
            新增指标
          </Button>
        )}
      </div>

      {currentId && (
        <DageTreeActions
          defaultExpandAll
          treeData={treeData}
          selectedKeys={checkedKeys}
          onAdd={checkable ? undefined : handleAddNode}
          onEdit={handleEditNode}
          onDelete={handleDeleteNode}
          onSelect={(keys, { selectedNodes }) => {
            const checkedId = keys[keys.length - 1] as number;

            lastCheckedItem.current.disabled = false;
            selectedNodes[0].disabled = true;
            setCurrentId(checkedId);
            setCheckedKeys([checkedId]);
            lastCheckedItem.current = selectedNodes[0];
          }}
        />
      )}

      {loading && <DageLoading />}
    </div>
  );
};
