import ChevronIcon from "@Assets/Icons/chevron.svg";
import PlusIcon from "@Assets/Icons/plus.svg";
import Documents from "@Front/Api/LeCoffreApi/SuperAdmin/Documents/Documents";
import Module from "@Front/Config/Module";
import classNames from "classnames";
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
import { Customer, Document } from "le-coffre-resources/dist/Notary";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";
import Image from "next/image";
import Link from "next/link";
import React from "react";

import Button, { EButtonVariant } from "../Button";
import Confirm from "../Modal/Confirm";
import QuantityProgressBar from "../QuantityProgressBar";
import classes from "./classes.module.scss";
import DocumentList from "./DocumentList";
import UserFolderHeader from "./UserFolderHeader";

type IProps = {
	customer: Customer;
	animationDelay?: number;
	folder: OfficeFolder;
	isArchived?: boolean;
	isOpened: boolean;
	onChange: (id: string) => void;
};
type IState = {
	isOpenDeletionModal: boolean;
	selectedDocumentToDelete: string;
};

export default class UserFolder extends React.Component<IProps, IState> {
	static defaultProps = {
		animationDelay: 300,
		isArchived: false,
	};
	public rootRefElement = React.createRef<HTMLDivElement>();

	constructor(props: IProps) {
		super(props);
		this.state = {
			isOpenDeletionModal: false,
			selectedDocumentToDelete: "",
		};
		this.closeDeletionModal = this.closeDeletionModal.bind(this);
		this.openDeletionModal = this.openDeletionModal.bind(this);
		this.changeUserFolder = this.changeUserFolder.bind(this);
		this.deleteAskedDocument = this.deleteAskedDocument.bind(this);
	}
	public override render(): JSX.Element {
		const documentsAsked: Document[] | null = [
			...(this.getDocumentsByStatus("ASKED") ?? []),
			...(this.getDocumentsByStatus("REFUSED") ?? []),
		];
		const otherDocuments: Document[] | null = this.getValidatedAndPendindDocuments();
		const redirectPath = Module.getInstance()
			.get()
			.modules.pages.Folder.pages.AskDocument.props.path.replace("[folderUid]", this.props.folder.uid ?? "")
			.replace("[customerUid]", this.props.customer.uid ?? "");
		return (
			<div className={classes["root"]} data-opened={this.props.isOpened.toString()}>
				<Confirm
					isOpen={this.state.isOpenDeletionModal}
					onClose={this.closeDeletionModal}
					onAccept={this.deleteAskedDocument}
					closeBtn
					header={"Supprimer la demande de document ?"}
					cancelText={"Annuler"}
					confirmText={"Confirmer"}>
					Êtes-vous vous de vouloir supprimer la demande de document ?
				</Confirm>

				<div className={classes["header"]} onClick={this.changeUserFolder}>
					<UserFolderHeader customer={this.props.customer} folder={this.props.folder} isArchived={this.props.isArchived} />
					<Image
						src={ChevronIcon}
						alt="chevron open close"
						className={classNames(classes["chevron-icon"], this.props.isOpened && classes["open"])}
						onClick={this.changeUserFolder}
					/>
				</div>

				{this.props.isOpened && (
					<div className={classes["container"]} ref={this.rootRefElement}>
						<QuantityProgressBar
							title="Complétion du dossier client"
							total={100}
							currentNumber={this.calculateDocumentsPercentageProgress()}
						/>
						<div className={classes["content"]}>
							<DocumentList
								documents={documentsAsked}
								title="Documents demandés"
								openDeletionModal={this.openDeletionModal}
								folderUid={this.props.folder.uid!}
								className={classes["documents-asked"]}
							/>
							<DocumentList
								documents={otherDocuments}
								title="Documents à valider / validés"
								subtitle={
									otherDocuments && otherDocuments?.length > 0
										? "Vous avez des documents à valider."
										: "Vous n'avez aucun document à valider"
								}
								openDeletionModal={this.openDeletionModal}
								folderUid={this.props.folder.uid!}
							/>
							{!this.props.isArchived && (
								<div className={classes["button-container"]}>
									<Link href={redirectPath}>
										<Button variant={EButtonVariant.LINE} icon={PlusIcon}>
											Demander un autre document{" "}
										</Button>
									</Link>
									<Button disabled={documentsAsked ? false : true}>Envoyer un mail de demande</Button>
								</div>
							)}
						</div>
					</div>
				)}
			</div>
		);
	}

	public override componentDidUpdate(prevProps: IProps): void {
		this.rootRefElement.current?.style.setProperty("--animation-delay", this.props.animationDelay!.toString().concat("ms"));
	}

	private async deleteAskedDocument() {
		try {
			await Documents.getInstance().delete(this.state.selectedDocumentToDelete);
			window.location.reload();
		} catch (e) {
			console.error(e);
		}
	}

	private calculateDocumentsPercentageProgress(): number {
		if (!this.props.customer.documents) return 0;
		const documents = this.props.customer.documents.filter((document) => document.folder?.uid === this.props.folder.uid);
		const totalDocuments: number = documents.length;
		const numberDocumentsRefused: number = this.getDocumentsByStatus(EDocumentStatus.REFUSED)?.length || 0;
		const numberDocumentsAsked: number = this.getDocumentsByStatus(EDocumentStatus.ASKED)?.length || 0;
		const depositedDocuments: number = totalDocuments - numberDocumentsAsked - numberDocumentsRefused;

		const percentage = (depositedDocuments / totalDocuments) * 100;
		return isNaN(percentage) ? 0 : percentage;
	}

	private getDocumentsByStatus(status: string): Document[] | null {
		if (!this.props.customer.documents) return null;
		const filteredDocuments = this.props.customer.documents.filter(
			(document) => document.document_status === status && document.folder?.uid === this.props.folder.uid,
		);
		return filteredDocuments;
	}

	// Get all documents Validated, pending
	private getValidatedAndPendindDocuments(): Document[] | null {
		const pendingDocuments = this.getDocumentsByStatus(EDocumentStatus.DEPOSITED);
		const validatedDocuments = this.getDocumentsByStatus(EDocumentStatus.VALIDATED);
		if (!pendingDocuments && !validatedDocuments) return null;
		pendingDocuments?.push(...validatedDocuments!);
		return pendingDocuments;
	}

	// TODO: REFACTO this because the other documents should only be correspond to other documents of the props folders
	// private getOtherDocuments(documentToExclude: Document[] | null): Document[] | null {
	// 	if (!this.props.customer.documents) return null;
	// 	if (!documentToExclude) return this.props.customer.documents;
	// 	return this.props.customer.documents.filter((document) => !documentToExclude.includes(document));
	// }

	private changeUserFolder() {
		this.props.onChange(this.props.customer.uid!);
	}

	private openDeletionModal(uid?: string): void {
		if (!uid) return;

		this.setState({
			isOpenDeletionModal: true,
			selectedDocumentToDelete: uid,
		});
	}
	private closeDeletionModal(): void {
		this.setState({
			isOpenDeletionModal: false,
		});
	}
}
