import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { parse } from 'qs';
import { DragOverlay } from '@dnd-kit/core';
import { KeyboardArrowDownRounded, KeyboardArrowUpRounded, TheatersRounded } from '@mui/icons-material';

import { DND_DRAG_OVERLAY_ID } from '@/modules/editorial/constants/dnd';
import { QUERY_PARAM_TAB, TAB_WATCH } from '@/modules/editorial/constants/routing';
import { RECENT } from '@/modules/editorial/constants/video';
import { MODE_LIST } from '@/modules/editorial/RightSideBar/common/constants';

import * as selectors from '../../redux/selectors';
import {
  aiPlaylistIdAction,
  getEmbedCodeAction,
  getPlayersAction,
  loadNextEventAction,
  playlistModeAction,
  selectedAspectRatioAction,
  selectedPlayerAction,
  selectedVideoAction,
  showDividerAction,
  showEmbedCodeButtonAction,
  showNotificationAction,
  targetVideoIdAction,
  videosAction,
  videosChangeProcessingStatusMonitoringAction,
} from '../../redux/slices';
import * as filterContainerSelectors from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/selectors';
import {
  configAction,
  configChangedEventAction,
  restoreConfigAction,
} from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/slices';
import {
  aiPlaylistModeSelector,
  playlistIdSelector,
  playlistsSelector,
} from '@/modules/editorial/RightSideBar/TabPlaylist/redux/selectors';
import {
  setAiPlaylistModeAction,
  updateAiFiltersAction as playlistsUpdateAiFiltersAction,
} from '@/modules/editorial/RightSideBar/TabPlaylist/redux/slices';
import {
  aiPlaylistSelector as watchAiPlaylistSelector,
  channelIdSelector,
  watchIdSelector,
} from '@/modules/editorial/RightSideBar/TabWatch/Watches/redux/selectors';
import { updateAiFiltersAction as watchUpdateAiFiltersAction } from '@/modules/editorial/RightSideBar/TabWatch/Watches/redux/slices';
import { isMobileApp } from '@/modules/layout/helpers';

import ReactList from '@/modules/@common/components/ReactList/ReactList';
import { filterConfig } from '../../../editorialSearchFilter/filterConfig';
import ListItem from '../listItem';
import VideoPlaceholder from '../placeholder';
import { Button, ButtonGroup, Divider, Paper, Stack, Tooltip, Typography } from '@/mui/components';

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

