"use client";
import { IYoutubeItem } from "@/interfaces/youtube";
import Image from "next/image";
import { useState } from "react";

export default function YouTubeEmbed({
	video,
	width = 424,
	height = 238,
	loadIframe = false,
	autoPlay = true,
}: {
	video: IYoutubeItem | string;
	width?: number | "full";
	height?: number | "full";
	loadIframe?: boolean;
	autoPlay?: boolean;
}) {
	const [isIframeLoaded, setIframeLoaded] = useState(loadIframe);

	const id =
		typeof video === "string"
			? video
			: typeof video.id === "string"
				? video.snippet.resourceId.videoId
				: video.id.videoId;

	const isString = typeof video === "string";

	const _loadIframe = () => setIframeLoaded(true);

	return (
		<div
			style={{
				width: width === "full" ? "100%" : `${width}px`,
				height: height === "full" ? "100%" : `${height}px`,
			}}
			className={`relative w-${width === "full" ? width : "[" + width + "px]"} h-${height === "full" ? height : "[" + height + "px]"} cursor-pointer`}
			onClick={_loadIframe}
		>
			{isIframeLoaded ? (
				<iframe
					className="rounded-md shadow-current aspect-video"
					width={width === "full" ? "100%" : width}
					height={height === "full" ? "100%" : height}
					src={`https://www.youtube-nocookie.com/embed/${id}?rel=0&modestbranding=1&autoplay=${autoPlay ? 1 : 0}`}
					title={
						isString ? "YouTube video player" : video.snippet.title
					}
					allow="accelerometer; autoplay; encrypted-media; gyroscope"
					allowFullScreen
				/>
			) : (
				<>
					{width === "full" || height === "full" ? (
						<img
							width="100%"
							height="100%"
							className="w-full h-full object-cover rounded-md shadow-current"
							src={`https://img.youtube.com/vi/${id}/hqdefault.jpg`}
							alt={
								isString
									? "YouTube video player"
									: video.snippet.title
							}
						/>
					) : (
						<Image
							width={width}
							height={height}
							className="w-full h-full object-cover rounded-md shadow-current"
							src={`https://img.youtube.com/vi/${id}/hqdefault.jpg`}
							alt={
								isString
									? "YouTube video player"
									: video.snippet.title
							}
						/>
					)}

					<button className="absolute top-[50%] left-[50%] -translate-x-[50%] -translate-y-[50%] text-white text-8xl cursor-pointer">
						▶
					</button>
				</>
			)}
		</div>
	);
}
