import * as React from 'react';
import { useRef, forwardRef, useContext, useMemo, CSSProperties, RefObject } from 'react';
import { style } from 'typestyle';
import { StoreContext } from '../../../../services/store';
import useVideoControls from '../../../../hooks/useVideoControls';
import ImageContent from './ImageContent';
import VideoContent from './VideoContent';

interface ContentProps {
  autoplay?: boolean;
  /** Overlays a mute/unmute button on the video. */
  showMuteButton?: boolean;
  /** Shows the video duration progress bar while playing. */
  showDurationBar?: boolean;
  /** Renders the username pill at the top-left. */
  showUsernamePill?: boolean;
}

const useContentControls = (
  video: string | null,
  imgRef: RefObject<HTMLImageElement>,
  autoplay: boolean,
  forcedMuted: boolean,
) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const videoControls = useVideoControls(videoRef, video || '', autoplay, forcedMuted);

  return {
    videoRef,
    videoControls: video ? videoControls : null,
  };
};

const Content = forwardRef<HTMLDivElement, ContentProps>((
  { autoplay = false, showMuteButton = false, showDurationBar = false, showUsernamePill = false },
  contentRef,
) => {
  const context = useContext(StoreContext);
  const { image, video, post, username, source, isMuted: isForceMuted } = context.post!;

  const imgRef = useRef<HTMLImageElement>(null);
  const { videoRef, videoControls } = useContentControls(
    video ?? null,
    imgRef,
    autoplay,
    !!isForceMuted,
  );

  const contentClass = useMemo(
    () =>
      context.isMobile
        ? style({ width: '100%', height: '100%' })
        : style({ display: 'flex', flex: 1 }),
    [context.isMobile],
  );

  return (
    <div
      style={styles.container(context.isMobile)}
      className={`${context.config.classPrefix}-postviewer-content`}
      aria-label={video ? undefined : `${source} content created by ${username}.`}
      role={video ? undefined : 'region'}
      ref={contentRef}
    >
      {video && videoControls ? (
        <VideoContent
          video={video}
          pause={videoControls.isPaused}
          onPause={videoControls.pauseVideo}
          onPlay={videoControls.playVideo}
          videoRef={videoRef}
          contentClass={contentClass}
          source={source}
          username={username}
          isMuted={showMuteButton || isForceMuted ? videoControls.isMuted : undefined}
          toggleMute={
            showMuteButton && !isForceMuted ? videoControls.toggleMute : undefined
          }
          showDurationBar={showDurationBar}
          showUsernamePill={showUsernamePill}
        />
      ) : (
        image ? (
          <ImageContent
            image={image}
            post={post}
            source={source}
            contentClass={contentClass}
            showUsernamePill={showUsernamePill || context.data.settings.display_name}
            imgRef={imgRef}
          />
        ) : null
      )}
    </div>
  );
});

const styles = {
  container: (isMobile: boolean): CSSProperties => ({
    position: 'relative',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    overflow: 'hidden',
    borderRadius: 'inherit',
    ...(isMobile && { height: '85vw' }),
    ...(!isMobile && { flex: 1 }),
  }),
};

export default Content;
