'use client';

import { Loader } from "../../Loader/index.mjs";
import { ButtonColor, ButtonSize, ButtonVariant } from "../../Button/Button.mjs";
import { Checkbox } from "../../Input/Checkbox.mjs";
import { useSession } from "../../../hooks/useAuth/useSession.mjs";
import { useAuditContentDeclarationMetadata, useGetProjects, useGetTags } from "../../../hooks/reactQuery.mjs";
import { MultiSelect } from "../../Select/Multiselect.mjs";
import { useForm as useForm$1 } from "../../Form/FormBase.mjs";
import { Form } from "../../Form/Form.mjs";
import { useDictionaryDetailsSchema } from "./useDictionaryDetailsSchema.mjs";
import { WandSparkles } from "lucide-react";
import { useEffect } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { useIntlayer } from "react-intlayer";
import { useEditedContent } from "@intlayer/editor-react";
import { AnimatePresence, motion } from "framer-motion";
import { useWatch } from "react-hook-form";

//#region src/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.tsx
const DictionaryDetailsForm = ({ dictionary, mode }) => {
	const { session } = useSession();
	const { project } = session ?? {};
	const { data: projectsData, isLoading: isLoadingProjects } = useGetProjects();
	const { data: tagsData } = useGetTags();
	const projects = projectsData?.data ?? [];
	const allTags = tagsData?.data ?? [];
	const DictionaryDetailsSchema = useDictionaryDetailsSchema(String(project?.id));
	const { form, isSubmitting } = useForm$1(DictionaryDetailsSchema, { defaultValues: {
		...dictionary,
		location: dictionary.location ?? "remote"
	} });
	const { editedContent, setEditedDictionary } = useEditedContent();
	const { titleInput, keyInput, descriptionInput, projectInput, tagsSelect, locationSelect, filePathInput, auditButton } = useIntlayer("dictionary-details");
	const { mutate: auditContentDeclaration, isPending: isAuditing } = useAuditContentDeclarationMetadata();
	const updatedDictionary = editedContent?.[dictionary.localId];
	useEffect(() => {
		form.reset({
			...dictionary,
			location: dictionary.location ?? "remote"
		});
	}, [dictionary, form?.reset]);
	useEffect(() => {
		if (typeof updatedDictionary === "undefined") form.reset({
			...dictionary,
			location: dictionary.location ?? "remote"
		});
	}, [updatedDictionary]);
	const handleOnAuditFile = () => {
		const dictionaryToAudit = {
			...dictionary,
			...updatedDictionary
		};
		auditContentDeclaration({ fileContent: JSON.stringify(dictionaryToAudit) }, { onSuccess: (response) => {
			if (!response?.data) return;
			try {
				const auditedDictionary = response.data.fileContent;
				setEditedDictionary((prev) => ({
					...prev,
					...dictionaryToAudit,
					...auditedDictionary
				}));
				form.reset({
					...dictionaryToAudit,
					...auditedDictionary
				});
			} catch (error) {
				console.error(error);
			}
		} });
	};
	const watchedLocation = useWatch({
		control: form.control,
		name: "location"
	});
	const isLocalChecked = watchedLocation === "local" || watchedLocation === "local&remote";
	return /* @__PURE__ */ jsxs(Form, {
		className: "flex w-full flex-col gap-8",
		...form,
		schema: DictionaryDetailsSchema,
		children: [
			/* @__PURE__ */ jsxs("div", {
				className: "grid grid-cols-2 gap-8 max-md:grid-cols-1",
				children: [/* @__PURE__ */ jsx(Form.EditableFieldInput, {
					name: "key",
					label: keyInput.label,
					placeholder: keyInput.label.value,
					description: keyInput.description,
					disabled: isSubmitting,
					isRequired: true,
					onSave: (value) => {
						form.setValue("key", value, { shouldDirty: true });
						setEditedDictionary((prev) => ({
							...dictionary,
							...prev ?? {},
							key: value
						}));
					}
				}), /* @__PURE__ */ jsx(Form.EditableFieldInput, {
					name: "title",
					label: titleInput.label,
					placeholder: titleInput.placeholder.value,
					description: titleInput.description,
					disabled: isSubmitting,
					onSave: (value) => {
						form.setValue("title", value, { shouldDirty: true });
						setEditedDictionary((prev) => ({
							...dictionary,
							...prev ?? {},
							title: value
						}));
					}
				})]
			}),
			/* @__PURE__ */ jsx(Form.EditableFieldTextArea, {
				name: "description",
				label: descriptionInput.label,
				placeholder: descriptionInput.placeholder.value,
				description: descriptionInput.description,
				disabled: isSubmitting,
				onSave: (value) => {
					form.setValue("description", value, { shouldDirty: true });
					setEditedDictionary((prev) => ({
						...dictionary,
						...prev ?? {},
						description: value
					}));
				}
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "grid grid-cols-2 gap-8 px-1 max-md:grid-cols-1",
				children: [/* @__PURE__ */ jsx(Form.Field, {
					control: form.control,
					name: "location",
					render: ({ field }) => {
						const value = field.value;
						const isLocal = value === "local" || value === "local&remote";
						const isRemote = value === "remote" || value === "local&remote";
						const handleLocalToggle = (isChecked) => {
							if (!isChecked && !isRemote) return;
							const newValue = isChecked ? isRemote ? "local&remote" : "local" : "remote";
							field.onChange(newValue);
							const newFilePath = isChecked ? form.getValues("filePath") ?? dictionary.filePath : void 0;
							if (!isChecked) form.setValue("filePath", void 0);
							setEditedDictionary((prev) => ({
								...dictionary,
								...prev ?? {},
								location: newValue,
								filePath: newFilePath
							}));
						};
						const handleRemoteToggle = (isChecked) => {
							if (!isChecked && !isLocal) return;
							const newValue = isChecked ? isLocal ? "local&remote" : "remote" : "local";
							field.onChange(newValue);
							setEditedDictionary((prev) => ({
								...dictionary,
								...prev ?? {},
								location: newValue
							}));
						};
						return /* @__PURE__ */ jsxs(Form.Item, {
							className: "flex flex-col gap-2 px-1",
							children: [
								/* @__PURE__ */ jsx(Form.Label, {
									className: "ml-1",
									children: locationSelect.label
								}),
								/* @__PURE__ */ jsxs("div", {
									className: "ml-2 flex items-center gap-4 py-2",
									children: [/* @__PURE__ */ jsx(Checkbox, {
										id: "location-local",
										name: "location-local",
										label: locationSelect.local.value,
										checked: isLocal,
										disabled: !mode.includes("local") && !mode.includes("remote"),
										onChange: (e) => handleLocalToggle(e.target.checked)
									}), /* @__PURE__ */ jsx(Checkbox, {
										id: "location-remote",
										name: "location-remote",
										label: locationSelect.remote.value,
										checked: isRemote,
										disabled: !mode.includes("remote") && dictionary.location !== "remote" && dictionary.location !== "local&remote",
										onChange: (e) => handleRemoteToggle(e.target.checked)
									})]
								}),
								/* @__PURE__ */ jsx(Form.Description, { children: locationSelect.testDescription }),
								/* @__PURE__ */ jsx(Form.Message, {})
							]
						});
					}
				}), /* @__PURE__ */ jsx(AnimatePresence, {
					mode: "wait",
					children: isLocalChecked && /* @__PURE__ */ jsx(motion.div, {
						initial: {
							opacity: 0,
							height: 0
						},
						animate: {
							opacity: 1,
							height: "auto"
						},
						exit: {
							opacity: 0,
							height: 0
						},
						transition: { duration: .3 },
						className: "overflow-hidden",
						children: /* @__PURE__ */ jsx(Form.Input, {
							name: "filePath",
							label: filePathInput.label.value,
							placeholder: filePathInput.placeholder.value,
							description: filePathInput.description.value,
							disabled: isSubmitting || !isLocalChecked,
							onChange: (e) => {
								const value = e.target.value;
								setEditedDictionary((prev) => ({
									...dictionary,
									...prev ?? {},
									filePath: value
								}));
							}
						})
					}, "filePath-input")
				})]
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "grid grid-cols-2 gap-8 max-md:grid-cols-1",
				children: [/* @__PURE__ */ jsxs(Form.MultiSelect, {
					name: "projectIds",
					label: projectInput.label.value,
					description: projectInput.description,
					onValueChange: (value) => {
						const valueArray = [value].flat();
						form.setValue("projectIds", valueArray, { shouldDirty: true });
						setEditedDictionary((prev) => ({
							...dictionary,
							...prev ?? {},
							projectIds: valueArray
						}));
					},
					children: [/* @__PURE__ */ jsx(MultiSelect.Trigger, {
						getBadgeValue: (value) => projects?.find((project$1) => String(project$1.id) === value)?.name ?? value,
						children: /* @__PURE__ */ jsx(MultiSelect.Input, { placeholder: projectInput.placeholder.value })
					}), /* @__PURE__ */ jsx(MultiSelect.Content, { children: /* @__PURE__ */ jsx(Loader, {
						isLoading: isLoadingProjects,
						children: /* @__PURE__ */ jsx(MultiSelect.List, { children: projects?.map((project$1) => /* @__PURE__ */ jsx(MultiSelect.Item, {
							value: String(project$1.id),
							children: project$1.name
						}, String(project$1.id))) })
					}) })]
				}), /* @__PURE__ */ jsxs(Form.MultiSelect, {
					name: "tags",
					label: tagsSelect.label.value,
					description: tagsSelect.description,
					onValueChange: (value) => {
						const valueArray = [value].flat();
						form.setValue("tags", valueArray, { shouldDirty: true });
						setEditedDictionary((prev) => ({
							...dictionary,
							...prev ?? {},
							tags: valueArray
						}));
					},
					children: [/* @__PURE__ */ jsx(MultiSelect.Trigger, {
						getBadgeValue: (value) => allTags?.find((tag) => String(tag.key) === value)?.name ?? value,
						children: /* @__PURE__ */ jsx(MultiSelect.Input, { placeholder: tagsSelect.placeholder.value })
					}), /* @__PURE__ */ jsx(MultiSelect.Content, { children: /* @__PURE__ */ jsx(Loader, {
						isLoading: isLoadingProjects,
						children: /* @__PURE__ */ jsx(MultiSelect.List, { children: allTags?.map((tag) => /* @__PURE__ */ jsx(MultiSelect.Item, {
							value: String(tag.key),
							children: tag.name ?? tag.key
						}, String(tag.key))) })
					}) })]
				})]
			}),
			/* @__PURE__ */ jsx("div", {
				className: "flex flex-wrap items-center justify-end gap-2 max-md:flex-col",
				children: /* @__PURE__ */ jsx(Form.Button, {
					type: "button",
					size: ButtonSize.ICON_MD,
					label: auditButton.label.value,
					Icon: WandSparkles,
					variant: ButtonVariant.OUTLINE,
					color: ButtonColor.TEXT,
					className: "max-md:w-full",
					onClick: handleOnAuditFile,
					disabled: isSubmitting || isAuditing,
					isLoading: isAuditing
				})
			})
		]
	});
};

//#endregion
export { DictionaryDetailsForm };
//# sourceMappingURL=DictionaryDetailsForm.mjs.map