import backgroundImage from "@Assets/images/background_refonte.svg";
import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import DragAndDrop from "@Front/Components/DesignSystem/DragAndDrop";
import Form from "@Front/Components/DesignSystem/Form";
import AutocompleteMultiSelectField from "@Front/Components/DesignSystem/Form/AutocompleteMultiSelectField";
import RadioBox from "@Front/Components/DesignSystem/RadioBox";
import { ToasterService } from "@Front/Components/DesignSystem/Toaster";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import BackArrow from "@Front/Components/Elements/BackArrow";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import Module from "@Front/Config/Module";
import { PaperAirplaneIcon } from "@heroicons/react/24/outline";
import { ValidationError } from "class-validator";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useMemo, useState } from "react";

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

import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import DocumentService from "src/common/Api/LeCoffreApi/sdk/DocumentService";
import FileService from "src/common/Api/LeCoffreApi/sdk/FileService";
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";

enum EClientSelection {
	ALL_CLIENTS = "all_clients",
	SELECTED_CLIENTS = "selected_clients",
}

export default function SendDocuments() {
	const router = useRouter();
	let { folderUid } = router.query;
	const [folder, setFolder] = useState<OfficeFolder | null>(null);
	const [clientSelection, setClientSelection] = useState<EClientSelection | null>(null);
	const [selectedClients, setSelectedClients] = useState<string[]>([]);
	const [files, setFiles] = useState<File[]>([]);
	const [isSending, setIsSending] = useState(false);
	const [validationError, setValidationError] = useState<ValidationError | null>(null);

	const onFormSubmit = useCallback(
		async (
			_e: React.FormEvent<HTMLFormElement> | null,
			_values: {
				[key: string]: any;
			},
		) => {
			if (!files.length) {
				console.error("No files to send");
				return;
			}

			try {
				setIsSending(true);

				if (selectedClients.length === 0) {
					setValidationError({
						property: "clients",
						constraints: {
							isEmpty: "Veuillez sélectionner au moins un client",
						},
					});
					throw new Error("No clients selected");
				}

				LoaderService.getInstance().show();
				for (const selectedClient of selectedClients) {
					const customer: any = await new Promise<void>((resolve: (customer: any) => void) => {
						CustomerService.getCustomerByUid(selectedClient as string).then((process: any) => {
							if (process) {
								const customer: any = process.processData;
								resolve(customer);
							}
						});
					});

					for (const file of files) {
						await new Promise<void>((resolve: () => void) => {
							const reader = new FileReader();
							reader.onload = (event) => {
								if (event.target?.result) {
									const date: Date = new Date();
									const strDate: string = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;

									const fileName: string = `${customer.contact.last_name}_${strDate}.${file.name.split('.').pop()}`;

									const arrayBuffer: ArrayBuffer = event.target.result as ArrayBuffer;
									const uint8Array: Uint8Array = new Uint8Array(arrayBuffer);

									const fileBlob: any = {
										type: file.type,
										data: uint8Array
									};

									const fileData: any = {
										file_blob: fileBlob,
										file_name: fileName
									};
									const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';

									FileService.createFile(fileData, validatorId).then((processCreated: any) => {
										const fileUid: string = processCreated.processData.uid;

										const documentData: any = {
											folder: {
												uid: folderUid as string
											},
											customer: {
												uid: selectedClient as string
											},
											files: [
												{
													uid: fileUid
												}
											],
											document_status: EDocumentNotaryStatus.SENT
										};

										DocumentService.createDocument(documentData, validatorId).then(() => {
											FolderService.refreshFolderByUid(folderUid as string).then(() => resolve());
										});
									});
								}
							};
							reader.readAsArrayBuffer(file);
						});
					}
				}
				LoaderService.getInstance().hide();

				router.push(
					Module.getInstance()
						.get()
						.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string),
				);
				setIsSending(false);
				ToasterService.getInstance().success({ title: "Succès !", description: "Votre document a été envoyée avec succès." });

				/*
				await Promise.all(
					selectedClients.map(async (customer) => {
						const promises = files.map(async (file) => {
							const formData = new FormData();
							formData.append("customerUid", customer as string);
							formData.append("folderUid", folderUid as string);
							formData.append("name", file.name);
							formData.append("file", file);

							// Envoi de chaque fichier pour chaque client
							return DocumentsNotary.getInstance().post(formData);
						});

						// Attendre que tous les fichiers pour un client soient envoyés
						await Promise.all(promises);
					}),
				);
				router.push(
					Module.getInstance()
						.get()
						.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string),
				);
				setIsSending(false);
				ToasterService.getInstance().success({ title: "Succès !", description: "Votre document a été envoyée avec succès." });
				*/
			} catch (error) {
				setIsSending(false);
				console.warn("Error while sending files: ", error);
			}
		},
		[files, folderUid, router, selectedClients],
	);

	const fetchFolder = useCallback(async () => {
		LoaderService.getInstance().show();
		FolderService.getFolderByUid(folderUid as string).then((process: any) => {
			if (process) {
				const folder: any = process.processData;
				setFolder(folder);
				LoaderService.getInstance().hide();
			}
		});
	}, [folderUid]);

	const onClientSelectionChange = useCallback(
		(e: React.ChangeEvent<HTMLInputElement>) => {
			const selection = e.target.value as EClientSelection;
			setClientSelection(selection);

			if (selection === EClientSelection.ALL_CLIENTS && folder?.customers) {
				const allClientIds = folder.customers.map((customer) => customer.uid ?? "");
				setSelectedClients(allClientIds);
			} else {
				setSelectedClients([]);
			}
		},
		[folder],
	);

	const handleClientSelectionChange = useCallback((selectedOptions: any) => {
		setSelectedClients(selectedOptions.map((option: any) => option.id));
	}, []);

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

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

	const handleFileChange = useCallback((files: File[]) => {
		setFiles(files);
	}, []);

	const clientsOptions = useMemo(() => {
		if (!folder?.customers) return [];
		return folder.customers.map((customer) => ({
			id: customer.uid ?? "",
			label: `${customer.contact?.first_name} ${customer.contact?.last_name}`,
		}));
	}, [folder]);

	return (
		<DefaultDoubleSidePage title={"Demander des documents"} image={backgroundImage} showHeader>
			<div className={classes["root"]}>
				<BackArrow url={backUrl} />
				<Typography typo={ETypo.TITLE_H1} color={ETypoColor.TEXT_PRIMARY}>
					Envoyer des documents, sélectionnez les destinataires :
				</Typography>
				<Typography typo={ETypo.TEXT_MD_LIGHT} color={ETypoColor.TEXT_SECONDARY}>
					Voulez-vous envoyer ce document à tous les clients du dossier ou sélectionner certains clients ?{" "}
				</Typography>
				<div className={classes["radioboxes"]}>
					<RadioBox
						name="clients"
						value={EClientSelection.ALL_CLIENTS}
						label="Sélectionner tous les clients du dossier"
						onChange={onClientSelectionChange}
					/>
					<RadioBox
						name="clients"
						value={EClientSelection.SELECTED_CLIENTS}
						label="Sélectionner certains clients"
						onChange={onClientSelectionChange}
					/>
				</div>

				<Form onSubmit={onFormSubmit} className={classes["form"]}>
					{clientSelection === EClientSelection.SELECTED_CLIENTS && (
						<AutocompleteMultiSelectField
							name="clients"
							label="Choisir le ou les clients: "
							options={clientsOptions}
							onSelectionChange={handleClientSelectionChange}
							validationError={validationError ?? undefined}
						/>
					)}
					{clientSelection && (
						<>
							<DragAndDrop
								name="files"
								title="Glisser ou déposer ou"
								description="Formats acceptés : PDF, JPG, PNG, CSV, XLSX, doc, dox, txt Taille maximale : 100 Mo"
								onChange={handleFileChange}
							/>

							<div className={classes["buttons-container"]}>
								<a href={backUrl}>
									<Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED}>
										Annuler
									</Button>
								</a>
								<Button type="submit" rightIcon={<PaperAirplaneIcon />} isLoading={isSending}>
									Envoyer
								</Button>
							</div>
						</>
					)}
				</Form>
			</div>
		</DefaultDoubleSidePage>
	);
}
