import {
	MediaCaptionsButton,
	MediaControlBar,
	MediaController,
	MediaFullscreenButton,
	MediaMuteButton,
	MediaPlayButton,
	MediaSeekBackwardButton,
	MediaSeekForwardButton,
	MediaTimeDisplay,
	MediaTimeRange,
	MediaVolumeRange,
} from "media-chrome/react";
import { useMemo } from "react";
import ReactPlayer from "react-player";
import { PlayerErrorState } from "@/components/player/states/PlayerErrorState";
import { PlayerLoadingState } from "@/components/player/states/PlayerLoadingState";
import { detectCodecSupport } from "@/utils/codec-detection";
import { usePlaybackSession } from "./hooks/usePlaybackSession";

type SelectedTracks = {
	audio?: number;
	subtitle?: number;
};

interface HLSPlayerProps {
	titleId: string;
	episodeId?: string;
	selectedTracks?: SelectedTracks;
}

export function HLSPlayer({
	titleId,
	episodeId,
	selectedTracks,
}: HLSPlayerProps) {
	const supportedCodecs = useMemo(() => detectCodecSupport(), []);

	const { isLoading, isError, data, error } = usePlaybackSession({
		titleId,
		episodeId,
		supportedCodecs,
		selectedTracks,
	});

	if (isLoading) {
		return <PlayerLoadingState />;
	}

	if (isError) {
		return <PlayerErrorState error={new Error(error.message)} />;
	}

	if (!data) {
		return <PlayerLoadingState />;
	}

	return (
		<MediaController
			style={{
				width: "100%",
				aspectRatio: "16/9",
			}}
		>
			<ReactPlayer
				slot="media"
				src={data.playlistUrl}
				config={{
					hls: {
						enableWorker: true,
						startPosition: 0,
					},
				}}
				controls={false}
				style={{
					width: "100%",
					height: "100%",
					// "--controls": "none",
				}}
			/>
			<MediaControlBar>
				<MediaPlayButton />
				<MediaSeekBackwardButton seekOffset={10} />
				<MediaSeekForwardButton seekOffset={10} />
				<MediaTimeRange />
				<MediaTimeDisplay showDuration />
				<MediaMuteButton />
				<MediaVolumeRange />
				<MediaCaptionsButton />
				<MediaFullscreenButton />
			</MediaControlBar>
		</MediaController>
	);
}
