import { getHSEnv, getHubID, getHublet } from '@hubspot/cms-components';
import {
  TranslationsProvider,
  useVideo,
  VideoFetchProvider,
  VideoPlayer,
  VideoPlayerProvider,
} from '@hubspot/video-player-core';

import TrackHSVideoAnalytics from '../TrackHSVideoAnalytics.js';
import { HSVideoIslandProps } from '../types.js';

const HSVideoIsland = ({
  video,
  hubspotVideoParams,
  playButtonColor,
}: HSVideoIslandProps) => {
  const portalId = getHubID();
  const hsEnv = getHSEnv();
  const hublet = getHublet();
  const {
    video: clientFetchedVideo,
    fetchError: videoFetchError,
    refetch,
  } = useVideo(
    hubspotVideoParams.player_id,
    portalId,
    hsEnv,
    hublet,
    Boolean(video)
  );
  const resolvedVideo = video || clientFetchedVideo;

  return (
    <TranslationsProvider translations={{}} language="en">
      <VideoFetchProvider
        env={hsEnv}
        hublet={hublet}
        videoId={hubspotVideoParams.player_id}
        video={resolvedVideo}
        videoFetchError={videoFetchError}
        hubspotVideoParams={{
          ...hubspotVideoParams,
          size_type: 'auto_full_width',
        }}
        onRefetch={refetch}
      >
        <VideoPlayerProvider video={resolvedVideo}>
          <VideoPlayer
            portalId={portalId}
            playButtonColor={{ color: playButtonColor?.color }}
            theme="DARK"
          />
          {resolvedVideo && (
            <TrackHSVideoAnalytics video={resolvedVideo} portalId={portalId} />
          )}
        </VideoPlayerProvider>
      </VideoFetchProvider>
    </TranslationsProvider>
  );
};

export default HSVideoIsland;
