import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import classNames from 'clsx';
import dayjs from 'dayjs';
import { useRouter } from 'next/router';
import { useTheme } from '@mui/material/styles';
import {
  AutoAwesome,
  CodeRounded,
  DragIndicator,
  ExploreOutlined,
  InsertInvitationRounded,
  MoreVertRounded,
  PersonAddAltOutlined,
  PlayCircleOutline,
  PlaylistAddRounded,
  ShareRounded,
  SpeedRounded,
  ThumbUpRounded,
  TrendingUpRounded,
  VisibilityRounded,
} from '@mui/icons-material';

import { VIDEO_EMBED } from '@/modules/@common/acl/constants';
import { MODULE_CHAPTERS } from '@/modules/editorial/aiWorkbench/AiWorkbench/constants';
import {
  VIDEO_STATE_ACTIVE,
  VIDEO_STATE_FAILED,
  VIDEO_STATE_PROCESSING,
} from '@/modules/editorial/editorialSearch/constants/searchFilter';
import { MODE_PLAYLIST } from '@/modules/editorial/RightSideBar/common/constants';

import { canChangeAccess, canShare } from '../../shareAndAccess/helpers/permissions';
import { getPercent, getTime, isVideoUnsafe } from '../helpers';
import { getIsWPVideoMode } from '@/modules/@common/app/helpers';
import { abbreviateNumber } from '@/modules/@common/helpers/number';
import { getDuration } from '@/modules/@common/helpers/time';
import { addQueriesAction } from '@/modules/@common/location/redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import {
  getPublisherIdsSelector,
  getUserAccountIdSelector,
  getUserContentOwnersSelector,
  getUserIdSelector,
  getUserPermissionsSelector,
} from '@/modules/@common/user/redux/selectors';
import { initAiWorkbenchAction } from '@/modules/editorial/aiWorkbench/AiWorkbench/redux/slices';
import {
  isActiveSelector as isBulkActionsActiveSelector,
  isVideoSelectedSelector,
} from '@/modules/editorial/bulkActions/redux/selectors';
import { selectVideoAction, unselectVideoAction } from '@/modules/editorial/bulkActions/redux/slices';
import {
  getCanEditVideoAttributes,
  getContentOwnerNameAndFeedDisplayName,
} from '@/modules/editorial/editorialVideoDetails/helpers';
import { isMobileApp } from '@/modules/layout/helpers';

import AccessControlView from '@/modules/editorial/editorialSearchResults/components/AccessControlView';
import Tags from '../../common/components/NewCard/Tags/Tags';
import Thumbnail from '../../common/components/NewCard/Thumbnail/Thumbnail';
import VideoDescription from '../../common/components/NewCard/VideoDescription/VideoDescription';
import VideoName from '../../common/components/NewCard/VideoName/VideoName';
import StatusBlockComponent from '../../common/components/statusBlock/index';
import { Box, Button, Grid, IconButton, LinearProgress, Stack, Typography } from '@/mui/components';

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

const insights = [
  {
    name: 'views',
    icon: VisibilityRounded,
    getValue: (video) => video?.insights?.views,
    getMaxPerformance: (maxPerfs) => maxPerfs?.insights.views ?? 0,
  },
  {
    name: 'likes',
    icon: ThumbUpRounded,
    getValue: (video) => video?.insights?.likes,
    getMaxPerformance: (maxPerfs) => maxPerfs?.insights.likes ?? 0,
  },
  {
    name: 'shares',
    icon: ShareRounded,
    getValue: (video) => video?.insights?.shares,
    getMaxPerformance: (maxPerfs) => maxPerfs?.insights.shares ?? 0,
  },
  {
    name: 'minutesViewed',
    icon: PlayCircleOutline,
    getValue: (video) => video?.performance?.minutesViewed,
    getMaxPerformance: (maxPerfs) => maxPerfs?.minutesViewed ?? 0,
  },
  {
    name: 'avgPlayback',
    icon: SpeedRounded,
    getValue: (video) => {
      const time = (video?.performance?.avgPlayback ?? 0) * 60 || 0;

      return getTime(time);
    },
    getMaxPerformance: (maxPerfs) => maxPerfs?.avgPlayback ?? 0,
  },
  {
    name: 'trending',
    icon: TrendingUpRounded,
    getValue: (video) => video?.trending,
    getMaxPerformance: (maxPerfs) => maxPerfs?.trending ?? 0,
  },
  {
    name: 'engagement',
    icon: ExploreOutlined,
    getValue: (video) => video?.performance?.engagement,
    getMaxPerformance: (maxPerfs) => maxPerfs?.engagement ?? 0,
  },
];

