import { Form } from "../../../utilities/form/Form.mjs";
import { Field } from "../../../utilities/form/Field.mjs";
import { SubmitButton } from "../../../utilities/form/SubmitButton.mjs";
import { FormButtons } from "../../../utilities/form/FormButtons.mjs";
import { ConfigService } from "../../../configService/index.mjs";
import { useHandleAxiosSnackbar } from "../../../utilities/apiHelpers.mjs";
import { apiMutate } from "../../../utilities/useAxiosMutate.mjs";
import { UnityFluentIcon } from "../../../utilities/iconLibrary/UnityFluentIcon.mjs";
import { useActionState } from "../../../hooks/useActions.mjs";
import { getIconFromName } from "../../../utilities/tree/TreeUtilities.mjs";
import { getUnityIconFromName } from "../../../utilities/iconLibrary/UnityIconLibrary.mjs";
import { SideSheet } from "../../../UI/surfaces/SideSheet.mjs";
import { AmbientGridTemplate } from "../../../UI/templates/deprecated/AmbientGridTemplate/AmbientGridTemplate.mjs";
import { ActionsRenderer } from "../../../UI/templates/ui/renderers/ActionsRenderer.mjs";
import { FluentCheckbox } from "../../../UI/inputs/checkbox/FluentCheckbox.mjs";
import IconLibrary_default from "../../../utilities/iconLibrary/IconLibrary.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { IconButton, LinearProgress, TextField } from "@material-ui/core";
import { useTranslation } from "react-i18next";
//#region src/udp/pages/UdpVerticalManagementSidesheet/UdpVerticalManagementSidesheet.jsx
const UdpVerticalManagementSidesheet = (props) => {
	const { selectedVertical, environment, associatedProducts, isEdit, deleteVertical, open, selectedCatalog, closeSidesheet, onSubmit, ...sheetProps } = props;
	const { t } = useTranslation();
	const [loading, setLoading] = useState(false);
	useActionState();
	const [displayedIcon, setDisplayedIcon] = useState({
		name: "StatusCircleQuestionMarkIcon",
		color: "",
		type: ""
	});
	const [products, setProducts] = useState([]);
	const [openIconLibrary, setOpenIconLibrary] = useState(false);
	const [selectedProductIds, setSelectedProductIds] = useState([]);
	const [checkboxValues, setCheckboxValues] = useState([]);
	const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
	const selectedProductIdsRef = useRef();
	selectedProductIdsRef.current = selectedProductIds;
	const displayedIconRef = useRef();
	displayedIconRef.current = displayedIcon;
	const selectedVerticalRef = useRef();
	selectedVerticalRef.current = selectedVertical;
	const formRef = useRef();
	const nameRef = useRef();
	const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
	const CheckBoxRenderer = ({ onChange, value, id, defaultChecked }) => {
		const isAssociatedToVertical = useCallback((productId) => {
			if (!isEdit) return false;
			for (let product of associatedProducts) if (product.productId === productId && product.verticalId === selectedVerticalRef.current.verticalId) return true;
			getIconFromName(selectedVerticalRef.current.icon);
			return false;
		}, [associatedProducts, selectedVerticalRef]);
		const handleCheckboxChange = (e) => {
			if (e.target.checked) setSelectedProductIds((prevState) => [...prevState, id]);
			else setSelectedProductIds((prevState_0) => prevState_0.filter((item) => item !== id));
		};
		return /* @__PURE__ */ React.createElement(FluentCheckbox, {
			defaultChecked: isAssociatedToVertical(id),
			onChange: handleCheckboxChange,
			aria: "column-active"
		});
	};
	const gridOptions = useMemo(() => ({
		frameworkComponents: {
			actionsRenderer: ActionsRenderer,
			checkboxRenderer: CheckBoxRenderer
		},
		columnDefs: [{
			headerName: "",
			field: "select",
			cellRenderer: "checkboxRenderer",
			cellRendererParams: (params) => ({ id: params.data.productId })
		}, {
			headerName: t("Product Name"),
			field: "name",
			minWidth: 200
		}]
	}), [
		isEdit,
		selectedVertical,
		associatedProducts
	]);
	const executeMutation = useCallback(async (endpoint, method, data) => apiMutate(ConfigService.uemV1ApiUrl, endpoint, { method: method || "post" }, data), []);
	const getProducts = useCallback(async (data_0) => {
		setLoading(true);
		const response = await executeMutation("uem", "post", data_0);
		if (response?.status === 200) setProducts(response?.data);
		setLoading(false);
	}, [executeMutation, setProducts]);
	const createVertical = useCallback(async (data_1) => {
		setLoading(true);
		if ((await executeMutation("vertical/uemCreate", "post", data_1))?.status === 201) {
			closeSidesheet();
			handleSuccessSnackbar("Vertical Created Successfully");
		} else handleErrorSnackbar("Something went wrong");
		setLoading(false);
	}, [executeMutation]);
	const updateVertical = useCallback(async (data_2) => {
		setLoading(true);
		if ((await executeMutation(`vertical/${selectedVertical.verticalId}/uemUpdate`, "put", data_2))?.status === 204) {
			closeSidesheet();
			handleSuccessSnackbar("Vertical Updated Successfully");
		} else handleErrorSnackbar("Something went wrong");
		setLoading(false);
	}, [selectedVertical, executeMutation]);
	const handleSubmit = useCallback((values) => {
		setLoading(true);
		const products_0 = selectedProductIdsRef.current.map((productId_0) => ({ productId: productId_0 }));
		!isEdit ? createVertical({ data: {
			name: values.name,
			products: products_0,
			icon: displayedIconRef?.current.name,
			EnvironmentId: environment.environmentId,
			apiPath: "api/v1/vertical/uemCreate"
		} }) : updateVertical({ data: {
			name: values.name,
			products: products_0,
			icon: displayedIconRef?.current.name,
			EnvironmentId: environment.environmentId,
			apiPath: `api/v1/vertical/${selectedVertical.verticalId}/uemUpdate`
		} });
	}, [
		isEdit,
		createVertical,
		environment,
		updateVertical,
		selectedVertical,
		selectedProductIdsRef
	]);
	useEffect(() => {
		if (environment && getProducts) {
			if (environment.environmentId) getProducts({ data: {
				customerId: null,
				environmentId: environment.environmentId,
				apiPath: `tenantService/api/v2/product`
			} });
		}
	}, [environment, getProducts]);
	useEffect(() => {
		if (selectedVertical) {
			const associatedProductIds = selectedVertical.verticalProductVertical.map((product_0) => product_0.productId);
			setSelectedProductIds((prevState_1) => [...prevState_1, ...associatedProductIds]);
		}
	}, [selectedVertical, setSelectedProductIds]);
	const setDisplayedIconCallback = useCallback(() => {
		setDisplayedIcon({ name: isEdit && selectedVertical?.icon ? selectedVertical?.icon : "StatusCircleQuestionMarkIcon" });
	}, [selectedVertical, isEdit]);
	useEffect(() => {
		setDisplayedIconCallback();
	}, [open]);
	const closeIconLibrary = () => {
		setOpenIconLibrary(false);
	};
	const onOpenLibrary = () => {
		setOpenIconLibrary(true);
	};
	const handleIconSelect = (icon_0) => {
		const updateddisplayedIcon = { ...props.displayedIcon };
		updateddisplayedIcon.name = icon_0.id;
		updateddisplayedIcon.type = icon_0.type || null;
		setDisplayedIcon(updateddisplayedIcon);
		closeIconLibrary();
	};
	const initialValues = useMemo(() => {
		return { name: isEdit ? selectedVertical?.name : "" };
	}, [
		associatedProducts,
		selectedVertical,
		isEdit
	]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SideSheet, {
		open,
		onClose: () => closeSidesheet(),
		width: 400,
		title: props.title
	}, /* @__PURE__ */ React.createElement(Form, {
		ref: formRef,
		onSubmit: handleSubmit,
		initialValues
	}, /* @__PURE__ */ React.createElement("div", { style: { display: "flex" } }, /* @__PURE__ */ React.createElement(Field, {
		ref: nameRef,
		component: TextField,
		label: t("Name"),
		id: "name",
		name: "name",
		variant: "outlined",
		size: "small",
		required: true,
		style: { marginTop: 8 }
	}), /* @__PURE__ */ React.createElement(IconButton, { onClick: onOpenLibrary }, displayedIcon && /* @__PURE__ */ React.createElement(UnityFluentIcon, {
		type: displayedIcon?.type,
		icon: displayedIcon?.type === "unity" ? getUnityIconFromName(displayedIcon?.name) : getIconFromName(displayedIcon?.name)
	}))), /* @__PURE__ */ React.createElement(AmbientGridTemplate, {
		data: products,
		title: t("Products"),
		loading,
		height: "calc(100vh - 300px)",
		hideGroupTab: true,
		hideColumnTab: true,
		disablePagination: true,
		hideFitGrid: true,
		hideExpandGrid: true,
		hideExportGrid: true,
		hideRemoveFilters: true,
		hideFilterTab: true,
		...gridOptions
	}), /* @__PURE__ */ React.createElement(FormButtons, null, /* @__PURE__ */ React.createElement(SubmitButton, {
		variant: "contained",
		color: "secondary",
		marginTop: "50px",
		disabled: false,
		disablePristine: false
	}, t(isEdit ? "Update" : "Create"))), loading && /* @__PURE__ */ React.createElement(LinearProgress, null))), /* @__PURE__ */ React.createElement(SideSheet, {
		open: openIconLibrary,
		onClose: closeIconLibrary,
		title: t("Icon Library"),
		width: "100%",
		anchor: "bottom"
	}, /* @__PURE__ */ React.createElement(IconLibrary_default, {
		addItem: handleIconSelect,
		selectedIconName: displayedIcon?.name,
		title: t("Select Icon")
	})));
};
//#endregion
export { UdpVerticalManagementSidesheet as default };

//# sourceMappingURL=UdpVerticalManagementSidesheet.mjs.map