import { HttpStatusCode } from "axios";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";
import { z } from "zod";

import { MemberModel } from "@/contracts/client.schemas";
import { UserModel } from "@/models/UserModel";

import { Card, ErrorContext } from "../../../common/components/card/Card";
import { CardField } from "../../../common/components/card/CardField";
import { TableStateResponse } from "../../../common/models/TableStateResponse";
import { ZERO_ID } from "../../../constants";
import { KeyValue } from "../../../models/KeyValue";
import { http } from "../../../services/http.service";

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 fetchOptions = async (): Promise<KeyValue[]> => {
		const allUsers = (
			await http.get<TableStateResponse<UserModel>>("/api/users", {
				params: { role: "User" },
			})
		).items;

		return allUsers.map((user: UserModel) => {
			return {
				key: user.id,
				value: user.username,
			};
		});
	};

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

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

	const fields: CardField<MemberModel>[] = [
		{
			name: "userId",
			title: "User",
			type: "select",
			loadOptions: fetchOptions,
		},
	];

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

		return false;
	};

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/members"
			createTitle="Добавление участника"
			editTitle="Редактирование участника"
			viewTitle="Карточка участника"
			validationSchema={validationSchema}
			onError={handleError}
			filters={{
				organizationId,
			}}
			notificationMethodPrefix="MEMBERS"
			getModelTitle={(x) => x.username}
			canRemove={true}
			// noCard={{
			// 	condition: options.length === 0,
			// 	element: (
			// 		<Centroid>
			// 			<Typography variant="h5">
			// 				No allowed members in the system
			// 			</Typography>
			// 		</Centroid>
			// 	),
			// }}
		/>
	);
};
