"use client";
import Customers from "@Front/Api/LeCoffreApi/Customer/Customers/Customers";
import Documents, { IGetDocumentsparams } from "@Front/Api/LeCoffreApi/Customer/Documents/Documents";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import DepositDocument from "@Front/Components/DesignSystem/DepositDocument";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Confirm from "@Front/Components/DesignSystem/Modal/Confirm";
import Typography, { ITypo } from "@Front/Components/DesignSystem/Typography";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import Customer, { Document, DocumentType } from "le-coffre-resources/dist/Customer";
import React, { useCallback, useEffect, useState } from "react";

import classes from "./classes.module.scss";
import { useRouter } from "next/router";
import JwtService from "@Front/Services/JwtService/JwtService";

type IProps = {};

export default function ClientDashboard(props: IProps) {
	const router = useRouter();
	let { folderUid } = router.query;
	const [documents, setDocuments] = useState<Document[] | null>(null);
	const [customer, setCustomer] = useState<Customer | null>(null);
	const [isAddDocumentModalVisible, setIsAddDocumentModalVisible] = useState<boolean>(false);

	const onCloseModalAddDocument = useCallback(() => {
		setIsAddDocumentModalVisible(false);
	}, []);

	const onOpenModalAddDocument = useCallback(() => {
		setIsAddDocumentModalVisible(true);
	}, []);

	useEffect(() => {
		async function getDocuments() {
			let jwt;
			if (typeof document !== "undefined") {
				jwt = JwtService.getInstance().decodeJwt();
			}
			if (!jwt || !jwt.email) return;
			const customers = await Customers.getInstance().get({
				where: { contact: { email: jwt.email }, office_folders: { some: { uid: folderUid } } },
			});
			const actualCustomer: Customer = customers[0]!;

			const query: IGetDocumentsparams = {
				where: { depositor: { uid: actualCustomer.uid }, folder_uid: folderUid as string },
				include: {
					files: true,
					document_history: true,
					document_type: true,
					depositor: true,
				},
			};

			const documentList = await Documents.getInstance().get(query);

			setDocuments(documentList);
			setCustomer(actualCustomer);
		}

		getDocuments();
	}, [folderUid]);

	const renderHeader = useCallback(() => {
		return (
			<div className={classes["header"]}>
				<div className={classes["text-container"]}>
					{/* TODO Get name from userStore */}
					<Typography typo={ITypo.H1} className={classes["title"]}>
						Bonjour {customer?.contact?.first_name.concat(" ", customer?.contact?.last_name)}
					</Typography>

					<Typography typo={ITypo.H2} className={classes["subtitle"]}>
						Documents à envoyer
					</Typography>

					<Typography typo={ITypo.P_16} className={classes["text"]}>
						Votre notaire est dans l'attente de documents pour valider votre dossier. Voici la liste des documents.Veuillez
						glisser / déposez chaque document dans la zone prévue à cet effet ou cliquez sur la zone puis sélectionnez le
						document correspondant. Si un des documents demandés ne vous concernent pas, veuillez contacter votre notaire à
						l’aide du bouton ci-dessus.
					</Typography>
				</div>
				<a href="mailto:g.texier@notaires.fr" target="_blank">
					<Button className={classes["button"]}>Contacter mon notaire</Button>
				</a>
			</div>
		);
	}, [customer]);

	return (
		<DefaultTemplate title={"Mon compte"} isPadding={false} hasHeaderLinks={false}>
			<div className={classes["root"]}>
				{renderHeader()}
				<div className={classes["sub-container"]}>
					<div className={classes["content"]}>
						{documents?.map((document) => (
							<DepositDocument document={document} key={document.uid} defaultFiles={document.files ?? []} />
						))}
					</div>
					<Typography typo={ITypo.H2}>Documents supplémentaires (facultatif)</Typography>
					<Typography typo={ITypo.P_16} className={classes["text"]}>
						Vous souhaitez envoyer d'autres documents à votre notaire ?
					</Typography>
					<Button variant={EButtonVariant.GHOST} className={classes["button"]} onClick={onOpenModalAddDocument}>
						Ajouter d'autres documents
					</Button>
				</div>
				<Confirm
					isOpen={isAddDocumentModalVisible}
					onClose={onCloseModalAddDocument}
					onAccept={onOpenModalAddDocument}
					closeBtn
					header={"Ajouter un document"}
					cancelText={"Annuler"}
					confirmText={"Déposer le document"}>
					<div className={classes["modal-content"]}>
						<Typography typo={ITypo.P_16} className={classes["text"]}>
							Vous souhaitez envoyer un autre document à votre notaire ?
						</Typography>
						<TextField placeholder="Nom du document" />
						<Typography typo={ITypo.P_16} className={classes["text"]}>
							Glissez / Déposez votre document dans la zone prévue à cet effet ou cliquez sur la zone puis sélectionnez le
							document correspondant.
						</Typography>
						<DepositDocument
							document={Document.hydrate<Document>({
								document_type: DocumentType.hydrate<DocumentType>({
									name: "Document annexe",
								}),
							})}
						/>
					</div>
				</Confirm>
			</div>
		</DefaultTemplate>
	);
}
