/**
 * Datart
 *
 * Copyright 2021
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  EditOutlined,
  MoreOutlined,
} from '@ant-design/icons';
import { Menu, message, Popconfirm, TreeDataNode } from 'antd';
import { MenuListItem, Popup, Tree, TreeTitle } from 'app/components';
import useI18NPrefix from 'app/hooks/useI18NPrefix';
import {
  selectIsOrgOwner,
  selectOrgId,
  selectPermissionMap,
} from 'app/pages/MainPage/slice/selectors';
import { CommonFormTypes } from 'globalConstants';
import { memo, useCallback, useContext, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router';
import { onDropTreeFn, stopPPG, uuidv4 } from 'utils/utils';
import { CascadeAccess, getCascadeAccess } from '../../../Access';
import {
  PermissionLevels,
  ResourceTypes,
} from '../../PermissionPage/constants';
import { SaveFormContext } from '../SaveFormContext';
import {
  selectDepartmentsListLoading,
} from '../slice/selectors';
import {  getDepartments } from '../slice/thunks';

interface DepartmentListProps {
  departmentId?: string;
  list?: TreeDataNode[];
}

export const DepartmentList = memo(({ departmentId, list }:DepartmentListProps) => {
  const dispatch = useDispatch();
  const history = useHistory();
  const orgId = useSelector(selectOrgId);
  const deptId = departmentId || '0';
  const loading = useSelector(selectDepartmentsListLoading);
  const t = useI18NPrefix('department');
  const tg = useI18NPrefix('global');
  const { showSaveForm } = useContext(SaveFormContext);
  const isOwner = useSelector(selectIsOrgOwner);
  const permissionMap = useSelector(selectPermissionMap);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  
  useEffect(() => {
    dispatch(getDepartments(deptId));
  }, [dispatch, orgId]);

  const toDetails = useCallback(
    id => () => {
      history.push(`/organizations/${orgId}/departments/${id}`);
    },
    [history, orgId],
  );

  const moreMenuClick = useCallback(
    ({ id, name, parentId, index }) =>
      ({ key, domEvent }) => {
        domEvent.stopPropagation();
        switch (key) {
          case 'info':
            showSaveForm({
              sourceType: 'folder',
              type: CommonFormTypes.Edit,
              visible: true,
              simple: false,
              initialValues: {
                id,
                name,
                parentId,
              },
              parentIdLabel: t('sidebar.parent'),
              onSave: (values, onClose) => {
              },
            });
            break;
          case 'addNewView':
            break;
          case 'delete':
            break;
          default:
            break;
        }
      },
    [dispatch, history, orgId, showSaveForm, t, toDetails],
  );

  const renderTreeTitle = useCallback(
    node => {
      const { title, path, isFolder, id, type } = node;
      const isAuthorized = getCascadeAccess(
        isOwner,
        permissionMap,
        ResourceTypes.Department,
        path,
        PermissionLevels.Manage,
      );
      return (
        <TreeTitle>
          <h4>{title}</h4>
          <CascadeAccess
            module={ResourceTypes.Department}
            path={path}
            level={PermissionLevels.Manage}
          >
            <Popup
              trigger={['click']}
              placement="bottom"
              content={
                <Menu
                  prefixCls="ant-dropdown-menu"
                  selectable={false}
                  onClick={moreMenuClick(node)}
                >
                  {isAuthorized && (
                    <MenuListItem
                      key="info"
                      prefix={<EditOutlined className="icon" />}
                    >
                      {tg('button.info')}
                    </MenuListItem>
                  )}

                  {isAuthorized && type !== 'FOLDER' && (
                    <MenuListItem
                      key="addNewView"
                      prefix={<EditOutlined className="icon" />}
                    >
                      {t('creatView')}
                    </MenuListItem>
                  )}

                </Menu>
              }
            >
              <span className="action" onClick={stopPPG}>
                <MoreOutlined />
              </span>
            </Popup>
          </CascadeAccess>
        </TreeTitle>
      );
    },
    [isOwner, permissionMap, moreMenuClick, tg, t],
  );

  const onDrop = info => {
    onDropTreeFn({
      info,
      treeData: list,
      callback: (id, parentId, index) => {
      },
    });
  };

  const menuSelect = useCallback(
    (_, { node }) => {
      if (node.type === 'FOLDER') {
        if (expandedKeys?.includes(node.key)) {
          setExpandedKeys(expandedKeys.filter(k => k !== node.key));
        } else {
          setExpandedKeys([node.key].concat(expandedKeys));
        }
      } else {
        history.push(`/organizations/${orgId}/departments/${node.id}`);
      }
    },
    [expandedKeys, history, orgId],
  );

  const handleExpandTreeNode = expandedKeys => {
    setExpandedKeys(expandedKeys);
  };

  return (
    <Tree
      loading={loading}
      treeData={list}
      titleRender={renderTreeTitle}
      onSelect={menuSelect}
      onDrop={onDrop}
      expandedKeys={expandedKeys}
      onExpand={handleExpandTreeNode}
      {...(departmentId && { selectedKeys: [departmentId] })}
      draggable
    />
  );
});
