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 { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useState, useRef } 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";

import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import { DocumentData } from "../FolderInformation/ClientView/DocumentTables/types";

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 [selectedDocumentTypes, setSelectedDocumentTypes] = useState<string[]>([]);
	const formRef = useRef<Form>(null);

	const closeModal = () => setIsCreateDocumentModalVisible(false);
	const openModal = () => {
		// Store the currently selected document types before opening modal
		const selectedTypes = getSelectedDocumentTypes();
		setSelectedDocumentTypes(selectedTypes);
		setIsCreateDocumentModalVisible(true);
	};

	const getSelectedDocumentTypes = () => {
		// Get all checked checkboxes
		if (!formRef.current) return [];

		const formElement = formRef.current.formRef.current;
		if (!formElement) return [];

		const checkboxes = Array.from(formElement.elements).filter(
			(elem) => elem.getAttribute("type") === "checkbox" && elem.getAttribute("name") === "document_types",
		) as HTMLInputElement[];

		return checkboxes.filter((checkbox) => checkbox.checked).map((checkbox) => checkbox.value);
	};

	const onFormSubmit = useCallback(
		async (
			e: React.FormEvent<HTMLFormElement> | null,
			values: {
				[key: string]: any;
			},
		) => {
			try {
				// TODO: review
				LoaderService.getInstance().show();
				const documentAsked: [] = values["document_types"] as [];
				for (let i = 0; i < documentAsked.length; i++) {
					const documentTypeUid = documentAsked[i];
					if (!documentTypeUid) continue;
					
					const documentData: any = {
						folder: {
							uid: folderUid as string,
						},
						depositor: {
							uid: customerUid as string,
						},
						document_type: {
							uid: documentTypeUid
						},
						document_status: EDocumentStatus.ASKED,
						file_uid: null,
					};
					const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';

					await DocumentService.createDocument(documentData, validatorId);
				}
				router.push(
					Module.getInstance()
						.get()
						.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string),
				);
			} catch (e) {
				console.error(e);
			}
		},
		[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 {
			LoaderService.getInstance().show();
			FolderService.getFolderByUid(folderUid as string).then(async (process: any) => {
				if (process) {
					const folder: any = process.processData;
					setFolder(folder);
					setDocumentTypes(await getAvailableDocuments(folder));
					LoaderService.getInstance().hide();
				}
			});
		} catch (e) {
			console.error(e);
		}
	}, [folderUid, getAvailableDocuments]);

	// Update checkboxes after data has been refreshed
	const updateCheckedState = useCallback(() => {
		if (!formRef.current || selectedDocumentTypes.length === 0) return;

		const formElement = formRef.current.formRef.current;
		if (!formElement) return;

		// Check all checkboxes that were previously selected
		const checkboxes = Array.from(formElement.elements).filter(
			(elem) => elem.getAttribute("type") === "checkbox" && elem.getAttribute("name") === "document_types",
		) as HTMLInputElement[];

		checkboxes.forEach((checkbox) => {
			if (selectedDocumentTypes.includes(checkbox.value)) {
				checkbox.checked = true;
				// Trigger change to update the internal state of CheckBox component
				const event = new Event("change", { bubbles: true });
				checkbox.dispatchEvent(event);
			}
		});
	}, [selectedDocumentTypes]);

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

	useEffect(() => {
		// Set timeout to ensure DOM is updated with checkboxes before trying to check them
		const timer = setTimeout(() => {
			updateCheckedState();
		}, 0);
		return () => clearTimeout(timer);
	}, [documentTypes, updateCheckedState]);

	const backUrl = Module.getInstance()
		.get()
		.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string);

	const handleDocumentsUpdated = async (newDocumentTypes: IOption[]) => {
		// Store existing selections
		const existingSelections = getSelectedDocumentTypes();

		// Update document types with new ones
		setDocumentTypes([...documentTypes, ...newDocumentTypes]);

		// Set these as selected
		setSelectedDocumentTypes([...existingSelections, ...newDocumentTypes.map((dt) => dt.value 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 ref={formRef} 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={selectedDocumentTypes.includes(documentType.value as string)}
										/>
									);
								}
								return (
									<CheckBox
										name="document_types"
										option={documentType}
										key={documentType.value as string}
										checked={selectedDocumentTypes.includes(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}
					onDocumentsUpdated={handleDocumentsUpdated}
				/>
			)}
		</DefaultDoubleSidePage>
	);
}
