import Deeds from "@Front/Api/LeCoffreApi/Notary/Deeds/Deeds";
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Modal from "@Front/Components/DesignSystem/Modal";
import RadioBox from "@Front/Components/DesignSystem/RadioBox";
import { DocumentType, OfficeFolder } from "le-coffre-resources/dist/Notary";
import { ChangeEvent, useCallback, useEffect, useState } from "react";

import classes from "./classes.module.scss";

type IProps = {
	isCreateDocumentModalVisible: boolean;
	closeModal: () => void;
	folder: OfficeFolder;
	onDocumentAdded: () => Promise<void>;
};

export default function ParameterDocuments(props: IProps) {
	const [visibleDescription, setVisibleDescription] = useState<string>("");
	const [documentName, setDocumentName] = useState<string>("");

	const [addOrEditDocument, setAddOrEditDocument] = useState<"add" | "edit">("edit");

	const [selectedDocuments, setSelectedDocuments] = useState<IOption[]>([]);
	const [formattedOptions, setFormattedOptions] = useState<IOption[]>([]);

	const getAvailableDocuments = useCallback(async () => {
		const documents = await DocumentTypes.getInstance().get({});

		const formattedOptions: IOption[] = documents
			.filter((document) => {
				return !props.folder.deed?.document_types?.some((documentType) => documentType.uid === document.uid);
			})
			.map((document) => {
				return {
					label: document.name,
					id: document.uid ?? "",
				};
			});
		formattedOptions.sort((a, b) => (a.label > b.label ? 1 : -1));
		setFormattedOptions(formattedOptions);
	}, [props.folder.deed?.document_types]);

	const onVisibleDescriptionChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
		setVisibleDescription(event.target.value);
	};

	const onDocumentNameChange = (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
		setDocumentName(event.target.value);
	};

	const onDocumentChangeHandler = useCallback((options: IOption[] | null) => {
		options && setSelectedDocuments(options);
	}, []);

	const handleClose = useCallback(() => {
		setSelectedDocuments([]);
		setAddOrEditDocument("edit");
		setVisibleDescription("");
		setDocumentName("");
		props.closeModal();
	}, [props]);

	const addDocument = useCallback(async () => {
		try {
			if (addOrEditDocument === "add") {
				const documentType = await DocumentTypes.getInstance().post({
					name: documentName,
					private_description: visibleDescription,
					office: { uid: props.folder.office!.uid! },
					public_description: visibleDescription,
				});

				const oldDocumentsType = props.folder.deed?.document_types!;
				await Deeds.getInstance().put(props.folder.deed?.uid!, {
					document_types: [...oldDocumentsType, documentType],
				});
			} else {
				const oldDocumentsType = props.folder.deed?.document_types!;
				await Deeds.getInstance().put(props.folder.deed?.uid!, {
					document_types: [
						...oldDocumentsType,
						...selectedDocuments.map((document) => DocumentType.hydrate<DocumentType>({ uid: document.id as string })),
					],
				});
			}

			await props.onDocumentAdded(); // ✅ Refresh AskDocuments state with the new document
			handleClose(); // ✅ Close modal
		} catch (e) {
			console.error(e);
		}
	}, [addOrEditDocument, documentName, handleClose, props, selectedDocuments, visibleDescription]);

	const selectEditMode = () => {
		setAddOrEditDocument("edit");
	};

	const selectAddMode = () => {
		setAddOrEditDocument("add");
	};

	useEffect(() => {
		getAvailableDocuments();
	}, [getAvailableDocuments, props.folder]);

	return (
		<Modal
			isOpen={props.isCreateDocumentModalVisible}
			onClose={handleClose}
			firstButton={{ children: "Annuler", onClick: handleClose }}
			secondButton={{ children: "Ajouter", onClick: addDocument }}
			title={"Ajouter un document"}
			fullheight>
			<div className={classes["root"]}>
				<div className={classes["radiobox-container"]}>
					<RadioBox
						name="document"
						onChange={selectEditMode}
						checked={addOrEditDocument === "edit"}
						value={"existing client"}
						label="Document existant"
					/>

					<RadioBox
						name="document"
						onChange={selectAddMode}
						checked={addOrEditDocument === "add"}
						value={"new client"}
						label="Créer un document"
					/>
				</div>

				{addOrEditDocument === "add" && (
					<>
						<TextField name="document_name" placeholder="Nom du document à ajouter" onChange={onDocumentNameChange} />
						<TextAreaField
							name="description"
							placeholder="Description visible par le client"
							onChange={onVisibleDescriptionChange}
						/>
					</>
				)}
				{addOrEditDocument === "edit" && (
					<AutocompleteMultiSelectField
						label="Sélectionner des documents"
						options={formattedOptions}
						onSelectionChange={onDocumentChangeHandler}
						selectedOptions={selectedDocuments}
					/>
				)}
			</div>
		</Modal>
	);
}
