import ChevronIcon from "@Assets/Icons/chevron.svg";
import Folders, { IPutFoldersParams } from "@Front/Api/LeCoffreApi/SuperAdmin/Folders/Folders";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import FolderBoxInformation, { EFolderBoxInformationType } from "@Front/Components/DesignSystem/FolderBoxInformation";
import InputField from "@Front/Components/DesignSystem/Form/Elements/InputField";
import Confirm from "@Front/Components/DesignSystem/Modal/Confirm";
import QuantityProgressBar from "@Front/Components/DesignSystem/QuantityProgressBar";
import Typography, { ITypo, ITypoColor } from "@Front/Components/DesignSystem/Typography";
import DefaultNotaryDashboard, { IDashBoardFolder } from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
import Module from "@Front/Config/Module";
import { OfficeFolder } from "le-coffre-resources/dist/Customer";
import { EDocumentStatus } from "le-coffre-resources/dist/Notary/Document";
import Link from "next/link";
import { NextRouter, useRouter } from "next/router";
import { ChangeEvent } from "react";

import BasePage from "../../Base";
import classes from "./classes.module.scss";
import ClientSection from "./ClientSection";

type IProps = {};

type IPropsClass = IProps & {
	router: NextRouter;
	selectedFolderUid: string;
};

type IState = {
	selectedFolder: IDashBoardFolder | null;
	isArchivedModalOpen: boolean;
	inputArchivedDescripton: string;
};
class FolderInformationClass extends BasePage<IPropsClass, IState> {
	public constructor(props: IPropsClass) {
		super(props);
		this.state = {
			selectedFolder: null,
			isArchivedModalOpen: false,
			inputArchivedDescripton: "",
		};
		this.onSelectedFolder = this.onSelectedFolder.bind(this);
		this.openArchivedModal = this.openArchivedModal.bind(this);
		this.closeArchivedModal = this.closeArchivedModal.bind(this);
		this.onArchivedModalAccepted = this.onArchivedModalAccepted.bind(this);
		this.getCompletionNumber = this.getCompletionNumber.bind(this);
		this.onArchivedDescriptionInputChange = this.onArchivedDescriptionInputChange.bind(this);
		this.deleteFolder = this.deleteFolder.bind(this);
	}

	// TODO: Message if the user has not created any folder yet
	// TODO: get the selected folder from the api in componentDidMount
	public override render(): JSX.Element {
		const redirectPathEditCollaborators = Module.getInstance()
			.get()
			.modules.pages.Folder.pages.EditCollaborators.props.path.replace("[folderUid]", this.props.selectedFolderUid);
		return (
			<DefaultNotaryDashboard
				title={"Dossier"}
				onSelectedFolder={this.onSelectedFolder}
				isArchived={false}
				mobileBackText="Retour aux dossiers">
				<div className={classes["root"]}>
					{this.state.selectedFolder ? (
						<div className={classes["folder-informations"]}>
							<div className={classes["folder-header"]}>
								<div className={classes["header"]}>
									<div className={classes["title"]}>
										<Typography typo={ITypo.H1Bis}>Informations du dossier</Typography>
									</div>
									<Link href={redirectPathEditCollaborators}>
										<Button variant={EButtonVariant.LINE} icon={ChevronIcon}>
											Modifier les collaborateurs
										</Button>
									</Link>
								</div>
								<FolderBoxInformation folder={this.state.selectedFolder} type={EFolderBoxInformationType.INFORMATIONS} />
								<div className={classes["second-box"]}>
									<FolderBoxInformation folder={this.state.selectedFolder} type={EFolderBoxInformationType.DESCRIPTION} />
								</div>
								<div className={classes["progress-bar"]}>
									<QuantityProgressBar
										title="Complétion du dossier"
										total={100}
										currentNumber={this.getCompletionNumber()}
									/>
								</div>
								{this.doesFolderHaveCustomer() && <ClientSection folder={this.state.selectedFolder} />}
							</div>

							{!this.doesFolderHaveCustomer() && <ClientSection folder={this.state.selectedFolder} />}

							<div className={classes["button-container"]}>
								<Button variant={EButtonVariant.GHOST} onClick={this.openArchivedModal}>
									Archiver le dossier
								</Button>
								{!this.doesFolderHaveCustomer() && (
									<span className={classes["delete-folder"]} onClick={this.deleteFolder}>
										<Button variant={EButtonVariant.SECONDARY}>Supprimer le dossier</Button>
									</span>
								)}
							</div>
							<Confirm
								isOpen={this.state.isArchivedModalOpen}
								onAccept={this.onArchivedModalAccepted}
								onClose={this.closeArchivedModal}
								closeBtn
								header={"Archiver le dossier ?"}
								cancelText={"Annuler"}
								confirmText={"Archiver"}>
								<div className={classes["modal-title"]}>
									<Typography typo={ITypo.P_16}>Souhaitez-vous vraiment archiver le dossier ?</Typography>
								</div>
								<InputField
									name="archived_description"
									fakeplaceholder="Description"
									textarea
									onChange={this.onArchivedDescriptionInputChange}
								/>
							</Confirm>
						</div>
					) : (
						<div className={classes["no-folder-selected"]}>
							<Typography typo={ITypo.H1Bis}>Informations du dossier</Typography>
							<div className={classes["choose-a-folder"]}>
								<Typography typo={ITypo.P_18} color={ITypoColor.GREY}>
									Sélectionnez un dossier
								</Typography>
							</div>
						</div>
					)}
				</div>
			</DefaultNotaryDashboard>
		);
	}
	public override async componentDidMount() {
		this.setState({
			selectedFolder: (await this.getFolder()) as IDashBoardFolder,
		});
	}

