import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import { useTheme } from '@mui/material/styles';
import { AutoAwesome, CodeRounded, DragIndicator, PersonAddAltOutlined, PlaylistAddRounded } from '@mui/icons-material';

import {
  PCN_GET_DESTINATIONS,
  VIDEO_ACCESS_TARGETING,
  VIDEO_EMBED,
  VIDEO_INSIGHTS,
} 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 { PLATFORM_FACEBOOK, PLATFORM_YOUTUBE } from '@/modules/publishing/DestinationList/constants';

import canShowTrim from '../../common/components/trimVideo/helpers/canShowTrim';
import { canChangeAccess, canShare } from '../../shareAndAccess/helpers/permissions';
import {
  canAccessTabAdvanced,
  canAccessTabInfo,
  canArchive,
  canEditVideoByAccessControl,
  canShowVideoContentOwnerName,
  defineThumbnail,
  getCanEditVideoAttributes,
  tagsGenerator,
} from '../helpers';
import * as detailsSelectors from '../redux/selectors';
import {
  clearAction,
  currentVideoTimeAction,
  deleteVideoAction,
  dialogVisibleAction,
  evergreenAction,
  getOwnersOptionsAction,
  getSpeechToTextModelsAction,
  monitoringJobAction,
  selectedVideoAction,
  setTabIndexAction,
  speechToTextModelAction,
  updateVideoAction,
  updateVideoTagsAction,
} from '../redux/slices';
import { getIsWPVideoMode } from '@/modules/@common/app/helpers';
import { loadLanguagesAction } from '@/modules/@common/ccFiles/redux/slices';
import { getVideoLangs } from '@/modules/@common/helpers/videoLangs';
import { getTreeByChildItems } from '@/modules/@common/iab/helpers';
import { addQueriesAction } from '@/modules/@common/location/redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import {
  getPublisherIdsSelector,
  getUserAccountIdSelector,
  getUserContentOwnersSelector,
  getUserIdSelector,
  getUserPermissionsSelector,
  getUserRoleTypeSelector,
} from '@/modules/@common/user/redux/selectors';
import { initAiWorkbenchAction } from '@/modules/editorial/aiWorkbench/AiWorkbench/redux/slices';
import { monitoringJobsSelector } from '@/modules/editorial/editorialSearch/redux/selectors';
import { monitoringAction, videoJobAction } from '@/modules/editorial/editorialSearch/redux/slices';
import { isMobileApp } from '@/modules/layout/helpers';
import { publishEntriesSelector } from '@/modules/publishing/DestinationList/redux/selectors';

import Tags from '../../common/components/NewCard/Tags/Tags';
import VideoPlayer from '../../common/components/NewCard/VideoPlayer/VideoPlayer';
import StatusBlockComponent from '../../common/components/statusBlock/index';
import AccessControlView from '../../editorialSearchResults/components/AccessControlView';
import TagEditor from '../../TagEditor';
import EditorialMenu from './menu';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  InlineEditAutocomplete,
  InlineEditDateTimePicker,
  InlineEditTextField,
  Stack,
  Tab,
  TabContent,
  Tabs,
} from '@/mui/components';

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

const TabAdvanced = dynamic(() => import('./Tabs/TabAdvanced'), { ssr: false });
const TabAssets = dynamic(() => import('./Tabs/TabAssets'), { ssr: false });
const TabInfo = dynamic(() => import('./Tabs/TabInfo'), { ssr: false });
const TabPromotions = dynamic(() => import('./Tabs/TabPromotions/TabPromotions'), { ssr: false });
const TabInsights = dynamic(() => import('./Tabs/TabInsights'), { ssr: false });
const TabPublish = dynamic(() => import('./Tabs/TabPublish'), { ssr: false });
const PublishDialog = dynamic(() => import('./Tabs/TabPublish/components/PublishDialog/PublishDialog'), { ssr: false });
const PublishNameEditConfirm = dynamic(
  () => import('./Tabs/TabPublish/components/PublishNameEditConfirm/PublishNameEditConfirm'),
  { ssr: false },
);
const TabTargeting = dynamic(() => import('./Tabs/TabTargeting/components/TabTargeting'), { ssr: false });
const TabVersions = dynamic(() => import('./Tabs/TabVersions/components/TabVersions'), { ssr: false });

