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

import { AccessModel, AssetGroupModel } from "@/contracts/client.schemas";

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";

export const AccessCardPage = () => {
	const { memberId } = useParams();
	const { t } = useTranslation();

	if (!memberId) {
		throw new Error("Member id is required");
	}

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

	const getOptions = async (): Promise<KeyValue[]> => {
		// const allAccesses = await get<TableStateResponse<AccessModel>>(
		// 	`/api/accesses?memberId=${model.memberId}`
		// ).then((x) => x.items);

		const allGroups = await http
			.get<TableStateResponse<AssetGroupModel>>("/api/asset-groups")
			.then((x) => x.items);

		return (
			allGroups
				// .filter((x) => !allAccesses.some((y) => y.assetGroupId === x.id))
				.map((x) => ({
					key: x.id,
					value: x.name,
				}))
		);
	};

	const defaultValue: AccessModel = {
		id: ZERO_ID,
		memberId,
		username: "",
		assetGroupId: ZERO_ID,
		assetGroupName: "",
	};

	const fields: CardField<AccessModel>[] = [
		{
			name: "assetGroupId",
			title: "Asset Group",
			type: "select",
			loadOptions: getOptions,
		},
	];

	const handleError = (error: ErrorContext) => {
		if (error.status === HttpStatusCode.NotFound) {
			if (error.errors.some((x) => x.code === "User")) {
				toast.error(t("User not found"));
				return true;
			}
		}
		if (error.status === HttpStatusCode.Conflict) {
			toast.error(t("The same access is already in the system"));
			return true;
		}

		return false;
	};

	return (
		<Card
			defaultValue={defaultValue}
			fields={fields}
			baseUrl="/api/accesses"
			viewTitle="Access to asset group"
			validationSchema={validationSchema}
			onError={handleError}
			filters={{
				memberId,
			}}
			notificationMethodPrefix="MEMBERS"
			getModelTitle={(x) => x.username}
			canRemove={true}
		/>
	);
};
