import React, { useEffect, useState } from 'react';
import className from 'clsx';
import { useRouter } from 'next/router';

import {
  EXTERNAL_PLAYER_CONFIG_KEY,
  MAP_CLOSED_CAPTIONS,
  MAP_MOBILE_FLOATING_THEME,
} from '@/modules/players/PlayerIframeView/constants';

import {
  getPlayerConfigCdnEndpoint,
  getPlayerEndpoint,
  getPlaylistApiEndpoint,
} from '@/modules/@common/PlayerWidget/helpers';

import DesktopWrapper from './components/DesktopWrapper/DesktopWrapper';
import MobileWrapper from './components/MobileWrapper/MobileWrapper';
import { Skeleton } from '@/mui/components';

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

const playerContainerId = 'player-container';

function PlayerPreview() {
  const [config, setConfig] = useState({});
  const router = useRouter();

  const options = router.query;

  const ITEM_HEIGHT = options.mobile ? 44 : 32;

  const Wrapper = options.mobile === 'true' ? MobileWrapper : DesktopWrapper;
  const shouldSetPlayerAdjustWidth =
    (options.mobile === 'true' &&
      config?.playerWidth_mobile === '100%' &&
      (config?.aspectratio_mobile === '9:16' || config?.aspectratio === '9:16')) ||
    (options.mobile === 'false' && config?.playerWidth === '100%' && config?.aspectratio === '9:16');

  const addConfigConstraints = () => {
    const { ac_lre_conf: conf } = window;
    const externalConf = window[EXTERNAL_PLAYER_CONFIG_KEY];

    return {
      ...conf,
      lre_playerLogo: {
        file: externalConf.logo,
        link: '',
        enabled: !!externalConf.logo,
      },
      playerWidth: /%/.test(externalConf.playerWidth)
        ? externalConf.playerWidth
        : parseInt(externalConf.playerWidth, 10),
      playerWidth_mobile: /%/.test(externalConf.playerWidthMobile)
        ? externalConf.playerWidthMobile
        : parseInt(externalConf.playerWidthMobile, 10),
      playlistLimit: externalConf.playlistLimit,
      loopPlaylist: externalConf.loopPlaylist,
      startWithSound: externalConf.startWithSound,
      publisherDomainId: externalConf.publisherDomainId,
      selfServe: externalConf.selfServe,
      allFeeds: externalConf.allFeeds,
      verticalFullscreenTitleTimelineVisibility: externalConf.verticalFullscreenTitleTimelineVisibility,
      swipeAnimation: externalConf.swipeAnimation,
      swipeAnimationMaxVisits: parseInt(externalConf.swipeAnimationMaxVisits, 10),
      swipeAnimationDuration: parseInt(externalConf.swipeAnimationDuration, 10),
      fallbackPlaylist: externalConf.fallbackPlaylist,
      'auto-play-desktop': externalConf.autoplayDesktop,
      'auto-play-mobile': externalConf.autoplayMobile,
      displayAds: {
        ...conf.displayAds,
        enabled: externalConf.displayAdsEnabled,
        playAdsNotInView: externalConf.displayAdsPlayAdsNotInView,
        maxAdsPerClip: -1,
      },
      displayAdsForMobile: {
        ...conf.displayAdsForMobile,
        enabled: externalConf.displayAdsForMobileEnabled,
        playAdsNotInView: externalConf.displayAdsForMobilePlayAdsNotInView,
        maxAdsPerClip: -1,
      },
      lre_imaAds: {
        ...conf.lre_imaAds,
        adIndicator: externalConf.adIndicator,
        adIndicatorText: externalConf.adIndicatorText,
        playAdsOnLoopEnd: externalConf.playAdsOnLoopEnd,
        playAdsNotInView: externalConf.clipNotInViewPlayAdsDesktop,
        inviewAdInterval: externalConf.inviewAdInterval,
        notInviewAdInterval: externalConf.notInviewAdInterval,
        maxAdsPerClip: externalConf.maxAdsPerClip,
        adRequestDelay: externalConf.firstAdRequestDelay,
      },
      lre_imaAdsForMobile: {
        ...conf.lre_imaAdsForMobile,
        adIndicator: externalConf.adIndicator,
        adIndicatorText: externalConf.adIndicatorText,
        playAdsOnLoopEnd: externalConf.playAdsOnLoopEnd,
        playAdsNotInView: externalConf.clipNotInViewPlayAdsMobile,
        maxAdsPerClip: externalConf.maxAdsPerClip,
        adRequestDelay: externalConf.firstAdRequestDelay,
      },
      aspectratio: externalConf.aspectratio,
      aspectratio_mobile: externalConf.aspectratioMobile,
      branding: {
        ...conf.branding,
        enabled: !!externalConf.brandingLeftText || !!externalConf.brandingRigthText,
        leftText: externalConf.brandingLeftText || '', // Player Title
        rightText: externalConf.brandingRigthText || '', // Powered by AnyClip
      },
      // Player Controls
      advSettingsControl: {
        ...conf.advSettingsControl,
        resolutionPane: !!externalConf.resolutionPane, // Resolution Control
        speedPane: !!externalConf.speedPane, // Playback Speed
      },
      fullScreenButton: !!externalConf.fullScreenButton, // Full Screen
      chaptering: {
        ...conf.chaptering,
        menuListEnabled: !!externalConf.chapteringMenuListEnabled, // Chaptering
      },
      theaterModeButton: externalConf.theaterModeButton, // Theater Mode
      ffRewindDesktop: {
        ...conf.ffRewindDesktop,
        enabled: !!externalConf.ffRewind, // 10 Seconds Rewind
      },
      ffRewindMobile: {
        ...conf.ffRewindMobile,
        enabled: !!externalConf.ffRewind, // 10 Seconds Rewind
      },
      // Color & Size Customization
      customUI: {
        ...conf.customUI,
        leftBrandingColor: externalConf.leftBrandingColor,
        leftBrandingSize: `${externalConf.leftBrandingSize}px`,
        progressBarColor: externalConf.progressBarColor,
        timestampTooltipColor: externalConf.timestampTooltipColor,
        volumeBarColor: externalConf.volumeBarColor,
        settingsMenuHighlightColor: externalConf.settingsMenuHighlightColor,
      },
      // Floating
      floatingDesktop: {
        ...conf.floatingDesktop,
        closeButtonDelay: -1, // Don't show close button
        floatingDelay: externalConf.floatingDesktopDelay,
        floatingEnabled: externalConf.floatingDesktopEnabled,
        floatingMode: externalConf.floatingDesktopMode,
        floatingPosition: externalConf.floatingDesktopPosition,
        floatingReopenWait: 0,
        floatingWidth: externalConf.floatingDesktopWidth,
      },
      floatingMobile: {
        ...conf.floatingMobile,
        closeButtonDelay: -1, // Don't show close button
        floatingDelay: externalConf.floatingMobileDelay,
        floatingEnabled: externalConf.floatingMobileEnabled,
        floatingMargin: 0,
        floatingMode: externalConf.floatingMobileMode,
        floatingPosition: externalConf.floatingMobilePosition,
        floatingReopenWait: 0,
        floatingWidth: externalConf.floatingMobileWidth,
        floatingTheme:
          MAP_MOBILE_FLOATING_THEME[
            typeof externalConf.floatingMobileEnabled === 'number'
              ? externalConf.floatingMobileEnabled
              : externalConf.floatingMobileEnabledNumber
          ],
      },
      ampStickyBarMode: externalConf.ampStickyBarMode,
      lre_carouselEnabled: externalConf.carouselEnabled,
      lre_carouselEnabledMobile: externalConf.carouselEnabledMobile,
      carousel: {
        ...conf.carousel,
        type: externalConf.carouselOrientation,
      },
      xRayCampaignsEnabled: externalConf.xRayCampaignsEnabled,
      adServerDesktop: {
        ...conf.adServerDesktop,
        enabled: externalConf.adServerDesktopEnabled,
      },
      adServerMobile: {
        ...conf.adServerMobile,
        enabled: externalConf.adServerMobileEnabled,
      },
      lre_playlistType: externalConf.playlistType,
      shuffleFallback: externalConf.shuffleFallback,
      closedCaptions: {
        ...conf.closedCaptions,
        ...(externalConf.closedCaptions ? { state: MAP_CLOSED_CAPTIONS[externalConf.closedCaptions] } : {}),
      },
      socialIconsDesktop: {
        ...conf.socialIconsDesktop,
        enabled: !!externalConf.socialLikeButton || !!externalConf.socialViewButton,
        likeButton: !!externalConf.socialLikeButton,
        viewButton: !!externalConf.socialViewButton,
      },
      socialIconsMobile: {
        ...conf.socialIconsMobile,
        enabled: !!externalConf.socialLikeButton || !!externalConf.socialViewButton,
        likeButton: !!externalConf.socialLikeButton,
        viewButton: !!externalConf.socialViewButton,
      },
      lre_playlistApiEndpoint: getPlaylistApiEndpoint(),
    };
  };

  useEffect(() => {
    const playerContainer = document.getElementById(playerContainerId);

    if (window[EXTERNAL_PLAYER_CONFIG_KEY]) {
      const script$ = document.createElement('script');
      script$.src = getPlayerConfigCdnEndpoint(options.publisherName, options.widgetName);

      script$.addEventListener('load', () => {
        const configOverride = addConfigConstraints();
        window.ac_lre_conf_override = configOverride;
        setConfig(configOverride);

        const script = document.createElement('script');

        script.setAttribute('pubname', options.publisherName);
        script.setAttribute('widgetname', options.widgetName);
        script.setAttribute('data-ads', 'false');

        script.src = getPlayerEndpoint();

        playerContainer.appendChild(script);
      });

      playerContainer.appendChild(script$);
    }

    return () => {
      playerContainer.innerHTML = '';
    };
  }, []);

  return (
    <Wrapper>
      <Skeleton variant="rectangular" width="40%" height={ITEM_HEIGHT} animation={false} />
      <div
        id={playerContainerId}
        className={className(styles.Wrapper, { [styles.Wrapper___playerAdjustWidth]: shouldSetPlayerAdjustWidth })}
      />
      <Skeleton variant="rectangular" width="100%" height={ITEM_HEIGHT} animation={false} />
      <Skeleton variant="rectangular" width="100%" height={ITEM_HEIGHT} animation={false} />
      <Skeleton variant="rectangular" width="100%" height="100vh" animation={false} />
    </Wrapper>
  );
}

export default PlayerPreview;
