import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
import DocumentReminders from "@Front/Api/LeCoffreApi/Notary/DocumentReminders/DocumentReminders";
import Dropdown from "@Front/Components/DesignSystem/Dropdown";
import { IOption } from "@Front/Components/DesignSystem/Dropdown/DropdownMenu/DropdownOption";
import Table from "@Front/Components/DesignSystem/Table";
import { IHead, IRowProps } from "@Front/Components/DesignSystem/Table/MuiTable";
import Tag, { ETagColor, ETagVariant } from "@Front/Components/DesignSystem/Tag";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import BackArrow from "@Front/Components/Elements/BackArrow";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import Module from "@Front/Config/Module";
import Customer from "le-coffre-resources/dist/Customer";
import { EDocumentStatus } from "le-coffre-resources/dist/Customer/Document";
import { DocumentReminder } from "le-coffre-resources/dist/Notary";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useMemo, useState } from "react";

import classes from "./classes.module.scss";

type IProps = {};

const tradDocumentStatus: Record<EDocumentStatus, string> = {
	[EDocumentStatus.ASKED]: "DEMANDÉ",
	[EDocumentStatus.DEPOSITED]: "À VALIDER",
	[EDocumentStatus.VALIDATED]: "VALIDÉ",
	[EDocumentStatus.REFUSED]: "REFUSÉ",
};

const header: readonly IHead[] = [
	{
		key: "remindedAt",
		title: "Date de relance",
	},
	{
		key: "customer",
		title: "Client",
	},
	{
		key: "document_type",
		title: "Type de document",
	},
	{
		key: "statut",
		title: "Satut",
	},
];

export default function DocumentsReminderHistory(props: IProps) {
	const [reminders, setReminders] = useState<DocumentReminder[] | null>(null);
	const [customers, setCustomers] = useState<Customer[] | null>(null);
	const [customerOption, setCustomerOption] = useState<IOption | null>(null);
	const router = useRouter();
	let { folderUid } = router.query;

	const fetchReminders = useCallback(() => {
		DocumentReminders.getInstance()
			.get({
				...(customerOption && customerOption.id !== "tous" && { where: { document: { depositor: { uid: customerOption.id } } } }),
				include: {
					document: {
						include: {
							depositor: {
								include: {
									contact: true,
								},
							},
							document_type: true,
						},
					},
				},
				orderBy: { reminder_date: "desc" },
			})
			.then((reminders) => setReminders(reminders))
			.catch((e) => console.warn(e));
	}, [customerOption]);

	const fetchCustomers = useCallback(async () => {
		if (!folderUid) return;
		Customers.getInstance()
			.get({
				where: {
					office_folders: {
						some: {
							uid: folderUid as string,
						},
					},
				},
			})
			.then(setCustomers)
			.catch(console.warn);
	}, [folderUid]);

	const customersOptions: IOption[] = useMemo(() => {
		let options = [
			{
				id: "tous",
				label: "Tous",
			},
		];

		customers?.forEach((customer) => {
			options.push({
				id: customer.uid ?? "",
				label: `${customer.contact?.first_name} ${customer.contact?.last_name}`,
			});
		});
		return options;
	}, [customers]);

	useEffect(() => {
		fetchReminders();
		fetchCustomers();
	}, [customerOption, customersOptions, fetchCustomers, fetchReminders]);

	const onSelectionChange = useCallback((option: IOption | null) => {
		setCustomerOption(option ?? null);
	}, []);

	return (
		<DefaultTemplate title={"Historique des relances de documents"} isPadding={false}>
			<div className={classes["root"]}>
				<BackArrow
					text="Retour"
					url={Module.getInstance()
						.get()
						.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string)}
				/>
				<Typography typo={ETypo.TITLE_H1} color={ETypoColor.TEXT_PRIMARY}>
					Historique des relances de documents
				</Typography>
				<Dropdown
					className={classes["customer-filter"]}
					options={customersOptions}
					onSelectionChange={onSelectionChange}
					selectedOption={customerOption ?? customersOptions?.[0]}
					label="Client"
				/>
				<Table className={classes["table"]} header={header} rows={buildRows(reminders)} />
			</div>
		</DefaultTemplate>
	);
}

function buildRows(reminders: DocumentReminder[] | null): IRowProps[] {
	if (!reminders) return [];
	return reminders.map((reminder) => ({
		key: reminder.uid ?? "",
		remindedAt: { sx: { width: 220 }, content: formatDateWithHours(reminder.reminder_date) },
		customer: {
			sx: { width: 220 },
			content: `${reminder.document?.depositor?.contact?.first_name} ${reminder.document?.depositor?.contact?.last_name}`,
		},
		document_type: reminder.document?.document_type?.name,
		statut: { sx: { width: 220 }, content: getTag(reminder.document?.document_status as EDocumentStatus) },
	}));
}

function getTag(status: EDocumentStatus) {
	switch (status) {
		case EDocumentStatus.ASKED:
			return <Tag label={tradDocumentStatus[status]} color={ETagColor.INFO} variant={ETagVariant.SEMI_BOLD} />;
		case EDocumentStatus.DEPOSITED:
			return <Tag label={tradDocumentStatus[status]} color={ETagColor.WARNING} variant={ETagVariant.SEMI_BOLD} />;
		case EDocumentStatus.VALIDATED:
			return <Tag label={tradDocumentStatus[status]} color={ETagColor.SUCCESS} variant={ETagVariant.SEMI_BOLD} />;
		case EDocumentStatus.REFUSED:
			return <Tag label={tradDocumentStatus[status]} color={ETagColor.ERROR} variant={ETagVariant.SEMI_BOLD} />;
		default:
			return <Tag label={tradDocumentStatus[status]} color={ETagColor.INFO} variant={ETagVariant.SEMI_BOLD} />;
	}
}

function formatDateWithHours(date: Date | null) {
	if (!date) return "-";
	return new Date(date).toLocaleDateString("fr-FR", {
		year: "numeric",
		month: "2-digit",
		day: "2-digit",
		hour: "2-digit",
		minute: "2-digit",
	});
}
