import React, { useEffect, useState } from 'react';
import { useHistory, withRouter, RouteComponentProps } from 'react-router-dom';
import * as R from 'ramda';
import {YRouterItem} from '@/default.interface';
import {BookmarkProps, TargetKey, BookmarkActionType} from './module.interface';
import {TabsStyle, TabPaneStyle} from './bookmark.styles';
import { useModuleStore } from './useStore';

const Bookmark: React.FC<BookmarkProps & RouteComponentProps> = ({userId = '', projectId = '', location, config}) => {
  const [panes, setPanes] = useState<YRouterItem[]>(null as unknown as YRouterItem[]);
  const [activeKey, setActiveKey] = useState('');
  const [state, dispatch] = useModuleStore();
  const [sessionKey, setSessionKey] = useState(''); 
  const history = useHistory();

  const onChange = (key: string) => {
    setActiveKey(key);
    history.push(key);
  }

  const onEdit = async (targetKey: TargetKey, action: BookmarkActionType) => {
    console.log('close_menu 0', state)
    if (action === 'remove') {
      const res: any = await dispatch({
        type: 'close_menu',
        payload: {
          data: {
            path: targetKey,
            selectedMenus: panes
          }
        }
      });
      console.log('close_menu 1', res);
      sessionStorage.setItem(sessionKey, JSON.stringify([...res.selectedMenus]));
      setPanes([...res.selectedMenus])
    };
  }

  const updateSessionData = (key: string) => {
    setSessionKey(key);
    const data = sessionStorage.getItem(key);
    let selectedMenus: YRouterItem[] = [];
    if(data){
      selectedMenus = JSON.parse(data);
    }
    console.log('updateSessionData', state.defaultMenu?.url, config.moduleId);
    if(state.defaultMenu && state.defaultMenu.url && state.defaultMenu.url.indexOf(config.moduleId) >= 0){
      const confn = R.eqBy(R.prop('name') as any) as any;
      selectedMenus = R.unionWith(confn, selectedMenus, [state.defaultMenu]) as YRouterItem[];
    }
    setPanes([...selectedMenus]);
    if(state.defaultMenu){
      setActiveKey(`${state.defaultMenu.path}${location.search}`);
    }
    sessionStorage.setItem(key, JSON.stringify([...selectedMenus]));
  }

  useEffect(() => {
    if(!sessionKey || sessionKey === `${userId}${projectId}`){
      updateSessionData(`${userId}${projectId}`);
    } else {
      setSessionKey(`${userId}${projectId}`);
    }
  }, [state.defaultMenu]);


  return (
    <>
      {
        panes && panes.length ? (
          <TabsStyle
            hideAdd
            onChange={onChange}
            activeKey={activeKey}
            type="editable-card"
            onEdit={onEdit}
            size="small"
          >
            {panes.map((pane: YRouterItem) => (
              <TabPaneStyle
                tab={pane.meta?.title}
                key={pane.path}
                closable={panes.length !== 1}
              />
            ))}
          </TabsStyle>
        ) : null
      }
    </>
  );
}
export default withRouter(Bookmark);