import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
import { IOption as IFormOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
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 { OfficeFolder } from "le-coffre-resources/dist/Notary";
import { ChangeEvent, useCallback, useEffect, useState } from "react";

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

import DocumentTypeService from "src/common/Api/LeCoffreApi/sdk/DocumentTypeService";
import DeedTypeService from "src/common/Api/LeCoffreApi/sdk/DeedTypeService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import { DEFAULT_VALIDATOR_ID } from "@Front/Config/AppConstants";

type IProps = {
	isCreateDocumentModalVisible: boolean;
	closeModal: () => void;
	folder: OfficeFolder;
	onDocumentsUpdated?: (newDocumentTypes: IFormOption[]) => 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 () => {
		DocumentTypeService.getDocumentTypes().then((processes: any[]) => {
			if (processes.length > 0) {
				const documents: any[] = processes.map((process: any) => process.processData);

				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 () => {
		if (addOrEditDocument === "add") {
			try {
				LoaderService.getInstance().show();

				const documentTypeData: any = {
					name: documentName,
					private_description: visibleDescription,
					office: {
						uid: props.folder.office!.uid!,
					},
					public_description: visibleDescription,
				};

				const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
					DocumentTypeService.createDocumentType(documentTypeData, DEFAULT_VALIDATOR_ID).then((processCreated: any) => {
						const documentType: any = processCreated.processData;
						resolve(documentType);
					});
				});

				const oldDocumentsType = props.folder.deed?.document_types!;

				await new Promise<void>((resolve: () => void) => {
					DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then(async (process: any) => {
						if (process) {
							// New data
							const newData: any = {
								document_types: [
									...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
									{ uid: documentType.uid }
								]
							};

							// Merge process data with new data & update process
							process.processData.document_types = newData.document_types;
							await DeedTypeService.updateDeedType(process, newData);

							resolve();
						}
					});
				});

				// Create a new document type in the format expected by the parent component
				const newDocumentType: IFormOption = {
					label: documentType.name!,
					value: documentType.uid!,
					description: documentType.private_description!,
				};

				if (props.onDocumentsUpdated) {
					props.onDocumentsUpdated([newDocumentType]);
				}

				LoaderService.getInstance().hide();
				handleClose();
			} catch (e) {
				console.error(e);
			}
		} else {
			try {
				LoaderService.getInstance().show();

				const oldDocumentsType = props.folder.deed?.document_types!;
				await new Promise<void>((resolve: () => void) => {
					DeedTypeService.getDeedTypeByUid(props.folder.deed?.deed_type?.uid!).then(async (process: any) => {
						if (process) {
							// New data
							const newData: any = {
								document_types: [
									...oldDocumentsType.map((document: any) => ({ uid: document.uid })),
									...selectedDocuments.map((document: any) => ({ uid: document.id as string }))
								]
							};

							// Merge process data with new data & update process
							process.processData.document_types = newData.document_types;
							await DeedTypeService.updateDeedType(process, newData);

							resolve();
						}
					});
				});

				// Get the full document details for the selected documents
				const documentsById = await Promise.all(
					selectedDocuments.map(async (doc) => {
						const documentType: any = await new Promise<any>((resolve: (documentType: any) => void) => {
							DocumentTypeService.getDocumentTypeByUid(doc.id as string).then((process: any) => {
								if (process) {
									const documentType: any = process.processData;
									resolve(documentType);
								}
							});
						});
						return {
							label: documentType.name!,
							value: documentType.uid!,
							description: documentType.private_description!,
						} as IFormOption;
					})
				);

				if (props.onDocumentsUpdated) {
					props.onDocumentsUpdated(documentsById);
				}

				LoaderService.getInstance().hide();
				handleClose();
			} 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>
	);
}
