import Documents from "@Front/Api/LeCoffreApi/Notary/Documents/Documents";
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import CheckBox from "@Front/Components/DesignSystem/CheckBox";
import Form from "@Front/Components/DesignSystem/Form";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import BackArrow from "@Front/Components/Elements/BackArrow";
import Module from "@Front/Config/Module";
import { PlusIcon } from "@heroicons/react/24/outline";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState } from "react";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import classes from "./classes.module.scss";
import ParameterDocuments from "./ParameterDocuments";
import { IOption } from "@Front/Components/DesignSystem/Form/SelectFieldOld";
import backgroundImage from "@Assets/images/background_refonte.svg";

export default function AskDocuments() {
	const router = useRouter();
	let { folderUid, customerUid } = router.query;
	const [isCreateDocumentModalVisible, setIsCreateDocumentModalVisible] = useState<boolean>(false);
	const [documentTypes, setDocumentTypes] = useState<IOption[]>([]);
	const [folder, setFolder] = useState<OfficeFolder | null>(null);
	const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);

	const closeModal = () => setIsCreateDocumentModalVisible(false);
	const openModal = () => setIsCreateDocumentModalVisible(true);

	const onFormSubmit = useCallback(
		async (e: React.FormEvent<HTMLFormElement> | null) => {
			try {
				for (let i = 0; i < selectedDocuments.length; i++) {
					await Documents.getInstance().post({
						folder: { uid: folderUid },
						depositor: { uid: customerUid },
						document_type: { uid: selectedDocuments[i] },
					});
				}

				router.push(
					Module.getInstance()
						.get()
						.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string),
				);
			} catch (e) {
				console.error(e);
			}
		},
		[selectedDocuments, customerUid, folderUid, router],
	);

	const getAvailableDocuments = useCallback(
		async (folder: OfficeFolder): Promise<IOption[]> => {
			// Getting already asked documents UIDs in an array
			const userDocumentTypesUids = folder
				.documents!.filter((document) => document.depositor!.uid! === customerUid!)
				.map((document) => {
					return document.document_type!.uid!;
				});

			// If those UIDs are already asked, filter them to not show them in the list and only
			// show the documents that are not asked yet
			const documentTypes = folder.deed!.document_types!.filter((documentType) => {
				if (userDocumentTypesUids.includes(documentType!.uid!)) return false;
				return true;
			});

			// If there is none document type available, return an empty array
			if (!documentTypes) return [];

			// Else, return an array document types formatted as IOPtions
			const documentTypesOptions: IOption[] = documentTypes.map((documentType) => {
				return {
					label: documentType!.name!,
					value: documentType!.uid!,
					description: documentType!.private_description!,
				};
			});

			documentTypesOptions.sort((a, b) => (a.label > b.label ? 1 : -1));

			return documentTypesOptions;
		},
		[customerUid],
	);

	const loadData = useCallback(async () => {
		try {
			const folder = await Folders.getInstance().getByUid(folderUid as string, {
				q: {
					deed: {
						include: {
							document_types: true,
						},
					},
					office: true,
					documents: {
						include: {
							depositor: true,
							document_type: true,
						},
					},
				},
			});
			if (!folder) return;
			setFolder(folder);
			setDocumentTypes(await getAvailableDocuments(folder));
		} catch (e) {
			console.error(e);
		}
	}, [folderUid, getAvailableDocuments]);

	const handleDocumentAdded = async () => {
		if (!folder) return;

		try {
			// Fetch updated folder data to get the new document
			const updatedFolder = await Folders.getInstance().getByUid(folderUid as string, {
				q: {
					deed: { include: { document_types: true } },
					office: true,
					documents: { include: { depositor: true, document_type: true } },
				},
			});

			if (!updatedFolder) return;

			setFolder(updatedFolder); // ✅ Update the folder state
			setDocumentTypes(await getAvailableDocuments(updatedFolder)); // ✅ Refresh the document list

			console.log("Document list updated with new document:", updatedFolder);
		} catch (error) {
			console.error("Failed to refresh document list:", error);
		}
	};

	useEffect(() => {
		loadData();
	}, [loadData]);

	const backUrl = Module.getInstance()
		.get()
		.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string);
	return (
		<DefaultDoubleSidePage title={"Demander des documents"} image={backgroundImage} showHeader>
			<div className={classes["root"]}>
				<BackArrow url={backUrl} />
				<Typography typo={ETypo.DISPLAY_LARGE} color={ETypoColor.COLOR_GENERIC_BLACK} className={classes["title"]}>
					Demander des documents
				</Typography>
				<Form onSubmit={onFormSubmit}>
					<div className={classes["form-container"]}>
						<div className={classes["checkbox-container"]}>
							{documentTypes.map((documentType) => {
								if (documentType.description && documentType.description.length > 1) {
									return (
										<CheckBox
											name="document_types"
											toolTip={documentType.description}
											option={documentType}
											key={documentType.value as string}
											checked={selectedDocuments.includes(documentType.value as string)}
											onChange={(e) => {
												const value = documentType.value as string;
												setSelectedDocuments((prev) =>
													e.target.checked ? [...prev, value] : prev.filter((id) => id !== value),
												);
											}}
										/>
									);
								}
								return <CheckBox name="document_types" option={documentType} key={documentType.value as string} />;
							})}
						</div>
						<div className={classes["add-document-container"]}>
							<Button
								leftIcon={<PlusIcon style={{ transform: "rotate(180deg)", width: "22px", height: "22px" }} />}
								variant={EButtonVariant.PRIMARY}
								styletype={EButtonstyletype.OUTLINED}
								size={EButtonSize.MD}
								onClick={openModal}>
								Ajouter un document
							</Button>
						</div>
						<div className={classes["buttons-container"]}>
							<a href={backUrl}>
								<Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED}>
									Annuler
								</Button>
							</a>
							<Button type="submit">Envoyer la demande</Button>
						</div>
					</div>
				</Form>
			</div>
			{folder && (
				<ParameterDocuments
					folder={folder}
					closeModal={closeModal}
					isCreateDocumentModalVisible={isCreateDocumentModalVisible}
					onDocumentAdded={handleDocumentAdded}
				/>
			)}
		</DefaultDoubleSidePage>
	);
}
