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 OfficeRib from "@Front/Api/LeCoffreApi/Notary/OfficeRib/OfficeRib";
import DepositRib from "@Front/Components/DesignSystem/DepositRib";
import Confirm from "@Front/Components/DesignSystem/OldModal/Confirm";
import Loader from "@Front/Components/DesignSystem/Loader";

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 blob = await OfficeRib.getInstance().getRibStream();
			setFileBlob(blob.blob);
			setKey(key);
			setFileName(blob.fileName);
		} 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 formData = new FormData();
		formData.append("file", documentList[0]!, documentList[0]!.name);

		await OfficeRib.getInstance().post(formData);

		onCloseRibModal();
		fetchData();
	}

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

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

	async function onDeleteModalAccepted() {
		await OfficeRib.getInstance().delete();

		onCloseDeleteModal();
		fetchData();
	}

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

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

	const onDocumentChange = (documentList: File[]) => {
		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>
	);
}
