/**
 * 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 {
  FolderOpenFilled,
  FolderFilled,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from '@ant-design/icons';
import { message } from 'antd';
import { ListNav, ListPane, ListTitle } from 'app/components';
import { useDebouncedSearch } from 'app/hooks/useDebouncedSearch';
import useI18NPrefix from 'app/hooks/useI18NPrefix';
import { selectOrgId } from 'app/pages/MainPage/slice/selectors';
import { dispatchResize } from 'app/utils/dispatchResize';
import { ReactElement, memo, useCallback, useContext, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouteMatch } from 'react-router';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components/macro';
import { LEVEL_5, SPACE_TIMES, SPACE_XS } from 'styles/StyleConstants';
import { SaveFormContext } from '../SaveFormContext';
import { CommonFormTypes } from 'globalConstants';
import {
  makeSelectDepartmentTree,
  selectDepartments,
} from '../slice/selectors';
import { DepartmentSimpleViewModel } from '../slice/types';
import { DepartmentList } from './DepartmentList';

interface SidebarProps {
  isDragging: boolean;
  width: number;
  sliderVisible: boolean;
  handleSliderVisible: (status: boolean) => void;
}

export const Sidebar = memo(
  ({ width, isDragging, sliderVisible, handleSliderVisible }: SidebarProps) => {
    const dispatch = useDispatch();
    const history = useHistory();
    const orgId = useSelector(selectOrgId);
    const departmentData = useSelector(selectDepartments);
    const { showSaveForm } = useContext(SaveFormContext);
    const matchDepartmentDetail = useRouteMatch<{ departmentId: string }>(
      '/organizations/:orgId/departments/:departmentId',
    );
    const departmentId = matchDepartmentDetail?.params.departmentId;
    const t = useI18NPrefix('department');
    const selectDepartmentTree = useMemo(makeSelectDepartmentTree, []);

    
    const getIcon = useCallback(({ isFolder }: DepartmentSimpleViewModel) => {
        if (isFolder)
          return p => (p.expanded ? <FolderOpenFilled /> : <FolderFilled />);
        return () => <FolderFilled />;
      }, []);

    const getDisabled = useCallback(({ isFolder }: DepartmentSimpleViewModel) => {
      return false;
    }, []);

    const treeData = useSelector(state =>
      selectDepartmentTree(state, { getIcon, getDisabled }),
    );

    const { filteredData: departmentList, debouncedSearch: listSearch } =
      useDebouncedSearch(treeData, (keywords, d) =>
        d.title.toLowerCase().includes(keywords.toLowerCase()),
      );

      const toAdd = useCallback(
        ({ key }) => {
          switch (key) {
            case 'add':
              history.push(`/organizations/${orgId}/departments/add`);
              break;
            case 'folder':
              showSaveForm({
                sourceType: 'folder',
                type: CommonFormTypes.Add,
                visible: true,
                simple: false,
                parentIdLabel: t('sidebar.parent'),
                onSave: (values, onClose) => {
                  console.log(values);
                },
              });
              break;
            default:
              break;
          }
        },
        [dispatch, history, orgId, showSaveForm, departmentData, t],
      );

    const moreMenuClick = useCallback(
      (key, _, onNext) => {
        switch (key) {
          case 'recycle':
            onNext();
            break;
          case 'collapse':
            handleSliderVisible(!sliderVisible);
            dispatchResize();
            break;
        }
      },
      [handleSliderVisible, sliderVisible],
    );

    const titles = useMemo(
      () => [
        {
          key: 'list',
          title: t('sidebar.title'),
          search: true,
          onSearch: listSearch,
          add: {
            items: [
              { key: 'add', text: t('sidebar.add') },
              // { key: 'folder', text: t('sidebar.addFolder') },
            ],
            callback: ()=>{},
          },
          more: {
            items: [
              {
                key: 'collapse',
                text: t(sliderVisible ? 'sidebar.open' : 'sidebar.close'),
                prefix: sliderVisible ? (
                  <MenuUnfoldOutlined className="icon" />
                ) : (
                  <MenuFoldOutlined className="icon" />
                ),
              },
            ],
            callback: moreMenuClick,
          },
        },
      ],
      [t, listSearch, sliderVisible, moreMenuClick],
    );

    return (
      <Wrapper
        sliderVisible={sliderVisible}
        className={sliderVisible ? 'close' : ''}
        isDragging={isDragging}
        width={width}
      >
        {sliderVisible ? (
          <MenuUnfoldOutlined className="menuUnfoldOutlined" />
        ) : (
          ''
        )}
        <ListNavWrapper defaultActiveKey="list">
          <ListPane key="list">
            <ListTitle {...titles[0]} />
            <DepartmentList departmentId={departmentId} list={departmentList} />
          </ListPane>
        </ListNavWrapper>
      </Wrapper>
    );
  },
);

const Wrapper = styled.div<{
  sliderVisible: boolean;
  isDragging: boolean;
  width: number;
}>`
  z-index: ${LEVEL_5};
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  min-height: 0;
  background-color: ${p => p.theme.componentBackground};
  box-shadow: ${p => p.theme.shadowSider};
  transition: ${p => (!p.isDragging ? 'width 0.3s ease' : 'none')};
  .hidden {
    display: none;
  }
  > ul {
    display: ${p => (p.sliderVisible ? 'none' : 'block')};
  }
  > div {
    display: ${p => (p.sliderVisible ? 'none' : 'flex')};
  }
  &.close {
    position: absolute;
    width: ${SPACE_TIMES(7.5)} !important;
    height: 100%;
    .menuUnfoldOutlined {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    &:hover {
      width: ${p => p.width + '%'} !important;
      .menuUnfoldOutlined {
        display: none;
      }
      > ul {
        display: block;
      }
      > div {
        display: flex;
        &.hidden {
          display: none;
        }
      }
    }
  }
`;

const ListNavWrapper = styled(ListNav)`
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  padding: ${SPACE_XS} 0;
  background-color: ${p => p.theme.componentBackground};
`;
