import { Typography } from "@mui/material";
import { useParams } from "react-router-dom";
import { z } from "zod";

import { Card } from "@/common/components/card/Card";
import { CardField } from "@/common/components/card/CardField";
import { MAX_NAME_LENGTH, MAX_TEXT_LENGTH } from "@/constants";
import { useCreateCamera } from "@/contracts/cameras";
import { CameraModel } from "@/contracts/client.schemas";
import { VideoPlayer } from "@/features/VideoPlayer";

const fields: CardField<CameraModel>[] = [
	{
		name: "name",
		title: "Name",
		required: true,
	},
	{
		name: "address",
		title: "URL",
		required: true,
	},
];

const validationSchema = z.object({
	name: z
		.string({
			required_error: "Name is required",
			invalid_type_error: "Name must be a string",
		})
		.min(3, "Name must be at least 3 characters")
		.max(
			MAX_NAME_LENGTH,
			`Name must be less than ${MAX_NAME_LENGTH} characters`,
		),

	address: z
		.string({
			required_error: "Address is required",
			invalid_type_error: "Address must be a string",
		})
		.url("Address must be a valid URL")
		.min(3, "Address must be at least 3 characters")
		.max(
			MAX_TEXT_LENGTH,
			`Address must be less than ${MAX_TEXT_LENGTH} characters`,
		),
});

export const CameraCardPage = () => {
	const { assetId } = useParams();
	const createApi = useCreateCamera();

	if (!assetId) {
		throw new Error("assetId is required");
	}

	const defaultValue: CameraModel = {
		id: "",
		name: "",
		address: "",
		assetId: "",
	};

	const extraTitle = (camera: CameraModel) => {
		return <Typography>{camera.name}</Typography>;
	};

	const renderVideoPreview = (camera: CameraModel) => {
		// Показываем предпросмотр только если есть URL и это не режим редактирования
		if (!camera.address) {
			return null;
		}

		return (
			<div className="mt-6">
				<h4 className="text-lg font-semibold mb-3">Video Preview</h4>
				<div className="w-full h-64 bg-gray-100 rounded-lg overflow-hidden">
					<VideoPlayer
						src={camera.address}
						name={camera.name}
						isOnline={true}
						width="100%"
						height="100%"
						autoPlay={false} // Не автозапуск в предпросмотре
						muted={true}
						playsInline={true}
						controls={true}
					/>
				</div>
			</div>
		);
	};

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/cameras"
			createTitle="Add camera"
			editTitle="Edit camera"
			viewTitle="View camera"
			validationSchema={validationSchema}
			extraTitle={extraTitle}
			filters={{
				assetId,
			}}
			getModelTitle={(model) => model.name}
			notificationMethodPrefix="CAMERAS"
			canEdit={true}
			canRemove={true}
			extraFields={renderVideoPreview}
		/>
	);
};
