import { Typography } from "@mui/material";
import { HttpStatusCode } from "axios";
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 { UserModel } from "../../../models/UserModel";
import { Roles } from "../Roles";

const defaultValue: UserModel = {
	id: "",
	username: "",
	password: "",
	role: "",
};

const fields: CardField<UserModel>[] = [
	{
		name: "username",
		title: "Username",
	},
	{
		name: "password",
		title: "Password",
	},
	{
		name: "role",
		title: "Role",
		type: "select",
		loadOptions: () =>
			Promise.resolve(
				Roles.map((x) => ({
					key: x.id,
					value: x.name,
				}))
			),
	},
];

const validationSchema = z.object({
	username: z.string({
		required_error: "Username is required",
		invalid_type_error: "Username must be a string"
	}),
	password: z.string({
		required_error: "Password is required",
		invalid_type_error: "Password must be a string"
	}).nullable(),
	role: z.string({
		required_error: "Role is required",
		invalid_type_error: "Role must be a string"
	}),
});

export const UserCardPage = () => {
	const extraTitle = (application: UserModel) => {
		return <Typography>{application.username}</Typography>;
	};

	const handleError = (error: ErrorContext) => {
		if (
			error.status === HttpStatusCode.BadGateway &&
			error.errors.some((x) => x.code === "InvalidUserName")
		) {
			toast.error("User name is not valid");
			return true;
		}

		if (error.status === HttpStatusCode.Conflict) {
			toast.error("User with this name already exists");
			return true;
		}

		return false;
	};

	return (
		<Card
			baseUrl="/api/users"
			defaultValue={defaultValue}
			fields={fields}
			extraTitle={extraTitle}
			validationSchema={validationSchema}
			notificationMethodPrefix="USERS"
			getModelTitle={(x) => x.username}
			onError={handleError}
			canEdit={true}
			canRemove={true}
		/>
	);
};
