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

import { PhotoModel } from "@/contracts/client.schemas";

import { Card } from "../../../common/components/card/Card";
import { ImagePickerCardField } from "../../../common/components/card/card-fields/ImagePickerCardField";
import { CardField } from "../../../common/components/card/CardField";
import { MAX_NAME_LENGTH, MAX_TEXT_LENGTH } from "../../../constants";

const fields: CardField<PhotoModel>[] = [
	{
		name: "name",
		title: "Name",
		required: true,
	},
	{
		name: "description",
		title: "description",
		required: true,
	},
	{
		name: "base64",
		title: "Image",
		component: ImagePickerCardField<PhotoModel>,
	},
];

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`,
		),

	base64: z.string({
		required_error: "Image is required",
		invalid_type_error: "Image must be a string",
	}),

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

export const PhotoCardPage = () => {
	const { assetId } = useParams();

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

	const defaultValue: PhotoModel = {
		id: "",
		name: "",
		description: "",
		base64: "",
		assetId: assetId,
	};

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

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/photos"
			createTitle="Adding photo"
			editTitle="Editing photo"
			viewTitle="Photo card"
			validationSchema={validationSchema}
			extraTitle={extraTitle}
			filters={{
				assetId,
			}}
			getModelTitle={(model) => model.name}
			notificationMethodPrefix="PHOTOS"
			canEdit={true}
			canRemove={true}
		/>
	);
};
