import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
import classes from "./classes.module.scss";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
import { ChangeEvent, useCallback, useEffect, useState } from "react";
import DocumentTypes from "@Front/Api/LeCoffreApi/Notary/DocumentTypes/DocumentTypes";
import { DocumentType, OfficeFolder } from "le-coffre-resources/dist/Notary";
import Deeds from "@Front/Api/LeCoffreApi/Notary/Deeds/Deeds";
import MultiSelect from "@Front/Components/DesignSystem/MultiSelect";
import { IOption } from "@Front/Components/DesignSystem/Form/SelectField";
import { MultiValue } from "react-select";
import RadioBox from "@Front/Components/DesignSystem/RadioBox";

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

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,
					value: 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((values: MultiValue<IOption>) => {
		setSelectedDocuments(values as IOption[]);
	}, []);

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

	const addDocument = useCallback(async () => {
		if (addOrEditDocument === "add") {
			try {
				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],
				});

				//await this.loadData();
				handleClose();
			} catch (e) {
				console.error(e);
			}
		} else {
			try {
				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.value as string })),
					],
				});

				//await this.loadData();
				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 (
		<Confirm
			isOpen={props.isCreateDocumentModalVisible}
			onClose={handleClose}
			onAccept={addDocument}
			closeBtn
			header={"Ajouter des documents demandables"}
			cancelText={"Annuler"}
			confirmText={"Ajouter"}>
			<div className={classes["add-document-form-container"]}>
				<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" && (
					<MultiSelect
						options={formattedOptions}
						placeholder="Cliquez pour sélectionner des documents"
						onChange={onDocumentChangeHandler}
						defaultValue={selectedDocuments}
					/>
				)}
			</div>
		</Confirm>
	);
}