function VideoInfo({ showEmbedButton = false, isInsightsMode = false, isDragging = false, ...props }) {
  const theme = useTheme();
  const router = useRouter();
  const dispatch = useDispatch();
  const [isWPVideoMode, setIsWPVideoMode] = useState(false);
  const userId = useSelector(getUserIdSelector);
  const userContentOwners = useSelector(getUserContentOwnersSelector);
  const userAccountId = useSelector(getUserAccountIdSelector);
  const userPublisherIds = useSelector(getPublisherIdsSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);
  const isBulkActionsActive = useSelector(isBulkActionsActiveSelector);
  // eslint-disable-next-line react/prop-types
  const isSelectedForBulkAction = useSelector((state) => isVideoSelectedSelector(props.video.uid, state));

  const { canEditTagsAndLabels, canSeeMenu } = getCanEditVideoAttributes(
    props.video,
    userAccountId,
    userPublisherIds,
    userId,
    userContentOwners,
    userPermissions,
  );
  const isDisabledButton =
    !props.canAddToPlaylist ||
    ![VIDEO_STATE_ACTIVE, VIDEO_STATE_PROCESSING].find((status) => props.video.status === status);
  const addToPlaylistActionFn = (event) => {
    event.stopPropagation();
    event.preventDefault();

    if (event.nativeEvent) {
      event.nativeEvent.stopImmediatePropagation();
    }

    props.addToPlaylistAction();
  };

  const contentOwnerNameAndFeedDisplayName = getContentOwnerNameAndFeedDisplayName(
    props.video,
    userContentOwners,
    userPermissions,
  );

  const handleChangeForBulkActions = (checked) => {
    if (checked) {
      // eslint-disable-next-line react/prop-types
      dispatch(selectVideoAction(props.video.uid));
    } else {
      // eslint-disable-next-line react/prop-types
      dispatch(unselectVideoAction(props.video.uid));
    }
  };

  useEffect(() => {
    setIsWPVideoMode(getIsWPVideoMode());
  }, []);

  return (
    <Grid
      container
      tabIndex={-1}
      onKeyUp={null}
      role="button"
      data-id="videoInfo"
      data-distribution-id={props.video.distributionId}
      className={classNames(styles.NewCardWrapper, {
        [styles.NewCardWrapper___isDragging]: isDragging,
        [styles.NewCardWrapper___isSelected]: isSelectedForBulkAction,
      })}
      onClick={() => {
        if (!isBulkActionsActive) {
          props.selectedVideoAction(props.video);
          props.setShouldOpenVideoMenuImmediately(false);
        }

        if (isBulkActionsActive) {
          handleChangeForBulkActions(!isSelectedForBulkAction);
        }
      }}
    >
      {!isWPVideoMode &&
        !props.video?.sponsored?.sponsored &&
        props.playlistMode === MODE_PLAYLIST &&
        props.isPlaylistSectionOpened && (
          <Stack justifyContent="center" alignItems="center" className={styles.DragSign}>
            <DragIndicator fontSize="medium" htmlColor="shades.400" />
          </Stack>
        )}
      <Grid
        className={classNames(styles.VideoContainer, {
          [styles.VideoContainer___isInsightsMode]: isInsightsMode,
          [styles.VideoContainer___mobile]: isMobileApp,
        })}
      >
        <div
          data-id="thumbnailContainer"
          className={classNames(styles.ThumbnailContainer, {
            [styles['Thumbnail-container___mobile']]: isMobileApp,
          })}
        >
          <Thumbnail
            thumbnailUrl={props.video.thumbnailUrl || ''}
            duration={getDuration(props.video.videoLength || 0)}
            lang={props.video.lang[0]}
            isUnsafe={isVideoUnsafe(props.video)}
            isArchive={props.video.status === 'DISABLED'}
            // eslint-disable-next-line react/prop-types
            isHasTargeting={props.video.targetingStatus === 'ON'}
            isInsightsMode={isInsightsMode}
            isBulkActionsActive={isBulkActionsActive}
            isSelectedForBulkAction={isSelectedForBulkAction}
            onChangeForBulkActions={handleChangeForBulkActions}
          />

          <Box className={styles.StatusBlockContainer}>
            <StatusBlockComponent
              playbackImmediately={props.video.playbackImmediately}
              status={props.video.status}
              isSponsored={!!props.video?.sponsored?.sponsored}
            />
          </Box>
        </div>
        <Grid
          data-id="infoContainer"
          container
          direction="column"
          className={classNames(styles.Info, {
            [styles.Info___wide]: !isInsightsMode,
            [styles.Info___mobile]: isMobileApp,
          })}
        >
          <Grid container>
            <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={2} fullWidth>
              <VideoName name={props.video.name} />
              {!isMobileApp && (
                <div data-id="controlsContainer" className={styles.ControlContainer}>
                  {!isInsightsMode && (
                    <Stack direction="row" spacing={1} alignItems="center" className={styles.Controls}>
                      {canSeeMenu && (
                        <Button
                          data-id="ai-workbench-button"
                          variant="contained"
                          size="xSmall"
                          shape="rounded"
                          color="secondary"
                          startIcon={<AutoAwesome />}
                          disabled={isBulkActionsActive}
                          onClick={(e) => {
                            dispatch(
                              addQueriesAction({
                                // eslint-disable-next-line react/prop-types
                                videoId: props.video.uid,
                                aiworkbench: MODULE_CHAPTERS,
                              }),
                            );

                            dispatch(
                              initAiWorkbenchAction({
                                prevVideoIdInQuery: router.query.videoId,
                                // eslint-disable-next-line react/prop-types
                                videoId: props.video.uid,
                              }),
                            );

                            e.stopPropagation();
                          }}
                        >
                          AI Workbench
                        </Button>
                      )}

                      {hasPermission(VIDEO_EMBED, userPermissions) && showEmbedButton && (
                        <IconButton
                          data-tesid="embed-button"
                          size="xSmall"
                          color="neutral"
                          disabled={isBulkActionsActive}
                          onClick={props.openEmbedPopup}
                        >
                          <CodeRounded />
                        </IconButton>
                      )}

                      {(canShare(props.video, userPublisherIds, userId) ||
                        canChangeAccess(props.video, userId, userPermissions)) &&
                        ![VIDEO_STATE_PROCESSING, VIDEO_STATE_FAILED].includes(props.video.status) && (
                          <IconButton
                            data-id="share-button"
                            size="xSmall"
                            color="neutral"
                            disabled={isBulkActionsActive}
                            onClick={props.openShareAndAccess}
                          >
                            <PersonAddAltOutlined />
                          </IconButton>
                        )}

                      {!isWPVideoMode &&
                        !props.video?.sponsored?.sponsored &&
                        props.playlistMode === MODE_PLAYLIST &&
                        props.isPlaylistSectionOpened && (
                          <IconButton
                            data-id="add-to-playlist-button"
                            size="xSmall"
                            color="neutral"
                            disabled={isDisabledButton || isBulkActionsActive}
                            onClick={addToPlaylistActionFn}
                          >
                            <PlaylistAddRounded />
                          </IconButton>
                        )}

                      {canSeeMenu && (
                        <IconButton
                          data-id="menu-button"
                          size="xSmall"
                          color="neutral"
                          disabled={isBulkActionsActive}
                          onClick={(e) => {
                            props.setShouldOpenVideoMenuImmediately(true);
                            props.selectedVideoAction(props.video);
                            e.stopPropagation();
                          }}
                        >
                          <MoreVertRounded />
                        </IconButton>
                      )}
                    </Stack>
                  )}
                </div>
              )}
            </Stack>
          </Grid>

          <Stack
            direction={isInsightsMode ? 'column' : 'row'}
            flexWrap="wrap"
            spacing={theme.spacing(0, 3)}
            className={styles.Summary}
          >
            <Stack direction="row" alignItems="center" spacing={1}>
              <InsertInvitationRounded fontSize="x3Small" />
              <Typography
                variant="caption"
                whiteSpace="nowrap"
                color={props.video.videoCreationDate ? 'text.primary' : 'text.secondary'}
              >
                {props.video.videoCreationDate
                  ? dayjs(props.video.videoCreationDate).format('MMM D, YYYY hh:mm A')
                  : 'Select Date'}
              </Typography>
            </Stack>
            {!isInsightsMode && (
              <AccessControlView
                access={props.video.access}
                showListOfSitePopup={props.showListOfSitePopup}
                setShowListOfSitePopup={props.setShowListOfSitePopup}
                showListOfUserPopup={props.showListOfUserPopup}
                setShowListOfUserPopup={props.setShowListOfUserPopup}
              />
            )}
            <Typography title={contentOwnerNameAndFeedDisplayName} variant="caption" rows={1}>
              {contentOwnerNameAndFeedDisplayName}
            </Typography>
          </Stack>

          {!isInsightsMode && <VideoDescription plot={props.video.plot || ''} />}

          {!isInsightsMode && (
            <Tags
              video={props.video}
              isEditable={canEditTagsAndLabels}
              disabled={isBulkActionsActive}
              onClickEdit={() => props.openTagsEditor(true)}
            />
          )}
        </Grid>
      </Grid>

      {isInsightsMode && (
        <div className={styles.Insights} data-id="info-insights">
          {insights.map((insight) => {
            const Icon = insight.icon;

            return (
              <div key={insight.name}>
                <div className={styles.InsightsItem} data-id={`info-insights-${insight.name}`}>
                  <Stack direction="row" alignItems="center" spacing={2}>
                    <Icon fontSize="small" htmlColor="info.dark" />
                    <Typography variant="body2" fontWeight="600" color="info.dark">
                      {abbreviateNumber(insight.getValue(props.video))}
                    </Typography>
                  </Stack>
                  <LinearProgress
                    variant="determinate"
                    color="info"
                    value={getPercent(insight.getValue(props.video), insight.getMaxPerformance(props.maxPerformance))}
                  />
                </div>
              </div>
            );
          })}
        </div>
      )}
    </Grid>
  );
}

