import ChevronIcon from "@Assets/Icons/chevron.svg";
import PlusIcon from "@Assets/Icons/plus.svg";
import { IDashBoardFolder } from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
import Module from "@Front/Config/Module";
import classNames from "classnames";
import Customer, { Document } from "le-coffre-resources/dist/Customer";
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";
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";

type IProps = {
	customer: Customer;
	animationDelay?: number;
	folder: IDashBoardFolder;
	isArchived?: boolean;
	isOpened: boolean;
	onOpen: (id: string) => void;
	onClose: () => void;
};
type IState = {
	isOpenDeletionModal: boolean;
	willClose: boolean;
};

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,
			willClose: false,
		};
		this.toggleOpen = this.toggleOpen.bind(this);
		this.closeDeletionModal = this.closeDeletionModal.bind(this);
		this.openDeletionModal = this.openDeletionModal.bind(this);
		this.openComponent = this.openComponent.bind(this);
		this.closeComponent = this.closeComponent.bind(this);
	}
	public override render(): JSX.Element {
		const documentsAsked: Document[] | null = this.getDocumentsByStatus("ASKED");
		const otherDocuments: Document[] | null = this.getValidatedAndPendindDocuments();
		const redirectPath = Module.getInstance()
			.get()
			.modules.pages.Folder.pages.AskDocument.props.path.replace("[folderUid]", this.props.folder.uid ?? "");
		return (
			<div className={classes["root"]} data-opened={this.props.isOpened.toString()}>
				<Confirm
					isOpen={this.state.isOpenDeletionModal}
					onClose={this.closeDeletionModal}
					closeBtn
					header={"Supprimer la demande de document ?"}
					cancelText={"Cancel"}
					confirmText={"Confirmer"}>
					Êtes-vous vous de vouloir supprimer la demande de document ?
				</Confirm>

				<div className={classes["header"]} onClick={this.toggleOpen}>
					<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.toggleOpen}
					/>
				</div>

				{this.props.isOpened && (
					<div className={classes["container"]} data-will-close={this.state.willClose.toString()} 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}
							/>
							<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}
							/>
						</div>
						{!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 de documents</Button>}
							</div>
						)}
					</div>
				)}
			</div>
		);
	}

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


	private calculateDocumentsPercentageProgress(): number {
		if (!this.props.customer.documents) return 0;
		const totalDocuments: number = this.props.customer.documents.length;
		const numberDocumentsAsked: number = this.getDocumentsByStatus("ASKED")?.length || 0;
		return Math.round(((totalDocuments - numberDocumentsAsked) / totalDocuments) * 100);
	}

	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 toggleOpen(): void {
		if (this.props.isOpened) {
			this.closeComponent();
		} else {
			this.openComponent();
		}
	}

	private openComponent(): void {
		this.props.onOpen(this.props.folder.uid!);
	}

	private closeComponent(): void {
		if (this.state.willClose) return;
		this.setState({ willClose: true });
		window.setTimeout(() => {
			this.props.onClose();
			this.setState({
				willClose: false,
			});
		}, this.props.animationDelay);
	}

	private openDeletionModal(uid?: string): void {
		// TODO: call API to delete document
		this.setState({
			isOpenDeletionModal: true,
		});
	}
	private closeDeletionModal(): void {
		this.setState({
			isOpenDeletionModal: false,
		});
	}
}