	private async deleteFolder() {
		if (!this.state.selectedFolder?.uid) return;
		await Folders.getInstance().delete(this.state.selectedFolder.uid);
		this.props.router.push(Module.getInstance().get().modules.pages.Folder.props.path);
	}

	private getCompletionNumber() {
		const documents = this.state.selectedFolder?.documents;
		if (!documents) return 0;
		const totalDocuments = documents.length;
		const refusedDocuments = documents.filter((document) => document.document_status === EDocumentStatus.REFUSED).length ?? 0;
		const askedDocuments = documents.filter((document) => document.document_status === EDocumentStatus.ASKED).length ?? 0;
		const depositedDocuments = totalDocuments - askedDocuments - refusedDocuments;
		const percentage = (depositedDocuments / totalDocuments) * 100;
		return isNaN(percentage) ? 0 : percentage;
	}

	private doesFolderHaveCustomer(): boolean {
		if (!this.state.selectedFolder?.office_folder_has_customers) return false;
		return this.state.selectedFolder?.office_folder_has_customers!.length > 0;
	}

	private onSelectedFolder(folder: IDashBoardFolder): void {
		this.setState({ selectedFolder: folder });
	}

	private openArchivedModal(): void {
		this.setState({ isArchivedModalOpen: true });
	}

	private closeArchivedModal(): void {
		this.setState({ isArchivedModalOpen: false });
	}

	private onArchivedDescriptionInputChange(e: ChangeEvent<HTMLInputElement>) {
		this.setState({ inputArchivedDescripton: e.target.value });
	}

	private async onArchivedModalAccepted() {
		if (!this.state.selectedFolder) return;
		const folder = this.state.selectedFolder;
		folder.archived_description = this.state.inputArchivedDescripton;
		await Folders.getInstance().archive(this.state.selectedFolder.uid ?? "", folder as IPutFoldersParams);
		this.closeArchivedModal();
		this.props.router.push(Module.getInstance().get().modules.pages.Folder.props.path);
	}

	private async getFolder(): Promise<OfficeFolder> {
		const query = {
			q: {
				deed: { include: { deed_type: true } },
				office: true,
				office_folder_has_customers: {
					include: {
						customer: {
							include: {
								contact: true,
								documents: {
									include: {
										folder: true,
										document_type: true,
										files: true,
									},
								},
							},
						},
					},
				},
				documents: {
					include: {
						depositor: {
							include: {
								contact: true,
							},
						},
					},
				},
			},
		};

		const folder = await Folders.getInstance().getByUid(this.props.selectedFolderUid, query);
		return folder;
	}
}

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