VideoInfo.propTypes = {
  video: PropTypes.shape({
    name: PropTypes.string.isRequired,
    plot: PropTypes.string,
    access: PropTypes.shape({}),
    distributionId: PropTypes.string.isRequired,
    videoCreationDate: PropTypes.number,
    playbackImmediately: PropTypes.bool,
    status: PropTypes.string.isRequired,
    thumbnailUrl: PropTypes.string,
    videoLength: PropTypes.number,
    lang: PropTypes.arrayOf(PropTypes.string),
    sponsored: PropTypes.shape({
      sponsored: PropTypes.bool,
    }),
  }).isRequired,
  canAddToPlaylist: PropTypes.bool.isRequired,
  addToPlaylistAction: PropTypes.func.isRequired,
  selectedVideoAction: PropTypes.func.isRequired,
  openEmbedPopup: PropTypes.func.isRequired,
  openShareAndAccess: PropTypes.func.isRequired,
  showEmbedButton: PropTypes.bool,
  isInsightsMode: PropTypes.bool,
  playlistMode: PropTypes.string.isRequired,
  isDragging: PropTypes.bool,
  isPlaylistSectionOpened: PropTypes.bool.isRequired,
  showListOfSitePopup: PropTypes.bool.isRequired,
  setShowListOfSitePopup: PropTypes.func.isRequired,
  showListOfUserPopup: PropTypes.bool.isRequired,
  setShowListOfUserPopup: PropTypes.func.isRequired,
  maxPerformance: PropTypes.shape({
    completed: PropTypes.number,
    engagement: PropTypes.number,
    likes: PropTypes.number,
    avgPlayback: PropTypes.number,
    minutesViewed: PropTypes.number,
    recommendationPlaylistRatio: PropTypes.number,
    s20VideoViews: PropTypes.number,
    shares: PropTypes.number,
    trending: PropTypes.number,
    uniqueUsers: PropTypes.number,
    views: PropTypes.number,
  }).isRequired,
  setShouldOpenVideoMenuImmediately: PropTypes.func.isRequired,
  openTagsEditor: PropTypes.func.isRequired,
};

export default VideoInfo;
