// import { Card, CardField } from "../../../common/components/Card";
import { PeopleOutlined } from "@mui/icons-material";
import { Typography } from "@mui/material";
import { HttpStatusCode } from "axios";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { z } from "zod";

import { CardField } from "@/common/components/card/CardField";
import { OrganizationModel } from "@/contracts/client.schemas";

import { Card, ErrorContext } from "../../../common/components/card/Card";
import { CardAction } from "../../../common/models/card-action";
import {
	MAX_NAME_LENGTH,
	MAX_TEXT_LENGTH,
	MIN_NAME_LENGTH,
} from "../../../constants";

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

const fields: CardField<OrganizationModel>[] = [
	{
		name: "name",
		title: "Name",
	},
	{
		name: "description",
		title: "Description",
	},
];

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

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

export const OrganizationCardPage = () => {
	const navigate = useNavigate();

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

	const handleError = (response: ErrorContext) => {
		if (response.status === HttpStatusCode.Conflict) {
			toast.error("The same organization is already in the system");
			return true;
		}

		return false;
	};

	const extraActions: CardAction<OrganizationModel>[] = [
		{
			title: "Members",
			color: "secondary",
			variant: "outlined",
			icon: <PeopleOutlined />,
			action: async (model: OrganizationModel) => {
				navigate("./members", { relative: "path" });

				return model;
			},
		},
	];

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/organizations"
			createTitle="Добавление организации"
			editTitle="Редактирование организации"
			viewTitle="Карточка организации"
			validationSchema={validationSchema}
			extraTitle={extraTitle}
			onError={handleError}
			extraActions={extraActions}
			notificationMethodPrefix="ORGANIZATIONS"
			getModelTitle={(x) => x.name}
			canEdit={true}
			canRemove={true}
		/>
	);
};
