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

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

import Customer, { Document } from "le-coffre-resources/dist/Customer";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { 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 OfficeRib from "@Front/Api/LeCoffreApi/Customer/OfficeRib/OfficeRib";

import Tag, { ETagColor } from "@Front/Components/DesignSystem/Tag";
import DefaultCustomerDashboard from "@Front/Components/LayoutTemplates/DefaultCustomerDashboard";
import ContactBox from "@Front/Components/Elements/ContactBox";
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { ArrowDownTrayIcon } from "@heroicons/react/24/outline";
import DepositDocumentComponent from "./DepositDocumentComponent";

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 [ribUrl, setRibUrl] = useState<string | null>(null);

	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,
					},
				},
			},
		});

		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]);

	const notaryContact = useMemo(
		() =>
			folder?.stakeholders!.find((stakeholder) => stakeholder.office_role?.name === "Collaborateur")?.contact ??
			folder?.stakeholders![0]!.contact,
		[folder],
	);

	const note = useMemo(
		() =>
			folder?.notes?.find((note) => note.customer?.uid === customer?.uid) ?? {
				content: "Aucune note",
				created_at: new Date(),
				updated_at: new Date(),
			},
		[customer?.uid, folder?.notes],
	);

	useEffect(() => {
		if (!folder?.office?.uid) return;
		OfficeRib.getInstance()
			.getRibStream(folder.office.uid)
			.then((blob) => setRibUrl(URL.createObjectURL(blob)));
	}, [folder]);

	const downloadRib = useCallback(async () => {
		if (!ribUrl) return;
		const a = document.createElement("a");
		a.style.display = "none";
		a.href = ribUrl;
		a.download = "";
		document.body.appendChild(a);
		a.click();
	}, [ribUrl]);

	return (
		<DefaultCustomerDashboard>
			<div className={classes["root"]}>
				<div className={classes["title-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={"todo"} />
					<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>
				<div className={classes["content"]}>
					<div className={classes["notary"]}>
						<Typography typo={ETypo.TEXT_LG_BOLD} color={ETypoColor.TABLE_COLUMN_CONTRAST}>
							Votre Notaire
						</Typography>
						{notaryContact && <ContactBox contact={notaryContact} note={note} />}
						{ribUrl && (
							<Button
								fullwidth
								onClick={downloadRib}
								variant={EButtonVariant.PRIMARY}
								size={EButtonSize.LG}
								styletype={EButtonstyletype.CONTAINED}
								rightIcon={<ArrowDownTrayIcon />}>
								Télécharger le RIB
							</Button>
						)}
						<Button fullwidth variant={EButtonVariant.PRIMARY} size={EButtonSize.LG} styletype={EButtonstyletype.OUTLINED}>
							Voir les documents reçus
						</Button>
					</div>
					<div className={classes["documents"]}>
						<Typography typo={ETypo.TEXT_LG_BOLD} color={ETypoColor.TABLE_COLUMN_CONTRAST}>
							Documents à envoyer
						</Typography>
						{documents?.map((document) => (
							<DepositDocumentComponent
								key={document.uid}
								document={document}
								onChange={() => fetchDocuments(customer?.uid)}
							/>
						))}
					</div>
				</div>
			</div>
		</DefaultCustomerDashboard>
	);
}
