import Module from "@Front/Config/Module";
import classNames from "classnames";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import { EDocumentStatus } from "le-coffre-resources/dist/Notary/Document";
import Link from "next/link";
import { useRouter } from "next/router";
import React from "react";

import FolderContainer from "../FolderContainer";
import classes from "./classes.module.scss";

type IProps = {
	folders: OfficeFolder[];
	isArchived: boolean;
	onSelectedFolder?: (folder: OfficeFolder) => void;
	onCloseLeftSide?: () => void;
};

type IPropsClass = IProps & {
	selectedFolder: string;
};

type IState = {};

class FolderListClass extends React.Component<IPropsClass, IState> {
	private redirectPath: string = this.props.isArchived
		? Module.getInstance().get().modules.pages.Folder.pages.FolderArchived.pages.FolderInformation.props.path
		: Module.getInstance().get().modules.pages.Folder.pages.FolderInformation.props.path;
	public override render(): JSX.Element {
		return <div className={classNames(classes["root"], this.props.isArchived ? classes["archived"] : "")}>{this.renderFolders()}</div>;
	}

	private renderFolders(): JSX.Element[] {
		const pendingFolders = this.props.folders
			.filter((folder) => {
				const pendingDocuments = (folder.documents ?? []).filter(
					(document) => document.document_status === EDocumentStatus.DEPOSITED,
				);
				return pendingDocuments.length >= 1;
			})
			.sort((folder1, folder2) => {
				return folder1.created_at! > folder2.created_at! ? -1 : 1;
			});

		const otherFolders = this.props.folders
			.filter((folder) => {
				const pendingDocuments = (folder.documents ?? []).filter(
					(document) => document.document_status === EDocumentStatus.DEPOSITED,
				);
				return pendingDocuments.length === 0;
			})
			.sort((folder1, folder2) => {
				return folder1.created_at! > folder2.created_at! ? -1 : 1;
			});

		return [...pendingFolders, ...otherFolders].map((folder) => {
			return (
				<div
					onClick={this.props.onCloseLeftSide}
					key={folder.uid}
					className={folder.uid === this.props.selectedFolder ? classes["active"] : ""}>
					<Link href={this.redirectPath.replace("[folderUid]", folder.uid ?? "")}>
						<FolderContainer folder={folder} onSelectedFolder={this.props.onSelectedFolder} />;
					</Link>
				</div>
			);
		});
	}
}

export default function FolderList(props: IProps) {
	const router = useRouter();
	let { folderUid } = router.query;
	folderUid = folderUid as string;
	return <FolderListClass {...props} selectedFolder={folderUid} />;
}