function SearchResultsComponent(props) {
  const router = useRouter();
  const dispatch = useDispatch();
  const aiPlaylistMode = useSelector(aiPlaylistModeSelector);
  const watchAiPlaylist = useSelector(watchAiPlaylistSelector);
  const watchId = useSelector(watchIdSelector);
  const channelId = useSelector(channelIdSelector);
  const playlists = useSelector(playlistsSelector);
  const playlistId = useSelector(playlistIdSelector);

  const canAddToPlaylist = useSelector(selectors.canAddToPlaylistSelector);
  const embedCode = useSelector(selectors.embedCodeSelector);
  const players = useSelector(selectors.playersSelector);
  const searchFilters = useSelector(selectors.searchFiltersSelector);
  const selectedAspectRatio = useSelector(selectors.selectedAspectRatioSelector);
  const selectedPlayer = useSelector(selectors.selectedPlayerSelector);
  const selectedVideo = useSelector(selectors.selectedVideoSelector);
  const totalCount = useSelector(selectors.totalCountSelector);
  const videos = useSelector(selectors.videosSelector);
  const playlistMode = useSelector(selectors.playlistModeSelector);
  const isVideosLoading = useSelector(selectors.isVideosLoadingSelector);
  const showEmbedCodeButton = useSelector(selectors.showEmbedCodeButtonSelector);
  const aiPlaylistId = useSelector(selectors.aiPlaylistIdSelector);
  const showDivider = useSelector(selectors.showDividerSelector);
  const maxPerformance = useSelector(selectors.maxPerformanceSelector);

  const isInsightsMode = useSelector(filterContainerSelectors.isInsightsModeSelector);
  const config = useSelector(filterContainerSelectors.configSelector);

  const isWatchTabOpen = router.query[QUERY_PARAM_TAB] === TAB_WATCH;

  let aiPlaylist = {};
  let playlistType = '';
  if (isWatchTabOpen) {
    aiPlaylist = watchAiPlaylist;
    playlistType = Object.keys(aiPlaylist).find((key) => +(aiPlaylist[key]?.id ?? 0) === +aiPlaylistId);
  } else {
    const playlist = playlists.find((playlist$) => playlist$.id === playlistId);
    if (playlist && playlist.aiPlaylists) {
      aiPlaylist = Object.values(playlist.aiPlaylists).find((aiPlaylist$) => aiPlaylist$.id === aiPlaylistId);
      playlistType = aiPlaylist?.type;
    }
  }

  const updateAiFiltersAction = isWatchTabOpen ? watchUpdateAiFiltersAction : playlistsUpdateAiFiltersAction;
  const updateAiFiltersInputData = isWatchTabOpen ? { watchId, channelId } : { playlistId };

  const showNoResults = !isVideosLoading && searchFilters && !videos.length;
  const showList = !isVideosLoading && !!videos.length;
  const activeSorter = config.orderForInsights?.filters?.[0]?.value;

  const handleSortInsights = (filter, isReversed) => {
    const prevSorterValue = config?.orderForInsights?.filters?.[0]?.value;

    const updatedConfig = {
      ...config,
      orderForInsights: {
        ...config.orderForInsights,
        filters: [filter],
        isReversed: isReversed || prevSorterValue === filter?.value ? !config.orderForInsights.isReversed : false,
      },
    };

    dispatch(configAction(updatedConfig));
    dispatch(configChangedEventAction());
  };

  useEffect(() => {
    dispatch(playlistModeAction(MODE_LIST));
  }, []);

  useEffect(() => {
    if (isInsightsMode && !activeSorter) {
      handleSortInsights(filterConfig.orderForInsights.filters[0], false);
    }
  }, [isInsightsMode]);

  useEffect(() => {
    dispatch(videosChangeProcessingStatusMonitoringAction());
  }, []);

  useEffect(() => {
    dispatch(getPlayersAction());
  }, []);
  const handleCancelFilters = () => {
    dispatch(setAiPlaylistModeAction(false));
    dispatch(aiPlaylistIdAction(0));
    dispatch(showDividerAction(false));
    dispatch(restoreConfigAction());
  };

  const handleSaveFilters = () => {
    dispatch(setAiPlaylistModeAction(false));
    dispatch(
      updateAiFiltersAction({
        ...updateAiFiltersInputData,
        aiPlaylistId: +aiPlaylistId,
      }),
    );
    dispatch(aiPlaylistIdAction(0));
    dispatch(showDividerAction(false));
    dispatch(restoreConfigAction());
  };

  return (
    <>
      {isInsightsMode && (
        <Stack direction="row" data-id="total" className={styles.Total}>
          <div>
            <div className={styles.TotalInfo} />
          </div>
          <Stack spacing={0} alignItems="center" justifyContent="center">
            <Stack direction="row" alignItems="center" fullWidth divider={<Divider flexItem orientation="vertical" />}>
              <Typography
                component="div"
                align="center"
                variant="body1"
                color="text.secondary"
                className={styles.StatsHeaderTitle}
              >
                AnyClip + Social Stats
              </Typography>
              <Typography
                component="div"
                align="center"
                variant="body1"
                color="text.secondary"
                className={styles.StatsHeaderTitle}
              >
                AnyClip Stats
              </Typography>
            </Stack>
            <Stack direction="row" alignItems="center">
              {filterConfig.orderForInsights.filters.map((item, index) => (
                <React.Fragment key={item.value}>
                  <Stack alignItems="center" justifyContent="center" direction="row" className={styles.StatsItem}>
                    <Tooltip title={item.info} placement="top-end">
                      <ButtonGroup variant="text" size="xSmall">
                        <Button
                          data-id={item.value}
                          onClick={() => {
                            handleSortInsights(item);
                          }}
                        >
                          {item.label}
                        </Button>
                        {config.orderForInsights?.filters?.[0]?.value === item.value ? (
                          <Button
                            data-id={item.value}
                            onClick={() => {
                              handleSortInsights(item);
                            }}
                            square
                            startIcon={
                              config.orderForInsights.isReversed ? (
                                <KeyboardArrowUpRounded />
                              ) : (
                                <KeyboardArrowDownRounded />
                              )
                            }
                          />
                        ) : null}
                      </ButtonGroup>
                    </Tooltip>
                  </Stack>
                  {index === 2 && <Divider flexItem orientation="vertical" />}
                </React.Fragment>
              ))}
            </Stack>
          </Stack>
        </Stack>
      )}
      {isVideosLoading && (
        <div className={styles.Container}>
          <VideoPlaceholder />
        </div>
      )}
      {showNoResults && (
        <div className={styles.Container}>
          <Stack spacing={4} alignItems="center" justifyContent="center" className={styles.NoResults}>
            <div className={styles.NoResultsIconWrapper}>
              <TheatersRounded htmlColor="shades.500" fontSize="x4Large" />
            </div>
            <Typography variant="body2" color="text.secondary">
              Sorry, we weren&apos;t able to find any relevant videos :(
            </Typography>
          </Stack>
        </div>
      )}

      {showList && videos.length && (
        <ReactList
          className={styles.Container}
          length={videos.length}
          pageSize={10}
          itemRenderer={(index) => {
            const videoInfo = videos[index];
            const isDisabledDragging =
              !canAddToPlaylist ||
              !!videoInfo.sponsored?.sponsored ||
              parse(window.location.search, { ignoreQueryPrefix: true })?.highlights !== undefined ||
              !['ACTIVE', 'PROCESSING'].find((status) => videoInfo.status === status);

            return (
              <Fragment key={videoInfo.uid}>
                {aiPlaylist && aiPlaylist[playlistType]?.length === index && showDivider && (
                  <div className={styles.AiPlaylistDivider} />
                )}
                <div>
                  <ListItem
                    key={videoInfo.uid}
                    index={index}
                    videos={videos}
                    videosAction={(v) => dispatch(videosAction(v))}
                    totalCount={totalCount}
                    selectedVideo={selectedVideo}
                    searchFilters={searchFilters}
                    canAddToPlaylist={canAddToPlaylist}
                    addToPlaylistAction={() => dispatch(targetVideoIdAction(videoInfo.uid))}
                    selectedVideoAction={(v) => dispatch(selectedVideoAction(v))}
                    loadNextEventAction={(v) => dispatch(loadNextEventAction(v))}
                    players={players}
                    selectedPlayer={selectedPlayer}
                    selectedPlayerAction={(v) => dispatch(selectedPlayerAction(v))}
                    selectedAspectRatio={selectedAspectRatio}
                    selectedAspectRatioAction={(v) => dispatch(selectedAspectRatioAction(v))}
                    showNotificationAction={(v) => dispatch(showNotificationAction(v))}
                    embedCode={embedCode}
                    getEmbedCodeAction={(v) => dispatch(getEmbedCodeAction(v))}
                    showEmbedCodeButton={showEmbedCodeButton}
                    showEmbedCodeButtonAction={(v) => dispatch(showEmbedCodeButtonAction(v))}
                    isInsightsMode={isInsightsMode}
                    activeSorter={activeSorter}
                    playlistMode={playlistMode}
                    isPlaylistSectionOpened={props.isPlaylistSectionOpened}
                    maxPerformance={maxPerformance}
                    isDragDisabled={isDisabledDragging || isMobileApp}
                  />
                </div>
              </Fragment>
            );
          }}
        />
      )}

      {aiPlaylistMode && (
        <Stack
          component={Paper}
          spacing={2}
          direction="row"
          alignItems="center"
          elevation={8}
          className={styles.RecentControls}
        >
          <Button color="primary" size="small" variant="outlined" onClick={handleCancelFilters}>
            Cancel
          </Button>
          <Button color="primary" size="small" onClick={handleSaveFilters}>
            {`Save to ${playlistType === RECENT ? 'Recency' : 'Trending'} Block`}
          </Button>
        </Stack>
      )}

      {props.isDragVideoOverlayActive && (
        <DragOverlay>
          <div id={DND_DRAG_OVERLAY_ID} />
        </DragOverlay>
      )}
    </>
  );
}

SearchResultsComponent.propTypes = {
  isPlaylistSectionOpened: PropTypes.bool.isRequired,
  isDragVideoOverlayActive: PropTypes.bool.isRequired,
};

export default SearchResultsComponent;
