import { useWorkspace } from "../../../store/store.js";
import CodeInput_default from "../../../components/CodeInput/CodeInput.vue.js";
import DataTable_default from "../../../components/DataTable/DataTable.vue.js";
import DataTableCell_default from "../../../components/DataTable/DataTableCell.vue.js";
import DataTableHeader_default from "../../../components/DataTable/DataTableHeader.vue.js";
import DataTableRow_default from "../../../components/DataTable/DataTableRow.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createSlots, createTextVNode, createVNode, defineComponent, nextTick, normalizeClass, onMounted, openBlock, ref, renderList, unref, watch, withCtx, withModifiers } from "vue";
import { ScalarButton } from "@scalar/components";
import { ScalarIconTrash, ScalarIconWarning } from "@scalar/icons";
//#region src/views/Collection/components/EnvironmentForm.vue?vue&type=script&setup=true&lang.ts
var EnvironmentForm_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "EnvironmentForm",
	props: {
		collection: {},
		environment: {},
		workspace: {},
		envVariables: {}
	},
	setup(__props) {
		const { collectionMutators } = useWorkspace();
		const localVariables = ref([]);
		const collectionKeys = ref(/* @__PURE__ */ new Set());
		const tempKeys = ref(/* @__PURE__ */ new Map());
		const isUpdating = ref(false);
		const variables = computed(() => {
			if (!__props.environment?.value) return [{
				key: "",
				value: ""
			}];
			try {
				const parsedObject = JSON.parse(__props.environment.value);
				const entries = Object.entries(parsedObject).map(([key, val]) => ({
					key,
					value: String(val)
				}));
				if (entries.length === 0) return [{
					key: "",
					value: ""
				}];
				return entries;
			} catch (_) {
				return [{
					key: "",
					value: ""
				}];
			}
		});
		const environmentVariables = computed(() => {
			const lastRow = localVariables.value[localVariables.value.length - 1];
			if (!lastRow) return [{
				key: "",
				value: ""
			}];
			if (lastRow.key || lastRow.value) return [...localVariables.value, {
				key: "",
				value: ""
			}];
			return localVariables.value;
		});
		const getDuplicateKeyIndexes = computed(() => {
			const keyCounts = /* @__PURE__ */ new Map();
			localVariables.value.forEach((v, index) => {
				if (v.key) {
					const indexes = keyCounts.get(v.key) || [];
					indexes.push(index);
					keyCounts.set(v.key, indexes);
				}
			});
			tempKeys.value.forEach((key, index) => {
				if (key) {
					const indexes = keyCounts.get(key) || [];
					indexes.push(index);
					keyCounts.set(key, indexes);
				}
			});
			return Array.from(keyCounts.values()).filter((indexes) => indexes.length > 1).flat();
		});
		watch(variables, (newVars) => {
			localVariables.value = [...newVars];
			collectionKeys.value = new Set(newVars.map((v) => v.key).filter(Boolean));
		}, { immediate: true });
		const handleUpdateRow = async (index, field, value) => {
			if (isUpdating.value) return;
			if (field === "key") {
				tempKeys.value.set(index, value);
				const otherKeys = new Set(collectionKeys.value);
				const currentItem = localVariables.value[index];
				if (currentItem) otherKeys.delete(currentItem.key);
				if (otherKeys.has(value)) return;
			}
			isUpdating.value = true;
			try {
				const newVariables = [...localVariables.value];
				const currentItem = newVariables[index];
				if (!currentItem) return;
				newVariables[index] = {
					key: field === "key" ? value : currentItem.key,
					value: field === "value" ? value : currentItem.value
				};
				if (!newVariables[index].key && !newVariables[index].value && index !== newVariables.length - 1) newVariables.splice(index, 1);
				const updatedValue = newVariables.reduce((acc, { key, value }) => {
					if (key || value) acc[key] = value;
					return acc;
				}, {});
				if (__props.collection) {
					const environments = {
						...__props.collection["x-scalar-environments"],
						[__props.environment.name]: {
							...__props.collection["x-scalar-environments"]?.[__props.environment.name],
							variables: updatedValue
						}
					};
					await collectionMutators.edit(__props.collection.uid, "x-scalar-environments", environments);
				}
				if (index === localVariables.value.length - 1) {
					const lastRow = newVariables[newVariables.length - 1];
					if (lastRow && (lastRow.key || lastRow.value)) await addRow();
				}
				await nextTick();
				localVariables.value = newVariables;
				if (field === "key") {
					collectionKeys.value = new Set(newVariables.map((v) => v.key).filter(Boolean));
					tempKeys.value.delete(index);
				}
			} finally {
				isUpdating.value = false;
			}
		};
		const addRow = async () => {
			if (isUpdating.value) return;
			isUpdating.value = true;
			try {
				const newVariables = [...localVariables.value, {
					key: "",
					value: ""
				}];
				const updatedValue = newVariables.reduce((acc, { key, value }) => {
					if (key || value) acc[key] = value;
					return acc;
				}, {});
				if (__props.collection) {
					const environments = {
						...__props.collection["x-scalar-environments"],
						[__props.environment.name]: {
							...__props.collection["x-scalar-environments"]?.[__props.environment.name],
							variables: updatedValue
						}
					};
					await collectionMutators.edit(__props.collection.uid, "x-scalar-environments", environments);
				}
				await nextTick();
				localVariables.value = newVariables;
			} finally {
				isUpdating.value = false;
			}
		};
		const handleDeleteRow = async (index) => {
			if (isUpdating.value) return;
			isUpdating.value = true;
			try {
				const newVariables = [...localVariables.value];
				newVariables.splice(index, 1);
				const updatedValue = newVariables.reduce((acc, { key, value }) => {
					if (key || value) acc[key] = value;
					return acc;
				}, {});
				if (__props.collection) {
					const environments = {
						...__props.collection["x-scalar-environments"],
						[__props.environment.name]: {
							...__props.collection["x-scalar-environments"]?.[__props.environment.name],
							variables: updatedValue
						}
					};
					await collectionMutators.edit(__props.collection.uid, "x-scalar-environments", environments);
				}
				await nextTick();
				localVariables.value = newVariables;
			} finally {
				isUpdating.value = false;
			}
		};
		const defaultRow = async () => {
			if (localVariables.value.length === 0) await addRow();
			else if (localVariables.value.length >= 1) {
				const lastRow = localVariables.value[localVariables.value.length - 1];
				if (lastRow && (lastRow.key || lastRow.value)) await addRow();
			}
		};
		onMounted(() => {
			defaultRow();
		});
		watch(() => localVariables.value, () => {
			defaultRow();
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(DataTable_default, {
				class: "group/table flex-1",
				columns: ["", ""]
			}, {
				default: withCtx(() => [createVNode(DataTableRow_default, { class: "sr-only !block" }, {
					default: withCtx(() => [createVNode(DataTableHeader_default, null, {
						default: withCtx(() => [..._cache[0] || (_cache[0] = [createTextVNode("Key", -1)])]),
						_: 1
					}), createVNode(DataTableHeader_default, null, {
						default: withCtx(() => [..._cache[1] || (_cache[1] = [createTextVNode("Value", -1)])]),
						_: 1
					})]),
					_: 1
				}), (openBlock(true), createElementBlock(Fragment, null, renderList(environmentVariables.value, (variable, index) => {
					return openBlock(), createBlock(DataTableRow_default, {
						key: index,
						class: normalizeClass({ error: getDuplicateKeyIndexes.value.includes(index) })
					}, {
						default: withCtx(() => [createVNode(DataTableCell_default, null, {
							default: withCtx(() => [createVNode(CodeInput_default, {
								disableCloseBrackets: "",
								disableEnter: "",
								disableTabIndent: "",
								lineWrapping: "",
								environment: __props.environment,
								envVariables: __props.envVariables,
								modelValue: variable.key,
								placeholder: "Key",
								workspace: __props.workspace,
								"onUpdate:modelValue": (v) => handleUpdateRow(index, "key", v)
							}, createSlots({ _: 2 }, [getDuplicateKeyIndexes.value.includes(index) ? {
								name: "icon",
								fn: withCtx(() => [createVNode(unref(ScalarIconWarning), { class: "text-red mr-0.75 size-3.5 brightness-[.9]" })]),
								key: "0"
							} : void 0]), 1032, [
								"environment",
								"envVariables",
								"modelValue",
								"workspace",
								"onUpdate:modelValue"
							])]),
							_: 2
						}, 1024), createVNode(DataTableCell_default, null, {
							default: withCtx(() => [createVNode(CodeInput_default, {
								class: "pr-6 group-hover:pr-10 group-has-[.cm-focused]:pr-10",
								disableCloseBrackets: "",
								disableEnter: "",
								disableTabIndent: "",
								lineWrapping: "",
								environment: __props.environment,
								envVariables: __props.envVariables,
								modelValue: variable.value,
								placeholder: "Value",
								workspace: __props.workspace,
								"onUpdate:modelValue": (v) => handleUpdateRow(index, "value", v)
							}, {
								icon: withCtx(() => [variable.key || variable.value ? (openBlock(), createBlock(unref(ScalarButton), {
									key: 0,
									class: "text-c-2 hover:text-c-1 hover:bg-b-2 z-context hidden h-fit rounded p-1 group-hover:flex group-has-[.cm-focused]:flex",
									size: "sm",
									variant: "ghost",
									onClick: withModifiers(($event) => handleDeleteRow(index), ["stop"])
								}, {
									default: withCtx(() => [createVNode(unref(ScalarIconTrash), { class: "size-3.5" })]),
									_: 1
								}, 8, ["onClick"])) : createCommentVNode("", true)]),
								_: 2
							}, 1032, [
								"environment",
								"envVariables",
								"modelValue",
								"workspace",
								"onUpdate:modelValue"
							])]),
							_: 2
						}, 1024)]),
						_: 2
					}, 1032, ["class"]);
				}), 128))]),
				_: 1
			});
		};
	}
});
//#endregion
export { EnvironmentForm_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=EnvironmentForm.vue.script.js.map