import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Tabs from "@Front/Components/Elements/Tabs";
import Module from "@Front/Config/Module";
import { DocumentIcon, UserPlusIcon } from "@heroicons/react/24/outline";
import Customer from "le-coffre-resources/dist/Customer";
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
import Link from "next/link";
import { useCallback, useMemo, useState } from "react";

import { AnchorStatus } from "..";
import classes from "./classes.module.scss";
import ClientBox from "./ClientBox";
import DocumentTables from "./DocumentTables";
import EmailReminder from "./EmailReminder";

import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";
import MessageBus from "src/sdk/MessageBus";
import { idAsUrl } from "@Front/Utils/ProcessIdUtils";

type IProps = {
	folder: any;
	anchorStatus: AnchorStatus;
};

export type ICustomer = Customer & { id: string };

export default function ClientView(props: IProps) {
	const { folder, anchorStatus } = props;

	const customers: ICustomer[] = useMemo(
		() => {
			return folder?.FolderData?.customers
				?.map((customer: any) => ({
					id: customer.uid ?? '',
					...customer,
				}))
				.sort((a: any, b: any) => {
					return a.documents &&
						a.documents.filter((document: any) => document.document_status === EDocumentStatus.DEPOSITED).length > 0
						? -1
						: 1;
				}) ?? []
		},
		[folder],
	);

	const [customer, setCustomer] = useState<(typeof customers)[number]>(customers[0]!);

	const tabs = useMemo(
		() =>
			customers.map((customer) => ({
				label: `${customer.contact?.first_name} ${customer.contact?.last_name}`,
				key: customer.uid,
				value: customer,
				hasWarning:
					customer.documents &&
					customer.documents.filter((document) => document.document_status === EDocumentStatus.DEPOSITED).length > 0,
			})),
		[customers],
	);

	const handleClientDelete = useCallback(
		(customerUid: string) => {
			if (!folder.processId) return;
			LoaderService.getInstance().show();
			MessageBus.getInstance().getProcessData(folder.processId).then((process: { [key: string]: any }) => {
				if (process) {
					const processId = folder.processId;
					const folderData = process[processId];

					// FilterBy customerUid
					const customers = folderData.customers.filter((uid: string) => uid !== customerUid);

					FolderService.updateFolder(processId, { customers: customers }).then(() => {
						LoaderService.getInstance().hide();
						window.location.reload();
					});
				}
			});
		},
		[folder],
	);

	return (
		<section className={classes["root"]}>
			<div className={classes["tab-container"]}>
				<div className={classes["tabs"]}>{tabs && <Tabs<ICustomer> tabs={tabs} onSelect={setCustomer} />}</div>

				{anchorStatus === AnchorStatus.NOT_ANCHORED && (
					<Link
						href={Module.getInstance()
							.get()
							.modules.pages.Folder.pages.AddClient.props.path.replace("[folderUid]", idAsUrl(folder.processId) ?? "")}>
						<Button
							size={EButtonSize.MD}
							rightIcon={<UserPlusIcon />}
							variant={EButtonVariant.PRIMARY}
							styletype={EButtonstyletype.TEXT}>
							Ajouter un client
						</Button>
					</Link>
				)}
			</div>
			<div className={classes["content"]}>
				<div className={classes["client-box-container"]}>
					<ClientBox
						customer={customer}
						anchorStatus={anchorStatus}
						folderUid={folder.processId}
						onDelete={handleClientDelete}
						customerNote={folder.FolderData?.notes?.find((value: any) => value.customer?.uid === customer.uid) ?? null}
					/>
					<div className={classes["button-container"]}>
						{anchorStatus === AnchorStatus.NOT_ANCHORED && (
							<Link
								href={Module.getInstance()
									.get()
									.modules.pages.Folder.pages.AskDocument.props.path.replace("[folderUid]", folder.processId ?? "")
									.replace("[customerUid]", customer?.uid ?? "")}>
								<Button rightIcon={<DocumentIcon />} variant={EButtonVariant.PRIMARY} fullwidth>
									Demander un document
								</Button>
							</Link>
						)}
						<EmailReminder customer={customer} isAnchored={anchorStatus !== AnchorStatus.NOT_ANCHORED} />
					</div>
				</div>

				{customer?.uid && folder.processId && <DocumentTables customerUid={customer.uid} folderUid={folder.processId} />}
			</div>
		</section>
	);
}
