import Tabs from "@Front/Components/Elements/Tabs";
import Customer from "le-coffre-resources/dist/Customer";
import { OfficeFolder } from "le-coffre-resources/dist/Notary";

import { useCallback, useMemo, useState } from "react";

import { AnchorStatus } from "..";
import classes from "./classes.module.scss";
import ClientBox from "./ClientBox";
import Button, { EButtonSize, EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { DocumentIcon, UserPlusIcon } from "@heroicons/react/24/outline";
import Module from "@Front/Config/Module";
import Link from "next/link";
import NoDocument from "./NoDocument";
import DocumentTables from "./DocumentTables";
import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";

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

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

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

	const customers: ICustomer[] = useMemo(
		() =>
			folder?.customers?.map((customer) => ({
				id: customer.uid ?? "",
				...customer,
			})) ?? [],
		[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,
				}))
				// put every tabs that has warning first
				.sort((a, b) => (a.hasWarning ? -1 : 1)),
		[customers],
	);

	const doesCustomerHaveDocument = useMemo(() => customer.documents && customer.documents.length > 0, [customer]);

	const handleClientDelete = useCallback(
		(customerUid: string) => {
			if (!folder.uid) return;
			Folders.getInstance().put(
				folder.uid,
				OfficeFolder.hydrate<OfficeFolder>({
					...folder,
					customers: folder.customers?.filter((customer) => customer.uid !== customerUid),
				}),
			);
			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]", folder.uid ?? "")}>
						<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"]}>
					<ClientBox
						customer={customer}
						anchorStatus={anchorStatus}
						folderUid={folder.uid}
						onDelete={handleClientDelete}
						customerNote={folder.notes!.find((value) => value.customer?.uid === customer.uid) ?? null}
					/>
					{anchorStatus === AnchorStatus.NOT_ANCHORED && (
						<Link
							href={Module.getInstance()
								.get()
								.modules.pages.Folder.pages.AskDocument.props.path.replace("[folderUid]", folder.uid ?? "")
								.replace("[customerUid]", customer.uid ?? "")}>
							<Button rightIcon={<DocumentIcon />} variant={EButtonVariant.PRIMARY} fullwidth>
								Demander un document
							</Button>
						</Link>
					)}
				</div>
				{doesCustomerHaveDocument ? (
					<DocumentTables documents={customer.documents ?? []} folderUid={folder?.uid ?? ""} />
				) : (
					<NoDocument />
				)}
			</div>
		</section>
	);
}
