import React, { useCallback, useEffect, useState } from "react";
import Typography, { ITypo, ITypoColor } 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, { 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/Modal/Confirm";

export default function Rib() {
	const [documentList, setDocumentList] = useState<File[]>([]);
	const router = useRouter();
	let { officeUid } = router.query;
	const [fileUrl, setFileUrl] = useState<string>("");
	const [fileName, setFileName] = useState<string>("");
	const [key, setKey] = useState<string>("");
	const [isRibModalOpen, setIsRibModalOpen] = useState<boolean>(false);
	const [isDeleteModalOpen, setIsDeleteModalOpen] = useState<boolean>(false);

	//Put fetch data in a useCallback

	const fetchData = useCallback(async () => {
		try {
			const blob = await OfficeRib.getInstance().getRibStream();

			const ribUrl = URL.createObjectURL(blob);

			setFileUrl(ribUrl);
			setKey(key);
			setFileName(key);
		} catch (error) {
			setFileUrl("");
			setFileName("");
			setKey("");
		}
	}, [officeUid]);

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

	function downloadFile() {
		if (!fileUrl) return;
		const a = document.createElement("a");
		a.style.display = "none";
		a.href = fileUrl;
		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={ITypo.H1} color={ITypoColor.BLACK} className={classes["title"]}>
					Rib de l'office
				</Typography>

				{!fileUrl && (
					<div className={classes["document-container"]}>
						<div className={classes["file-container"]}>
							<Typography typo={ITypo.P_18} color={ITypoColor.GREY}>
								Aucun RIB n'a été déposé pour cet office
							</Typography>
						</div>
						<div className={classes["footer"]}>
							<div className={classes["buttons-container"]}>
								<Button onClick={openRibModal}>Déposer un RIB</Button>
							</div>
						</div>
					</div>
				)}

				{fileUrl && (
					<div className={classes["document-container"]}>
						<div className={classes["file-container"]}>{fileUrl && <FilePreview href={fileUrl} fileName={fileName} />}</div>
						<div className={classes["footer"]}>
							<Button onClick={openDeleteModal} variant={EButtonVariant.SECONDARY}>
								Supprimer
							</Button>
							<Button onClick={openRibModal} variant={EButtonVariant.GHOST}>
								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={ITypo.H1} color={ITypoColor.BLACK} className={classes["title"]}>
						Supprimer le RIB
					</Typography>
					<Typography typo={ITypo.P_18} color={ITypoColor.GREY}>
						Voulez-vous vraiment supprimer le RIB de votre office ?
					</Typography>
				</Confirm>
			</div>
		</DefaultTemplate>
	);
}
