import OfficeFolderAnchors from "@Front/Api/LeCoffreApi/Notary/OfficeFolderAnchors/OfficeFolderAnchors";
import Loader from "@Front/Components/DesignSystem/Loader";
import DefaultNotaryDashboard from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
import useOpenable from "@Front/Hooks/useOpenable";
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 AnchoringAlertInfo from "./elements/AnchoringAlertInfo";
import AnchoringAlertSuccess from "./elements/AnchoringAlertSuccess";
import AnchoringModal from "./elements/AnchoringModal";
import ArchiveAlertWarning from "./elements/ArchiveAlertWarning";
import ArchiveModal from "./elements/ArchiveModal";
import DownloadAnchoringProofModal from "./elements/DownloadAnchoringProofModal";
import RequireAnchoringModal from "./elements/RequireAnchoringModal";
import InformationSection from "./InformationSection";
import NoClientView from "./NoClientView";
import AnchoringProcessingInfo from "./elements/AnchoringProcessingInfo";

import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import EFolderStatus from "le-coffre-resources/dist/Customer/EFolderStatus";

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<any>(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: any) => {
			const documents = customer.documents.filter((document: any) => document.depositor);
			total += documents?.length ?? 0;
			validatedDocuments += documents?.filter((document: any) => 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: {
							where: {
								folder_uid: folderUid,
							},
							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));
		*/

		// TODO: review
		return FolderService.getFolderByUid(folderUid).then(async (process: any) => {
			if (process) {
				const folder: any = process.processData;
				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(() => {
				// TODO: review
				//return fetchAnchorStatus()
			})
			.catch((e) => console.error(e))
			.finally(() => setIsLoading(false));
	}, [fetchAnchorStatus, fetchFolder]);

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

	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*/ folder.status !== EFolderStatus.ARCHIVED && (
						<AnchoringAlertInfo onAnchor={anchoringModal.open} />
					)}
					{!isArchived && anchorStatus === AnchorStatus.VERIFIED_ON_CHAIN && (
						<AnchoringAlertSuccess
							onDownloadAnchoringProof={downloadAnchoringProofModal.open}
							onArchive={archiveModal.open}
							isArchived={isArchived}
						/>
					)}
					{!isArchived && anchorStatus === AnchorStatus.ANCHORING && <AnchoringProcessingInfo />}
					{isArchived && folderUid && (
						<ArchiveAlertWarning folderUid={folderUid} onDownloadAnchoringProof={downloadAnchoringProofModal.open} />
					)}
					{folder && !doesFolderHaveClient && <NoClientView folder={folder} anchorStatus={anchorStatus} />}
					{folder && doesFolderHaveClient && <ClientView folder={folder} anchorStatus={anchorStatus} />}
					{folderUid && (
						<AnchoringModal
							isOpen={anchoringModal.isOpen}
							onClose={anchoringModal.close}
							folderUid={folderUid}
							onAnchorSuccess={fetchData}
						/>
					)}
					{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>
	);
}
