import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { z } from "zod";

import { Card } from "@/common/components/card/Card";
import { TableStateResponse } from "@/common/models/TableStateResponse";
import { AssetModel } from "@/contracts/client.schemas";
import { KeyValue } from "@/models/KeyValue";
import { http } from "@/services/http.service";

export const AssetGroupCardPage = () => {
	const { organizationId } = useParams();
	const [, setOptions] = useState<KeyValue[]>([]);

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

	useEffect(() => {
		http.get<TableStateResponse<AssetModel>>("/api/assets", {
			params: { organizationId },
		}).then((response) => {
			setOptions(
				response.items.map((x) => ({
					key: x.id,
					value: x.name,
				})),
			);
		});
	}, []);

	const defaultValue = {
		id: "",
		name: "",
		assetIdList: [],
		organizationId,
		hasPBX: false,
	};

	const validationSchema = z.object({
		name: z.string({
			required_error: "Name is required",
			invalid_type_error: "Name must be a string",
		}),
		hasPBX: z.boolean(),
	});

	return (
		<Card
			defaultValue={defaultValue}
			createTitle="Create Asset Group"
			editTitle="Edit Asset Group"
			viewTitle="View Asset Group Card"
			baseUrl="/api/asset-groups"
			fields={[
				{
					name: "name",
					title: "Name",
				},
				{
					name: "hasPBX",
					title: "Has PBX",
					type: "checkbox",
				},
			]}
			validationSchema={validationSchema}
			getModelTitle={(model) => model.name}
			notificationMethodPrefix="ASSET-GROUPS"
			canEdit={true}
			canRemove={true}
		/>
	);
};
