import { LockOpenOutlined } from "@mui/icons-material";
import { HttpStatusCode } from "axios";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { z } from "zod";

import { Card, ErrorContext } from "@/common/components/card/Card";
import { CardField } from "@/common/components/card/CardField";
import { CardAction } from "@/common/models/card-action";
import { ZERO_ID } from "@/constants";
import { MemberModel } from "@/contracts/client.schemas";

const validationSchema = z.object({
	userId: z
		.string({
			required_error: "User is required",
			invalid_type_error: "User must be a string",
		})
		.refine((value) => value !== ZERO_ID, { message: "User is required" }),
});

export const MemberCardPage = () => {
	const { organizationId } = useParams();
	const navigate = useNavigate();

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

	const defaultValue: MemberModel = {
		id: ZERO_ID,
		userId: ZERO_ID,
		organizationId,
		username: "",
	};

	const fields: CardField<MemberModel>[] = [
		{
			name: "username",
			title: "Username",
		},
	];

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

		return false;
	};

	const extraActions: CardAction<MemberModel>[] = [
		{
			icon: <LockOpenOutlined />,
			title: "Accesses",
			action: async (model) => {
				navigate("./accesses", { relative: "path" });

				return model;
			},
		},
	];

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/members"
			viewTitle="Карточка участника"
			validationSchema={validationSchema}
			onError={handleError}
			filters={{
				organizationId,
			}}
			notificationMethodPrefix="MEMBERS"
			getModelTitle={(x) => x.username}
			extraActions={extraActions}
		/>
	);
};
