import { FC, useState } from "react";
import { useTranslation } from "react-i18next";

export interface VideoPlayerProps {
	/** URL видео потока */
	src: string;
	/** Название камеры для отображения */
	name?: string;
	/** Статус камеры (онлайн/оффлайн) */
	isOnline?: boolean;
	/** Ширина компонента */
	width?: string | number;
	/** Высота компонента */
	height?: string | number;
	/** Автоматическое воспроизведение */
	autoPlay?: boolean;
	/** Показывать контролы */
	controls?: boolean;
	/** Приглушенный звук */
	muted?: boolean;
	/** Воспроизведение встроенного видео */
	playsInline?: boolean;
	/** Дополнительные CSS классы */
	className?: string;
}

export const VideoPlayer: FC<VideoPlayerProps> = ({
	src,
	name,
	isOnline = true,
	width = "100%",
	height = "100%",
	autoPlay = true,
	controls = false,
	muted = true,
	playsInline = true,
	className = "",
}) => {
	const { t } = useTranslation("translation");
	const [connectionError, setConnectionError] = useState<string | null>(null);

	const handleLoadStart = () => {
		setConnectionError(null);
	};

	const handleCanPlayThrough = () => {
		setConnectionError(null);
	};

	const handleError = (e: React.SyntheticEvent<HTMLVideoElement, Event>) => {
		const target = e.target as HTMLVideoElement;
		let errorMessage = t("cameraConnectionError");

		if (target.error) {
			switch (target.error.code) {
				case MediaError.MEDIA_ERR_NETWORK:
					errorMessage = t("cameraNetworkError");
					break;
				case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
					errorMessage = t("cameraFormatError");
					break;
				case MediaError.MEDIA_ERR_ABORTED:
					errorMessage = t("cameraConnectionAborted");
					break;
				default:
					errorMessage = t("cameraConnectionError");
			}
		}

		setConnectionError(errorMessage);
	};

	const handleRetry = () => {
		setConnectionError(null);
		const video = document.querySelector(`video[src="${src}"]`) as HTMLVideoElement;
		if (video) {
			video.load();
			video.play().catch(() => {});
		}
	};

	if (!src) {
		return (
			<div
				className={`bg-gray-100 rounded-lg flex items-center justify-center ${className}`}
				style={{ width, height }}
			>
				<div className="text-center text-gray-500">
					<div className="text-4xl mb-2">📷</div>
					<div className="text-sm">{t("noVideoUrl")}</div>
				</div>
			</div>
		);
	}

	if (!isOnline) {
		return (
			<div
				className={`bg-black rounded-lg flex items-center justify-center relative overflow-hidden ${className}`}
				style={{ width, height }}
			>
				<div className="text-center text-gray-400">
					<div className="text-6xl mb-2">📷</div>
					<div className="text-sm">{name || t("cameraOffline")}</div>
					<div className="absolute top-2 right-2 w-3 h-3 bg-red-500 rounded-full"></div>
				</div>
			</div>
		);
	}

	return (
		<div
			className={`bg-black rounded-lg relative overflow-hidden ${className}`}
			style={{ width, height }}
		>
			<video
				className="w-full h-full object-cover rounded-lg"
				autoPlay={autoPlay}
				muted={muted}
				playsInline={playsInline}
				controls={controls}
				style={{
					width: "100%",
					height: "100%",
					objectFit: "cover",
					borderRadius: "inherit",
				}}
				src={src}
				onLoadStart={handleLoadStart}
				onCanPlayThrough={handleCanPlayThrough}
				onError={handleError}
			/>

			{/* Сообщение об ошибке подключения */}
			{connectionError && (
				<div className="absolute inset-0 bg-black bg-opacity-75 flex items-center justify-center rounded-lg">
					<div className="text-center text-white p-4">
						<div className="text-4xl mb-2">⚠️</div>
						<div className="text-sm font-medium mb-2">
							{connectionError}
						</div>
						<button
							onClick={handleRetry}
							className="px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors"
						>
							{t("retry")}
						</button>
					</div>
				</div>
			)}

			{/* Индикатор статуса камеры */}
			<div className="absolute top-2 right-2 w-3 h-3 bg-green-500 rounded-full"></div>
		</div>
	);
};
