import React, { useCallback, useEffect, useState } from "react";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import classes from "./classes.module.scss";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import FilePreview from "@Front/Components/DesignSystem/FilePreview";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { useRouter } from "next/router";
import DepositRib from "@Front/Components/DesignSystem/DepositRib";
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
import Loader from "@Front/Components/DesignSystem/Loader";

import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import OfficeRibService from "src/common/Api/LeCoffreApi/sdk/OfficeRibService";
import WatermarkService from "@Front/Services/WatermarkService";

export default function Rib() {
	const [documentList, setDocumentList] = useState<File[]>([]);
	const router = useRouter();
	let { officeUid } = router.query;
	const [fileBlob, setFileBlob] = useState<Blob>();
	const [fileName, setFileName] = useState<string>("");
	const [key, setKey] = useState<string>("");
	const [isRibModalOpen, setIsRibModalOpen] = useState<boolean>(false);
	const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);
	const [isLoading, setIsLoading] = useState<boolean>(true);
	//Put fetch data in a useCallback

	const fetchData = useCallback(async () => {
		try {
			const officeRib: any = (await OfficeRibService.getOfficeRib()).processData;
			const fileBlob: Blob = new Blob([officeRib.file_blob.data], { type: officeRib.file_blob.type });
			setFileBlob(fileBlob);
			setKey(key);
			setFileName(officeRib.file_name);
		} catch (error) {
			setFileBlob(undefined);
			setFileName("");
			setKey("");
		}
		setIsLoading(false);
	}, [key]);

	useEffect(() => {
		fetchData();
	}, [fetchData, officeUid]);

	function downloadFile() {
		if (!fileBlob) return;
		const url = window.URL.createObjectURL(fileBlob);
		const a = document.createElement("a");
		a.style.display = "none";
		a.href = url;
		a.download = key;
		document.body.appendChild(a);
		a.click();
	}

	async function onRibModalAccepted() {
		// Send documents to the backend for validation
		if (documentList.length === 0) return;
		const file = documentList[0]!;

		LoaderService.getInstance().show();
		// Add watermark to the file before processing
		WatermarkService.getInstance().addWatermark(file).then(async (watermarkedFile) => {
			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 = `aplc_${file.name.split('.')[0]}_${strDate}.${file.name.split('.').pop()}`;

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

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

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

					OfficeRibService.createOfficeRib(fileData, validatorId).then(() => {
						LoaderService.getInstance().hide();
						onCloseRibModal();

						setIsLoading(true);
						setTimeout(() => fetchData(), 2000);
					});
				}
			};
			reader.readAsArrayBuffer(watermarkedFile);
		});
	}

	function openRibModal(): void {
		setIsRibModalOpen(true);
	}

	function onCloseRibModal(): void {
		setDocumentList([]);
		setIsRibModalOpen(false);
	}

	async function onDeleteModalAccepted() {
		LoaderService.getInstance().show();
		OfficeRibService.getOfficeRib().then((process: any) => {
			if (process) {
				OfficeRibService.updateOfficeRib(process, { isDeleted: 'true', archived_at: new Date().toISOString() }).then(() => {
					LoaderService.getInstance().hide();
					onCloseDeleteModal();

					setIsLoading(true);
					setTimeout(() => fetchData(), 2000);
				});
			}
		});
	}

	function openDeleteModal(): void {
		setIsDeleteModalOpen(true);
	}

	function onCloseDeleteModal(): void {
		setIsDeleteModalOpen(false);
	}

	const onDocumentChange = (documentList: File[]) => {
		if (documentList.length === 0) return;
		if (fileBlob) {
			LoaderService.getInstance().show();
			OfficeRibService.getOfficeRib().then((process: any) => {
				if (process) {
					OfficeRibService.updateOfficeRib(process, { isDeleted: 'true', archived_at: new Date().toISOString() }).then(() => {
						LoaderService.getInstance().hide();
						onCloseDeleteModal();

						setIsLoading(true);
						setDocumentList(documentList);
					});
				}
			});
		} else {
			setDocumentList(documentList);
		}
	};

	return (
		<DefaultTemplate title={"RIB"}>
			<div className={classes["root"]}>
				<Typography typo={ETypo.DISPLAY_LARGE} color={ETypoColor.COLOR_GENERIC_BLACK} className={classes["title"]}>
					RIB de l'office
				</Typography>
				{isLoading && (
					<div className={classes["loader-container"]}>
						<div className={classes["loader"]}>
							<Loader />
						</div>
					</div>
				)}
				{!isLoading && !fileBlob && (
					<>
						<div className={classes["document-container"]}>
							<div>
								<Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.COLOR_NEUTRAL_500}>
									Aucun RIB n'a été déposé pour cet office
								</Typography>
							</div>
						</div>
						<div className={classes["footer"]}>
							<div className={classes["buttons-container"]}>
								<Button onClick={openRibModal}>Déposer un RIB</Button>
							</div>
						</div>
					</>
				)}

				{!isLoading && fileBlob && (
					<>
						<div className={classes["document-container"]}>
							<div className={classes["file-container"]}>
								{fileBlob && <FilePreview href={fileBlob ? URL.createObjectURL(fileBlob) : ""} fileName={fileName} />}
							</div>
						</div>
						<div className={classes["footer"]}>
							<div className={classes["buttons-container"]}>
								<Button onClick={openDeleteModal} variant={EButtonVariant.SECONDARY}>
									Supprimer
								</Button>
								<Button onClick={openRibModal} variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED}>
									Modifier
								</Button>
								<Button onClick={downloadFile}>Télécharger</Button>
							</div>
						</div>
					</>
				)}

				<Confirm
					isOpen={isRibModalOpen}
					onAccept={onRibModalAccepted}
					onClose={onCloseRibModal}
					closeBtn
					cancelText={"Annuler"}
					confirmText={"Enregistrer"}>
					<DepositRib onChange={onDocumentChange} />
				</Confirm>

				<Confirm
					isOpen={isDeleteModalOpen}
					onAccept={onDeleteModalAccepted}
					onClose={onCloseDeleteModal}
					closeBtn
					cancelText={"Annuler"}
					confirmText={"Supprimer"}>
					<Typography typo={ETypo.DISPLAY_LARGE} color={ETypoColor.COLOR_GENERIC_BLACK} className={classes["title"]}>
						Supprimer le RIB
					</Typography>
					<Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.COLOR_NEUTRAL_500}>
						Voulez-vous vraiment supprimer le RIB de votre office ?
					</Typography>
				</Confirm>
			</div>
		</DefaultTemplate>
	);
}
