import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
import OfficeFolderAnchors from "@Front/Api/LeCoffreApi/Notary/OfficeFolderAnchors/OfficeFolderAnchors";
import Loader from "@Front/Components/DesignSystem/Loader";
import DefaultNotaryDashboard from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import { EDocumentStatus } from "le-coffre-resources/dist/Notary/Document";
import { useParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";

import classes from "./classes.module.scss";
import ClientView from "./ClientView";
import InformationSection from "./InformationSection";
import NoClientView from "./NoClientView";
import AnchoringAlertInfo from "./elements/AnchoringAlertInfo";
import AnchoringModal from "./elements/AnchoringModal";
import useOpenable from "@Front/Hooks/useOpenable";
import AnchoringAlertSuccess from "./elements/AnchoringAlertSuccess";
import DownloadAnchoringProofModal from "./elements/DownloadAnchoringProofModal";
import RequireAnchoringModal from "./elements/RequireAnchoringModal";
import ArchiveModal from "./elements/ArchiveModal";

export enum AnchorStatus {
	"VERIFIED_ON_CHAIN" = "VERIFIED_ON_CHAIN",
	"ANCHORING" = "ANCHORING",
	"NOT_ANCHORED" = "NOT_ANCHORED",
}

type IProps = { isArchived?: boolean };

export default function FolderInformation(props: IProps) {
	const { isArchived = false } = props;
	const [anchorStatus, setAnchorStatus] = useState<AnchorStatus>(AnchorStatus.NOT_ANCHORED);
	const [isLoading, setIsLoading] = useState<boolean>(true);
	const [folder, setFolder] = useState<OfficeFolder | null>(null);
	const anchoringModal = useOpenable();
	const downloadAnchoringProofModal = useOpenable();
	const requireAnchoringModal = useOpenable();
	const archiveModal = useOpenable();

	const params = useParams();
	const folderUid = params["folderUid"] as string;

	const progress = useMemo(() => {
		let total = 0;
		let validatedDocuments = 0;
		folder?.customers?.forEach((customer) => {
			const documents = customer.documents;
			total += documents?.length ?? 0;
			validatedDocuments += documents?.filter((document) => document.document_status === EDocumentStatus.VALIDATED).length ?? 0;
		});
		if (total === 0) return 0;
		const percentage = (validatedDocuments / total) * 100;
		return isNaN(percentage) ? 0 : percentage;
	}, [folder]);

	const doesFolderHaveClient = useMemo(() => folder?.customers?.length !== 0, [folder]);

	const fetchFolder = useCallback(async () => {
		if (!folderUid) return;
		const query = {
			q: {
				deed: { include: { deed_type: true, document_types: true } },
				office: true,
				customers: {
					include: {
						contact: true,
						documents: {
							include: {
								folder: true,
								document_type: true,
								files: true,
							},
						},
					},
				},
				documents: {
					include: {
						depositor: {
							include: {
								contact: true,
							},
						},
					},
				},
				folder_anchor: true,
				notes: {
					include: {
						customer: true,
					},
				},
			},
		};

		return Folders.getInstance()
			.getByUid(folderUid, query)
			.then((folder) => setFolder(folder));
	}, [folderUid]);

	const fetchAnchorStatus = useCallback(() => {
		return OfficeFolderAnchors.getInstance()
			.getByUid(folderUid)
			.then((anchorStatus) =>
				setAnchorStatus(anchorStatus.status === "VERIFIED_ON_CHAIN" ? AnchorStatus.VERIFIED_ON_CHAIN : AnchorStatus.ANCHORING),
			)
			.catch(() => setAnchorStatus(AnchorStatus.NOT_ANCHORED));
	}, [folderUid]);

	const fetchData = useCallback(() => {
		setIsLoading(true);
		return fetchFolder()
			.then(() => fetchAnchorStatus())
			.catch((e) => console.error(e))
			.finally(() => setIsLoading(false));
	}, [fetchAnchorStatus, fetchFolder]);

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

	const onAnchorSuccess = useCallback(() => fetchData().then(downloadAnchoringProofModal.open), [fetchData, downloadAnchoringProofModal]);

	const onArchive = useCallback(() => {
		if (anchorStatus === AnchorStatus.NOT_ANCHORED) return requireAnchoringModal.open();
		archiveModal.open();
	}, [anchorStatus, archiveModal, requireAnchoringModal]);

	return (
		<DefaultNotaryDashboard title={"Dossier"} isArchived={isArchived} mobileBackText="Retour aux dossiers">
			{!isLoading && (
				<div className={classes["root"]}>
					<InformationSection
						folder={folder}
						progress={progress}
						onArchive={onArchive}
						anchorStatus={anchorStatus}
						isArchived={isArchived}
					/>
					{progress === 100 && anchorStatus === AnchorStatus.NOT_ANCHORED && (
						<AnchoringAlertInfo onAnchor={anchoringModal.open} />
					)}
					{anchorStatus === AnchorStatus.VERIFIED_ON_CHAIN && (
						<AnchoringAlertSuccess
							onDownloadAnchoringProof={downloadAnchoringProofModal.open}
							onArchive={archiveModal.open}
							isArchived={isArchived}
						/>
					)}
					{folder && !doesFolderHaveClient && <NoClientView folder={folder} anchorStatus={anchorStatus} />}
					{folder && doesFolderHaveClient && <ClientView folder={folder} anchorStatus={anchorStatus} />}
					{folderUid && anchorStatus === AnchorStatus.NOT_ANCHORED && (
						<AnchoringModal
							isOpen={anchoringModal.isOpen}
							onClose={anchoringModal.close}
							folderUid={folderUid}
							onAnchorSuccess={onAnchorSuccess}
						/>
					)}
					{folder && anchorStatus === AnchorStatus.VERIFIED_ON_CHAIN && (
						<DownloadAnchoringProofModal
							isOpen={downloadAnchoringProofModal.isOpen}
							onClose={downloadAnchoringProofModal.close}
							folder={folder}
						/>
					)}
					<RequireAnchoringModal
						isOpen={requireAnchoringModal.isOpen}
						onClose={requireAnchoringModal.close}
						onAnchor={anchoringModal.open}
					/>
					{folderUid && <ArchiveModal isOpen={archiveModal.isOpen} onClose={archiveModal.close} folderUid={folderUid} />}
				</div>
			)}
			{isLoading && (
				<div className={classes["loader-container"]}>
					<div className={classes["loader"]}>
						<Loader />
					</div>
				</div>
			)}
		</DefaultNotaryDashboard>
	);
}
