import { useContext, useEffect, useMemo, useRef } from 'react';
import useDarkMode from '../../hooks/useDarkMode';
import ThemeContext from '../../contexts/themeContext';

import VideoJS from './index'

interface IVideojsPlayerComponentProps {
  selectedLink: string,
  type: string,
  onFeedStatusChange?: (status: 'checking' | 'healthy' | 'unavailable', message?: string) => void
};

const VideojsPlayerComponent = (props: IVideojsPlayerComponentProps) => {

	const { mobileDesign } = useContext(ThemeContext);
  const { themeStatus } = useDarkMode();


  /////////////////////////////////////////////////

  const playerRef = useRef(null);
  const lastStatusRef = useRef<{ status: 'checking' | 'healthy' | 'unavailable'; message?: string }>();

  const videoJsOptions = useMemo(() => ({
    autoplay: true,
    controls: true,
    responsive: true,
    fluid: true,
    bigPlayButton: false,
    sources: [{
      src: props.selectedLink,
      type: props.type,
    }],
  }), [props.selectedLink, props.type]);

  useEffect(() => {
    lastStatusRef.current = undefined;
  }, [props.selectedLink, props.type]);

  const reportStatus = (status: 'checking' | 'healthy' | 'unavailable', message?: string) => {
    if (
      lastStatusRef.current?.status === status
      && lastStatusRef.current?.message === message
    ) {
      return;
    }

    lastStatusRef.current = { status, message };
    props.onFeedStatusChange?.(status, message);
  };

  const handlePlayerReady = (player: any) => {
    playerRef.current = player;

    // You can handle player events here, for example:
    player.on('loadstart', () => {
      reportStatus('checking');
    });

    player.on('canplay', () => {
      reportStatus('healthy');
    });

    player.on('playing', () => {
      reportStatus('healthy');
    });

    player.on('error', () => {
      const playerError = player.error();
      const code = playerError?.code;

      let message = 'Translation feed not yet available. Please select another language.';

      if (code === 4) {
        message = 'This translator stream format is currently not playable. Please select another language.';
      } else if (code === 2) {
        message = 'Network issue while loading this translator feed. Please try another language.';
      }

      reportStatus('unavailable', message);
    });

    player.on('waiting', () => {
      reportStatus('checking');
    });

    player.on('dispose', () => {
      //videojs.log('player will dispose');
    });
  };


	return (
      <div className=''>
        <VideoJS options={videoJsOptions} onReady={handlePlayerReady} />
      </div>
	);
};

export default VideojsPlayerComponent;
