"use client";
import Documents, { IGetDocumentsparams } from "@Front/Api/LeCoffreApi/Customer/Documents/Documents";

import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";

import Customer, { Document, DocumentType } from "le-coffre-resources/dist/Customer";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { DocumentNotary, type OfficeFolder as OfficeFolderNotary } from "le-coffre-resources/dist/Notary";

import classes from "./classes.module.scss";
import { useRouter } from "next/router";
import JwtService, { ICustomerJwtPayload } from "@Front/Services/JwtService/JwtService";
import Folders from "@Front/Api/LeCoffreApi/Customer/Folders/Folders";

import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag";
import DefaultCustomerDashboard from "@Front/Components/LayoutTemplates/DefaultCustomerDashboard";

import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import DepositDocumentComponent from "./DepositDocumentComponent";
import Module from "@Front/Config/Module";
import Separator, { ESeperatorColor, ESeperatorDirection } from "@Front/Components/DesignSystem/Separator";
import NotificationBox from "@Front/Components/DesignSystem/NotificationBox";
import ContactBox from "./ContactBox";
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
import { EDocumentNotaryStatus } from "le-coffre-resources/dist/Notary/DocumentNotary";
import DepositOtherDocument from "@Front/Components/DesignSystem/DepositOtherDocument";

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 [folder, setFolder] = useState<OfficeFolderNotary | null>(null);
	const [documentsNotary, setDocumentsNotary] = useState<DocumentNotary[]>([]);
	const [isAddDocumentModalVisible, setIsAddDocumentModalVisible] = useState<boolean>(false);

	const fetchFolderAndCustomer = useCallback(async () => {
		let jwt: ICustomerJwtPayload | undefined;
		if (typeof document !== "undefined") {
			jwt = JwtService.getInstance().decodeCustomerJwt();
		}

		const folder = await Folders.getInstance().getByUid(folderUid as string, {
			q: {
				office: true,
				customers: true,
				notes: {
					include: {
						customer: true,
					},
				},
				stakeholders: {
					include: {
						contact: true,
						office_role: true,
					},
				},
				deed: {
					include: {
						deed_type: true,
					},
				},
			},
		});

		const customer = folder?.customers?.find((customer) => customer.contact?.email === jwt?.email);
		if (!customer) throw new Error("Customer not found");

		setFolder(folder);
		setCustomer(customer);

		return { folder, customer };
	}, [folderUid]);

	const fetchDocuments = useCallback(
		(customerUid: string | undefined) => {
			const query: IGetDocumentsparams = {
				where: { depositor: { uid: customerUid }, folder_uid: folderUid as string },
				include: {
					files: true,
					document_history: true,
					document_type: true,
					depositor: true,
					folder: {
						include: {
							customers: {
								include: {
									contact: true,
								},
							},
						},
					},
				},
			};

			return Documents.getInstance()
				.get(query)
				.then((documents) => setDocuments(documents));
		},
		[folderUid],
	);

	useEffect(() => {
		fetchFolderAndCustomer().then(({ customer }) => fetchDocuments(customer.uid));
	}, [fetchDocuments, fetchFolderAndCustomer]);

	useEffect(() => {
		const customerUid = JwtService.getInstance().decodeCustomerJwt()?.customerId;
		if (!folderUid || !customerUid) return;
		DocumentsNotary.getInstance()
			.get({ where: { folder: { uid: folderUid }, customer: { uid: customerUid } }, include: { files: true } })
			.then((documentsNotary) => setDocumentsNotary(documentsNotary));
	}, [folderUid]);

	const documentsNotaryNotRead = useMemo(
		() => documentsNotary.filter((doc) => doc.document_status === EDocumentNotaryStatus.SENT),
		[documentsNotary],
	);

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

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

	const renderBox = useCallback(() => {
		return (
			<DepositOtherDocument
				folder_uid={folderUid!}
				customer_uid={customer!.uid!}
				open={isAddDocumentModalVisible}
				onClose={onCloseModalAddDocument}
				document={Document.hydrate<Document>({
					document_type: DocumentType.hydrate<DocumentType>({
						name: "Autres documents",
						office: folder!.office!,
					}),
				})}
			/>
		);
	}, [customer, folderUid, isAddDocumentModalVisible, onCloseModalAddDocument]);

	return (
		<DefaultCustomerDashboard>
			<div className={classes["root"]}>
				<div className={classes["top"]}>
					<div className={classes["folder-info-container"]}>
						<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_SECONDARY}>
							Dossier {folder?.folder_number} - {folder?.name}
						</Typography>
						<Typography typo={ETypo.TITLE_H4} color={ETypoColor.TEXT_PRIMARY}>
							Bonjour {customer?.contact?.first_name.concat(" ", customer?.contact?.last_name)}
						</Typography>
						<Tag color={ETagColor.INFO} label={folder?.deed?.deed_type?.name ?? ""} />
						<div className={classes["office-container"]}>
							<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_SECONDARY}>
								Office
							</Typography>

							<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.TEXT_ACCENT}>
								{folder?.office?.name}
							</Typography>
						</div>
					</div>
					<Separator
						className={classes["desktop-separator"]}
						direction={ESeperatorDirection.VERTICAL}
						size={142}
						color={ESeperatorColor.LIGHT}
					/>
					{(documentsNotaryNotRead?.length ?? 0) > 0 && (
						<NotificationBox
							text={`${documentsNotaryNotRead?.length} Nouveaux document(s) envoyé(s) par votre notaire`}
							button={{
								children: "Consulter les documents",
								variant: EButtonVariant.SECONDARY,
								styletype: EButtonstyletype.OUTLINED,
								onClick: () =>
									router.push(
										Module.getInstance()
											.get()
											.modules.pages.ClientDashboard.pages.ReceiveDocuments.props.path.replace(
												"[folderUid]",
												folderUid as string,
											),
									),
							}}
							read={false}
						/>
					)}
					{(documentsNotaryNotRead?.length ?? 0) === 0 && (documentsNotary?.length ?? 0) > 0 && (
						<NotificationBox
							text={`Consultez les documents envoyés par votre notaire`}
							button={{
								children: "Consulter les documents",
								variant: EButtonVariant.SECONDARY,
								styletype: EButtonstyletype.OUTLINED,
								onClick: () =>
									router.push(
										Module.getInstance()
											.get()
											.modules.pages.ClientDashboard.pages.ReceiveDocuments.props.path.replace(
												"[folderUid]",
												folderUid as string,
											),
									),
							}}
							read={true}
						/>
					)}
				</div>

				{customer && folder && <ContactBox customer={customer} folder={folder} />}

				<div className={classes["documents"]}>
					<Typography typo={ETypo.TEXT_LG_BOLD} color={ETypoColor.TABLE_COLUMN_CONTRAST}>
						Documents à envoyer
					</Typography>
					<div className={classes["content"]}>
						{documents?.map((document) => (
							<DepositDocumentComponent
								key={document.uid}
								document={document}
								onChange={() => fetchDocuments(customer?.uid)}
							/>
						))}
					</div>
				</div>
				<Typography typo={ETypo.TITLE_H3}>Documents supplémentaires (facultatif)</Typography>
				<Typography typo={ETypo.TEXT_MD_REGULAR} className={classes["text"]}>
					Vous souhaitez envoyer d'autres documents à votre notaire ?
				</Typography>
				<Button
					variant={EButtonVariant.PRIMARY}
					styletype={EButtonstyletype.OUTLINED}
					className={classes["button"]}
					onClick={onOpenModalAddDocument}>
					Ajouter d'autres documents
				</Button>
				{isAddDocumentModalVisible && renderBox()}
			</div>
		</DefaultCustomerDashboard>
	);
}