const TrimVideo = dynamic(() => import('../../common/components/trimVideo'), {
  ssr: false,
});

const maxLength = {
  TITLE: 1000,
  DESCRIPTION: 10000,
};

const maxTitleNameForPublish = {
  [PLATFORM_YOUTUBE]: 100,
  [PLATFORM_FACEBOOK]: 255,
};

const getOwnerAutocompleteValue = (video, userPermissions) => ({
  label: `${video.feedSource}${canShowVideoContentOwnerName(userPermissions) ? `/${video.contentOwnerName}` : ''}`,
  value: video.contentOwner,
});

function EditorialVideoDetails({
  showEmbedButton = false,
  isInsightsMode = false,
  shouldOpenVideoMenuImmediately = false,
  ...props
}) {
  const theme = useTheme();
  const router = useRouter();
  const dispatch = useDispatch();

  const userId = useSelector(getUserIdSelector);
  const userContentOwners = useSelector(getUserContentOwnersSelector);
  const userAccountId = useSelector(getUserAccountIdSelector);
  const userPublisherIds = useSelector(getPublisherIdsSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);
  const userRoleType = useSelector(getUserRoleTypeSelector);

  const publishEntries = useSelector(publishEntriesSelector);

  const monitoringJobs = useSelector(monitoringJobsSelector);

  const dialogVisible = useSelector(detailsSelectors.dialogVisibleSelector);
  const selectedVideo = useSelector(detailsSelectors.selectedVideoSelector);
  const tabIndex = useSelector(detailsSelectors.tabIndexSelector);
  const speechToTextModel = useSelector(detailsSelectors.speechToTextModelSelector);
  const speechToTextModels = useSelector(detailsSelectors.speechToTextModelsSelector);
  const ownersOptions = useSelector(detailsSelectors.ownersOptionsSelector);

  const tags = tagsGenerator(props.video, props.searchFilters);
  const langs = useMemo(() => getVideoLangs(), []);
  const {
    canEditVideoName,
    canEditVideoDescription,
    canEditVideoDate,
    canEditVideoSource,
    canEditTagsAndLabels,
    canSeeMenu,
    canOperateWithVideoVersionUpload,
    canShowTabVideoVersions,
  } = getCanEditVideoAttributes(
    props.video,
    userAccountId,
    userPublisherIds,
    userId,
    userContentOwners,
    userPermissions,
    userRoleType,
  );
  const thumbnailUrl = defineThumbnail(props.video.thumbnailUrl, props.video.thumbnailFiles);
  const lang = props.video.lang ? langs.find((lng) => props.video.lang.includes(lng.id)).id : '';
  const truncateVideoName = (str, max, suffix) =>
    str.length <= max ? str : `${str.substring(0, max - suffix.length)}${suffix}`;

  const [publishEntriesPlatform, setPublishEntriesPlatform] = useState('');
  const [isPublishOpen, setPublishOpen] = useState(false);
  const [isErrorMessageOpen, setErrorMessageOpen] = useState(false);
  const [videoName, setVideoName] = useState('');
  const [isWPVideoMode, setIsWPVideoMode] = useState(false);

  const MAX_LENGTH_VIDEO_NAME = maxTitleNameForPublish[publishEntriesPlatform] || PLATFORM_YOUTUBE;
  const VIDEO_NAME_SUFFIX = '...';

  const { aiworkbench } = router.query;

  const handleTruncateVideoName = (name) => {
    setVideoName(truncateVideoName(name, MAX_LENGTH_VIDEO_NAME, VIDEO_NAME_SUFFIX));
  };

  const handlePopupVideoNameChange = (name) => {
    dispatch(updateVideoAction({ name }));
  };

  const handleVideoDateChange = (date) => {
    const newDateValue = new Date(date).valueOf();
    const maxDateValue = new Date(dayjs().endOf('minute')).valueOf();

    if (newDateValue >= 0 && newDateValue <= maxDateValue) {
      dispatch(updateVideoAction({ videoCreationDate: newDateValue }));
    }
  };

  const handleOwnerChange = (value) => {
    if (
      !value?.id ||
      (selectedVideo.contentOwner === value.contentOwner && selectedVideo.feedSourceId === value.feedSourceId)
    ) {
      return;
    }

    dispatch(
      updateVideoAction({
        feedSourceId: value.id,
        feedSource: value.display_name || value.name,
        feedDescription: value.display_name || value.name,
        contentOwner: value.contentOwnerId,
      }),
    );
  };

  const handleVideoEverGreenChange = (evergreen) => {
    dispatch(updateVideoAction({ evergreen }));
    dispatch(evergreenAction(evergreen));
  };

  const handleVideoLabelChange = (labels) => {
    if (props.video.label?.length === labels.length) {
      const changedLabels = labels.filter((_lbl) => {
        const lblSource = props.video.label.find((lbl) => _lbl.labelId === lbl.labelId);

        return lblSource && _lbl.color !== lblSource.color;
      });

      if (changedLabels.length) {
        const updatedVideos = props.videos.map((_video) => ({
          ..._video,
          ...{
            label:
              _video.label?.map((_label) => {
                const lbl = changedLabels.find((el) => el.labelId === _label.labelId) ?? _label;

                return {
                  ..._label,
                  ...{
                    color: lbl.color,
                  },
                };
              }) ?? null,
          },
        }));

        props.videosAction(updatedVideos);
      }
    }
    dispatch(updateVideoTagsAction({ label: labels }));
  };

  const handleArchiveVideoClick = () => {
    dispatch(dialogVisibleAction(true));
  };

  const handleDeleteVideo = () => {
    dispatch(deleteVideoAction());
  };

  const handleArchiveConfirm = () => {
    const status = 'DISABLED';
    dispatch(dialogVisibleAction());
    dispatch(updateVideoAction({ status }));
  };

  const handleDialogClose = () => {
    dispatch(dialogVisibleAction());
  };

  const handleRefIdChange = (refId) => {
    if (selectedVideo.refId !== refId) {
      dispatch(updateVideoAction({ refId }));
    }
  };

  const handleNotesChange = (notes) => {
    if (selectedVideo.notes !== notes) {
      dispatch(updateVideoAction({ notes }));
    }
  };

  // handlers for new TagEditor
  const handleOnChangeSystemTags = (systemTags) => {
    const tagsFoUpdate = systemTags.reduce(
      (acc, tag) => {
        // eslint-disable-next-line react/prop-types
        const existInVideo = props.video.keywords?.find((videoKeyword) => videoKeyword.id === tag.id);
        const isKeywords = tag.type !== 'iab';

        if (existInVideo) {
          acc[isKeywords ? 'keywords' : 'iab'].push(existInVideo);
        } else {
          acc[isKeywords ? 'keywords' : 'iab'].push(
            isKeywords
              ? {
                  category: tag.type.toUpperCase(),
                  id: tag.id,
                  value: tag.text,
                  version: 'MANUAL_V4',
                }
              : {
                  id: tag.id,
                  name: tag.text,
                  probability: 1,
                  version: 'MANUAL_V4',
                },
          );
        }

        return acc;
      },
      { keywords: [], iab: [] },
    );

    dispatch(
      updateVideoTagsAction({
        keywords: tagsFoUpdate.keywords,
        iab: getTreeByChildItems(tagsFoUpdate.iab),
      }),
    );
  };

  const sortedVideoFiles = props.video.videoFiles?.length
    ? [...props.video.videoFiles].sort((a, b) => b.height - a.height)
    : [];

  let videoFiles = props.video.sourceVideoFile
    ? [{ ...props.video.sourceVideoFile, source: true }, ...sortedVideoFiles]
    : sortedVideoFiles;

  if (props.video.videoFileHls) {
    videoFiles = [...videoFiles, { ...props.video.videoFileHls, isHls: true }];
  }

  const tabs = [
    {
      name: 'videoInfo',
      dataId: 'videoInfo',
      label: 'Info',
      content: (
        <TabInfo
          key="videoInfo"
          lang={lang}
          updateVideoAction={(value) => dispatch(updateVideoAction(value))}
          video={props.video}
          monitoringJobs={monitoringJobs}
        />
      ),
      show: canAccessTabInfo(props.video, userContentOwners, userPermissions),
    },
    {
      name: 'insights',
      dataId: 'insights',
      label: 'Insights',
      content: (
        <TabInsights
          performance={props.video.performance}
          mediaPlatformPerformance={props.video.mediaPlatformPerformance}
        />
      ),
      show: hasPermission(VIDEO_INSIGHTS, userPermissions),
    },
    {
      name: 'promotions',
      dataId: 'videoPromotions',
      label: 'Promotions',
      content: <TabPromotions video={props.video} updateVideoAction={(value) => dispatch(updateVideoAction(value))} />,
      show: true,
    },
    {
      name: 'publish',
      dataId: 'publish',
      label: 'Publish',
      content: <TabPublish video={props.video} setPublishOpen={setPublishOpen} />,
      show: hasPermission(PCN_GET_DESTINATIONS, userPermissions),
    },
    {
      name: 'targeting',
      dataId: 'targeting',
      label: 'Targeting',
      content: (
        <TabTargeting
          videoId={props.video.uid}
          isVideoSponsored={props.video?.sponsored?.sponsored}
          accessControlSites={props.video?.access?.sites?.map((site) => `${site.id}`)}
        />
      ),
      show: hasPermission(VIDEO_ACCESS_TARGETING, userPermissions),
    },
    {
      name: 'videoAssets',
      dataId: 'videoAssets',
      label: 'Assets',
      content: (
        <TabAssets
          video={props.video}
          videoFiles={videoFiles}
          updateVideoAction={(value) => dispatch(updateVideoAction(value))}
          handleRefIdChange={handleRefIdChange}
        />
      ),
      show: true,
    },
    {
      name: 'advanced',
      dataId: 'advanced',
      label: 'Advanced',
      content: (
        <TabAdvanced
          video={props.video}
          monitoringJobs={monitoringJobs}
          videoJobAction={(value) => dispatch(videoJobAction(value))}
          videoVerificationAction={() => null}
          updateVideoAction={(value) => dispatch(updateVideoAction(value))}
          deleteVideoAction={handleDeleteVideo}
          canArchive={canArchive(props.video, userContentOwners, userPermissions)}
          speechToTextModel={speechToTextModel}
          speechToTextModels={speechToTextModels}
          speechToTextModelAction={(value) => dispatch(speechToTextModelAction(value))}
        />
      ),
      show: canAccessTabAdvanced(props.video, userContentOwners, userPermissions),
    },
    {
      name: 'versions',
      dataId: 'versions',
      label: 'Versions',
      content: (
        <TabVersions
          videoId={props.video.uid}
          accessControlSites={props.video?.access?.sites?.map((site) => `${site.id}`)}
        />
      ),
      show: canShowTabVideoVersions,
    },
  ].filter((item) => item.show);

  const getTabIndexByName = (tabName) => tabs.findIndex((item) => item.name === tabName);

  useEffect(() => {
    const hasPlatformByName = (platform) =>
      publishEntries?.map((publishEntry) => publishEntry.platform).includes(platform);

    const hasYoutube = hasPlatformByName(PLATFORM_YOUTUBE);
    const hasFacebook = hasPlatformByName(PLATFORM_FACEBOOK);

    let platform = '';
    if (hasYoutube) {
      platform = PLATFORM_YOUTUBE;
    } else if (hasFacebook) {
      platform = PLATFORM_FACEBOOK;
    }

    setPublishEntriesPlatform(platform);
  }, [publishEntries]);

  useEffect(() => {
    dispatch(selectedVideoAction(props.video));
    dispatch(loadLanguagesAction());

    if (props.video.status === VIDEO_STATE_PROCESSING) {
      dispatch(monitoringJobAction());
    }

    if (
      props.video.status !== VIDEO_STATE_PROCESSING &&
      isInsightsMode &&
      canEditVideoByAccessControl(props.video, userPublisherIds, userId)
    ) {
      dispatch(setTabIndexAction(getTabIndexByName('insights')));
    }

    dispatch(getSpeechToTextModelsAction());

    setIsWPVideoMode(getIsWPVideoMode());
  }, []);

  useEffect(() => () => dispatch(clearAction()), []);

  useEffect(() => {
    dispatch(monitoringAction(true));
  }, [props.video.uid]);

  const isDisabledButton =
    !props.canAddToPlaylist ||
    ![VIDEO_STATE_ACTIVE, VIDEO_STATE_PROCESSING].find((status) => props.video.status === status);

  const selectedVideoContentOwner = useMemo(
    () => getOwnerAutocompleteValue(props.video, userPermissions),
    [props.video, userPermissions],
  );

  const videoContentOwners = useMemo(() => {
    const owners = [...(ownersOptions || [])];

    if (
      selectedVideoContentOwner &&
      !owners.some((sourceOwners) => sourceOwners.label === selectedVideoContentOwner.label)
    ) {
      owners.push(selectedVideoContentOwner);
    }

    return owners;
  }, [ownersOptions, selectedVideoContentOwner]);

  return (
    <article data-id="editorial-video-editorial" data-distribution-id={props.video.distributionId}>
      {/* This need because we don't want to apply new uikit theme to menu */}
      <div className={styles.NewCardPosition}>
        {!isWPVideoMode && !props.video?.sponsored?.sponsored && props.playlistMode === MODE_PLAYLIST && (
          <Stack justifyContent="center" alignItems="center" className={styles.DragSign}>
            <DragIndicator fontSize="medium" htmlColor="shades.400" />
          </Stack>
        )}
        <Grid container className={styles.NewCardWrapper}>
          <Grid className={styles.NewCardWrapperVideoContainer}>
            <div className={styles.NewCardThumbnailContainer}>
              <VideoPlayer
                videoUrl={props.video.videoUrl}
                poster={thumbnailUrl}
                onTimeUpdate={(value) => dispatch(currentVideoTimeAction(value))}
                shouldPause={!!aiworkbench}
              />
              <Stack spacing={1} direction="row" alignItems="center" className={styles.StatusContainer}>
                <StatusBlockComponent
                  playbackImmediately={props.video.playbackImmediately}
                  status={props.video.status}
                  isSponsored={!!props.video?.sponsored?.sponsored}
                />
              </Stack>
            </div>

            <Stack spacing={1} fullWidth direction="column" alignItems="stretch" className={styles.NewCardInfo}>
              <Stack direction="row" alignItems="center" fullWidth>
                <div className={styles.VideoTitle}>
                  <InlineEditTextField
                    variant="h6Alt"
                    rows={1}
                    placeholder="Add video title"
                    textPlaceholder="Add video title"
                    value={props.video.name}
                    maxLength={maxLength.TITLE}
                    error={isErrorMessageOpen}
                    readOnly={!canEditVideoName}
                    onApply={(event, value) => {
                      if (props.video.name !== value) {
                        if (publishEntriesPlatform && value.length > MAX_LENGTH_VIDEO_NAME) {
                          handleTruncateVideoName(value);
                          setErrorMessageOpen(true);
                          event.preventDefault();
                        } else {
                          dispatch(
                            updateVideoAction({
                              name: value,
                            }),
                          );
                        }
                      }
                    }}
                  />
                </div>
                <Stack direction="row" spacing={1} alignItems="center" className={styles.Controls}>
                  {canSeeMenu && (
                    <Button
                      variant="contained"
                      size="xSmall"
                      shape="rounded"
                      color="secondary"
                      startIcon={<AutoAwesome />}
                      onClick={(e) => {
                        dispatch(
                          addQueriesAction({
                            videoId: props.video.uid,
                            aiworkbench: MODULE_CHAPTERS,
                          }),
                        );

                        dispatch(
                          initAiWorkbenchAction({
                            prevVideoIdInQuery: router.query.videoId,
                            videoId: props.video.uid,
                          }),
                        );

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

                  {showEmbedButton && !isMobileApp && hasPermission(VIDEO_EMBED, userPermissions) && (
                    <div>
                      <IconButton size="xSmall" color="neutral" onClick={props.openEmbedPopup}>
                        <CodeRounded />
                      </IconButton>
                    </div>
                  )}

                  {canSeeMenu &&
                    (canShare(props.video, userPublisherIds, userId) ||
                      canChangeAccess(props.video, userId, userPermissions)) &&
                    ![VIDEO_STATE_PROCESSING, VIDEO_STATE_FAILED].includes(props.video.status) && (
                      <div>
                        <IconButton size="xSmall" color="neutral" onClick={props.openShareAndAccess}>
                          <PersonAddAltOutlined />
                        </IconButton>
                      </div>
                    )}
                  {!isWPVideoMode && !props.video?.sponsored?.sponsored && props.playlistMode === MODE_PLAYLIST && (
                    <div>
                      <IconButton
                        size="xSmall"
                        color="neutral"
                        disabled={isDisabledButton}
                        onClick={props.addToPlaylistAction}
                      >
                        <PlaylistAddRounded />
                      </IconButton>
                    </div>
                  )}
                  {canSeeMenu && !isMobileApp && (
                    <EditorialMenu
                      shouldOpenVideoMenuImmediately={shouldOpenVideoMenuImmediately}
                      contentOwner={props.video.contentOwner}
                      onDeleteClick={handleDeleteVideo}
                      onArchiveClick={handleArchiveVideoClick}
                      onEvergreenSet={handleVideoEverGreenChange}
                      videoTitle={props.video.name}
                      evergreen={props.video.evergreen}
                      notes={props.video.notes}
                      handleNotesChange={handleNotesChange}
                      onPublish={setPublishOpen}
                      videoId={props.video.uid}
                      videoAccess={props.video.access}
                      canArchive={canArchive(props.video, userContentOwners, userPermissions)}
                      canShare={canShare(props.video, userPublisherIds, userId)}
                      canChangeAccess={canChangeAccess(props.video, userId, userPermissions)}
                      canEditVideo={!props.video.videoParent && canShowTrim(props.video, userId, userPermissions)}
                      canOperateWithVideoVersionUpload={canOperateWithVideoVersionUpload}
                      openShareAndAccess={props.openShareAndAccess}
                      videoStatus={props.video.status}
                    />
                  )}
                </Stack>
              </Stack>
              <Stack spacing={1} className={styles.VideoDataWrapper}>
                <Stack
                  direction="row"
                  flexWrap="wrap"
                  spacing={theme.spacing(0, 2)}
                  className={styles.VideoDataContent}
                  alignItems="flex-start"
                >
                  <div>
                    <InlineEditDateTimePicker
                      variant="caption"
                      readOnly={!canEditVideoDate}
                      value={props.video.videoCreationDate ? dayjs(props.video.videoCreationDate) : null}
                      minDate={dayjs(new Date(0))}
                      maxDate={dayjs().endOf('day')}
                      onChange={(date) => handleVideoDateChange(date.toDate())}
                      onApply={(date) => handleVideoDateChange(date.toDate())}
                      placeholder="Select Date"
                    />
                  </div>
                  <div>
                    <AccessControlView
                      access={props.video.access}
                      showListOfSitePopup={props.showListOfSitePopup}
                      setShowListOfSitePopup={props.setShowListOfSitePopup}
                      showListOfUserPopup={props.showListOfUserPopup}
                      setShowListOfUserPopup={props.setShowListOfUserPopup}
                    />
                  </div>
                  <div className={styles.Owners}>
                    <InlineEditAutocomplete
                      variant="caption"
                      defaultValue={selectedVideoContentOwner}
                      options={videoContentOwners}
                      filterOptions={(options) => options}
                      optionLabelKey="label"
                      optionValueKey="label"
                      placeholder="Choose owner"
                      readOnly={!canEditVideoSource}
                      onInputChange={(event, searchText) => dispatch(getOwnersOptionsAction(searchText))}
                      onOpen={() => dispatch(getOwnersOptionsAction(''))}
                      onChange={(event, owner) => handleOwnerChange(owner)}
                    />
                  </div>
                </Stack>
                <div className={styles.VideoDescription}>
                  <InlineEditTextField
                    variant="body2"
                    rows={4}
                    minRows={4}
                    placeholder="No description yet..."
                    textPlaceholder="No description yet..."
                    value={props.video.plot || ''}
                    readOnly={!canEditVideoDescription}
                    onApply={(event, value) => {
                      if (props.video.plot !== value) {
                        dispatch(updateVideoAction({ plot: value }));
                      }
                    }}
                  />
                </div>
              </Stack>
              <Tags
                isEditable={canEditTagsAndLabels}
                size="wide"
                video={props.video}
                onClickEdit={() => props.setShowTagsEditor(true)}
              />
            </Stack>
          </Grid>
        </Grid>
      </div>

      {canSeeMenu && (
        <div className={styles.Media}>
          <Stack spacing={4} justifyContent="space-between" alignItems="center" direction="row">
            <Tabs
              size="medium"
              value={tabs[tabIndex] ? tabIndex : 0}
              onChange={(e, value) => dispatch(setTabIndexAction(value))}
              className={styles.VideoTabs}
            >
              {tabs.map((item) => (
                <Tab key={item.label} data-id={item.dataId} label={item.label} />
              ))}
            </Tabs>
          </Stack>
          <Grid container className={styles.Assets}>
            <Grid item xs={12}>
              {tabs.map((item, index) => (
                <TabContent
                  id={index}
                  key={item.name}
                  renderHiddenContent={false}
                  selectedId={tabs[tabIndex] ? tabIndex : 0}
                >
                  {item.content}
                </TabContent>
              ))}
            </Grid>
          </Grid>
        </div>
      )}

      {isPublishOpen && (
        <PublishDialog
          isErrorMessageOpen={isErrorMessageOpen}
          video={props.video}
          checkedYoutubePublished={publishEntriesPlatform}
          setDialogOpen={setPublishOpen}
          setErrorMessageOpen={setErrorMessageOpen}
          setEditableFieldId={() => null}
          videoName={videoName}
          setVideoName={setVideoName}
          onTruncateVideoName={handleTruncateVideoName}
          onSubmitVideoName={handlePopupVideoNameChange}
        />
      )}

      {isErrorMessageOpen && (
        <PublishNameEditConfirm
          open={isErrorMessageOpen}
          videoName={videoName}
          maxLengthVideoName={MAX_LENGTH_VIDEO_NAME}
          setVideoName={setVideoName}
          setErrorMessageOpen={setErrorMessageOpen}
          checkedYoutubePublished={publishEntriesPlatform}
          content={`Video name exceeds max length permitted 
               on ${publishEntriesPlatform === PLATFORM_YOUTUBE ? 'Youtube' : 'Facebook'}, please edit name`}
          handlePublishVideoName={() => {
            handlePopupVideoNameChange(videoName);
            setErrorMessageOpen(false);
          }}
        />
      )}

      {dialogVisible && (
        <Dialog open={!!dialogVisible} onClose={handleDialogClose} maxWidth="md">
          <DialogTitle onClose={handleDialogClose}>Archive Video Confirmation</DialogTitle>
          <DialogContent>The video will be archived. Are you sure you would like to proceed?</DialogContent>
          <DialogActions>
            <Button size="small" variant="outlined" color="primary" onClick={handleDialogClose}>
              Cancel
            </Button>
            <Button size="small" variant="contained" color="primary" onClick={handleArchiveConfirm}>
              Archive
            </Button>
          </DialogActions>
        </Dialog>
      )}
      {/* Prevent drag'n'drop for modal  */}
      <div onPointerDown={(e) => e.stopPropagation()}>
        <TrimVideo video={props.video} />
        {props.isTagsEditorOpened && (
          <TagEditor
            isOpen={props.isTagsEditorOpened}
            isEditable={canEditTagsAndLabels}
            excludeSystemTagsCategory={['TEXT']}
            accountId={props.video.accountId}
            systemTags={tags || []}
            customTags={props.video.label || []}
            onChangeSystemTag={(systemTags) => handleOnChangeSystemTags(systemTags)}
            onChangeCustomTags={(customTags) => handleVideoLabelChange(customTags)}
            onClose={() => props.setShowTagsEditor(false)}
          />
        )}
      </div>
    </article>
  );
}

EditorialVideoDetails.propTypes = {
  canAddToPlaylist: PropTypes.bool.isRequired,
  showListOfSitePopup: PropTypes.bool.isRequired,
  setShowListOfSitePopup: PropTypes.func.isRequired,
  showListOfUserPopup: PropTypes.bool.isRequired,
  setShowListOfUserPopup: PropTypes.func.isRequired,
  openEmbedPopup: PropTypes.func.isRequired,
  openShareAndAccess: PropTypes.func.isRequired,
  searchFilters: PropTypes.shape({}).isRequired,
  showEmbedButton: PropTypes.bool,
  video: PropTypes.shape({
    uid: PropTypes.string,
    distributionId: PropTypes.string,
    thumbnailUrl: PropTypes.string,
    thumbnailFiles: PropTypes.arrayOf(PropTypes.shape({})),
    lang: PropTypes.arrayOf(PropTypes.string),
    name: PropTypes.string,
    plot: PropTypes.string,
    label: PropTypes.string,
    refId: PropTypes.string,
    notes: PropTypes.string,
    contentOwner: PropTypes.number,
    accountId: PropTypes.number,
    videoParent: PropTypes.string,
    iab: PropTypes.arrayOf(PropTypes.shape({})),
    videoFiles: PropTypes.arrayOf(PropTypes.shape({})),
    videoUrl: PropTypes.string,
    sourceVideoFile: PropTypes.shape({}),
    videoFileHls: PropTypes.shape({}),
    status: PropTypes.string,
    playbackImmediately: PropTypes.bool,
    videoCreationDate: PropTypes.number,
    evergreen: PropTypes.bool,
    mediaPlatformPerformance: PropTypes.shape({}),
    videoLength: PropTypes.number,
    performance: PropTypes.PropTypes.shape({}),
    feedDescription: PropTypes.string,
    access: PropTypes.shape({
      sites: PropTypes.arrayOf(PropTypes.string),
    }),
    approval: PropTypes.shape({
      status: PropTypes.string,
    }),
    highlights: PropTypes.string,
    highlightsPublished: PropTypes.bool,
    slides: PropTypes.string,
    slidesPublished: PropTypes.bool,
    sponsored: {
      sponsored: PropTypes.bool,
    },
  }).isRequired,
  videos: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
  isInsightsMode: PropTypes.bool,
  playlistMode: PropTypes.string.isRequired,
  shouldOpenVideoMenuImmediately: PropTypes.bool,
  isTagsEditorOpened: PropTypes.bool.isRequired,
  addToPlaylistAction: PropTypes.func.isRequired,
  videosAction: PropTypes.func.isRequired,
  setShowTagsEditor: PropTypes.func.isRequired,
};

export default EditorialVideoDetails;
