import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import classNames from 'clsx';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import {
  AddToQueueRounded,
  KeyboardArrowLeftOutlined,
  KeyboardArrowRightOutlined,
  QueuePlayNextRounded,
} from '@mui/icons-material';

import { MODE_LIST } from './common/constants';
import { PCN_GET_MANAGE_WATCH, PCN_GET_PLAYLIST } from '@/modules/@common/acl/constants';
import {
  QUERY_PARAM_CHANNEL,
  QUERY_PARAM_PLAYLIST,
  QUERY_PARAM_PLAYLIST_EDIT,
  QUERY_PARAM_TAB,
  QUERY_PARAM_WATCH_ID,
  TAB_PLAYLIST,
  TAB_WATCH,
} from '@/modules/editorial/constants/routing';

import { playlistModeAction, startSearchEventAction } from '../editorialSearchResults/redux/slices';
import { setModeAction } from './TabPlaylist/redux/slices';
import { openChannelAction } from './TabWatch/Watches/redux/slices';
import { getIsWordpressMode } from '@/modules/@common/app/helpers';
import { addQueriesAction, removeQueriesAction } from '@/modules/@common/location/redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { isMobileApp } from '@/modules/layout/helpers';

import { Button, Paper, Stack, Tab, Tabs } from '@/mui/components';

import styles from './styles.module.scss';

const Playlists = dynamic(() => import('./TabPlaylist/Playlists/components/Playlists'), {
  ssr: false,
});
const Watches = dynamic(() => import('./TabWatch/Watches/components'), {
  ssr: false,
});

const getActiveTabIndex = (tabQuery, tabs) => {
  const index = tabs.findIndex(({ id }) => id === tabQuery);
  return index !== -1 ? index : 0;
};

function EditorialSideBar(props) {
  const router = useRouter();
  const dispatch = useDispatch();

  const userPermissions = useSelector(getUserPermissionsSelector);

  const tabs = [
    hasPermission(PCN_GET_MANAGE_WATCH, userPermissions) &&
      !getIsWordpressMode() && {
        label: 'Watch',
        Icon: AddToQueueRounded,
        id: TAB_WATCH,
        Content: Watches,
      },
    hasPermission(PCN_GET_PLAYLIST, userPermissions) && {
      label: 'Playlist',
      Icon: QueuePlayNextRounded,
      id: TAB_PLAYLIST,
      Content: Playlists,
    },
  ].filter(Boolean);

  const [activeTab, setActiveTab] = useState(getActiveTabIndex(router.query.tab, tabs));

  const dispatchNewTab = (index) => {
    dispatch(addQueriesAction({ [QUERY_PARAM_TAB]: tabs[index].id }));

    // return path to init
    dispatch(startSearchEventAction());
    dispatch(
      removeQueriesAction(
        tabs[index]?.id === TAB_WATCH
          ? [QUERY_PARAM_PLAYLIST, QUERY_PARAM_PLAYLIST_EDIT]
          : [QUERY_PARAM_WATCH_ID, QUERY_PARAM_CHANNEL],
      ),
    );
    // return watch to init
    dispatch(openChannelAction({ watchId: null, channelId: null }));
    // return playlist to init
    dispatch(playlistModeAction(MODE_LIST));
    dispatch(setModeAction(MODE_LIST));
  };

  useEffect(() => {
    const newIndex = getActiveTabIndex(router.query.tab, tabs);
    setActiveTab(newIndex);

    if (tabs[newIndex].id !== router.query.tab) {
      dispatchNewTab(newIndex);
    }
  }, [router.query.tab]);

  return (
    <Paper
      elevation={1}
      className={classNames(styles.Playlist, {
        [styles.Playlist___mobile]: isMobileApp,
        [styles.Playlist___hide]: !props.showSideBar,
      })}
      data-id="playlistContainer"
      id="playlistContainer"
    >
      {tabs.length > 1 && (
        <Stack justifyContent="center">
          <Tabs value={activeTab} onChange={(e, tabIndex) => dispatchNewTab(tabIndex)} centered variant="fullWidth">
            {tabs.map((tabObject) => {
              const { Icon } = tabObject;

              return <Tab data-id={tabObject.id} key={tabObject.id} icon={<Icon />} label={tabObject.label} />;
            })}
          </Tabs>
        </Stack>
      )}
      {tabs.map((tabInfo, index) => {
        if (index === activeTab) {
          const Component = tabInfo.Content;
          return <Component key={tabInfo.Content} />;
        }
        return null;
      })}
      <Button
        className={classNames(styles.Toggle, {
          [styles.Toggle___collapsed]: isMobileApp || !props.showSideBar,
        })}
        square
        shape="circular"
        size={!isMobileApp ? 'small' : 'large'}
        onClick={props.toggleSideBar}
        startIcon={props.showSideBar ? <KeyboardArrowRightOutlined /> : <KeyboardArrowLeftOutlined />}
      />
    </Paper>
  );
}

EditorialSideBar.propTypes = {
  toggleSideBar: PropTypes.func.isRequired,
  showSideBar: PropTypes.bool.isRequired,
};

export default EditorialSideBar;
