import backgroundImage from "@Assets/images/background_refonte.svg";
import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form, { IBaseField } from "@Front/Components/DesignSystem/Form";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Modal from "@Front/Components/DesignSystem/Modal";
import Typography, { ETypo } from "@Front/Components/DesignSystem/Typography";
import BackArrow from "@Front/Components/Elements/BackArrow";
import DefaultDoubleSidePage from "@Front/Components/LayoutTemplates/DefaultDoubleSidePage";
import Module from "@Front/Config/Module";
import useOpenable from "@Front/Hooks/useOpenable";
import { ValidationError } from "class-validator";
import { Address } from "le-coffre-resources/dist/Customer";
import { Contact, Customer } from "le-coffre-resources/dist/Notary";
import Link from "next/link";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";

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

export default function UpdateClient() {
	const router = useRouter();
	const { folderUid, customerUid } = router.query;

	const [doesInputHasChanged, setDoesInputHasChanged] = useState<boolean>(false);
	const [customer, setCustomer] = useState<Customer | null>(null);
	const [validationError, setValidationError] = useState<ValidationError[]>([]);

	const { isOpen, open, close } = useOpenable();

	const backwardPath = Module.getInstance()
		.get()
		.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", folderUid as string);

	useEffect(() => {
		const fetchCustomer = async () => {
			try {
				const customerData = await Customers.getInstance().getByUid(customerUid as string, {
					contact: {
						include: {
							address: true,
						},
					},
				});
				if (customerData) {
					setCustomer(customerData);
				}
			} catch (error) {
				console.error("Failed to fetch customer", error);
			}
		};
		fetchCustomer();
	}, [customerUid]);

	const onFormSubmit = useCallback(
		async (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => {
			if (!values["cell_phone_number"]) return;

			let phoneNumber = values["cell_phone_number"].replace(/\s/g, "").replace(/\./g, "");
			if (phoneNumber.length === 10 && phoneNumber.startsWith("0")) {
				phoneNumber = "+33" + phoneNumber.substring(1);
			}
			const contact = Contact.hydrate<Contact>({
				first_name: values["first_name"],
				last_name: values["last_name"],
				email: values["email"],
				cell_phone_number: phoneNumber,
				birthdate: values["birthdate"] === "" ? null : new Date(values["birthdate"]!),
				civility: "-",
				address: values["address"] ? Address.hydrate<Address>({ address: values["address"], city: "-", zip_code: 0 }) : undefined,
			});

			try {
				await contact.validateOrReject?.({ groups: ["createCustomer"], forbidUnknownValues: false });
				await Customers.getInstance().put(customerUid as string, { contact });
				router.push(backwardPath);
			} catch (validationErrors) {
				if (Array.isArray(validationErrors)) {
					setValidationError(validationErrors as ValidationError[]);
				}
			}
		},
		[backwardPath, customerUid, router],
	);

	const leavePage = useCallback(() => {
		router.push(backwardPath);
	}, [backwardPath, router]);

	const onFieldChange = useCallback((name: string, field: IBaseField) => {
		if (field.props.value !== field.props.defaultValue) {
			setDoesInputHasChanged(true);
		} else {
			setDoesInputHasChanged(false);
		}
	}, []);

	return (
		<DefaultDoubleSidePage title={"Ajouter client(s)"} image={backgroundImage}>
			<div className={classes["root"]}>
				<div className={classes["back-arrow"]}>
					<BackArrow url={backwardPath} />
				</div>
				<Typography typo={ETypo.TITLE_H1}>Modifier les informations du client</Typography>
				<Form className={classes["form"]} onSubmit={onFormSubmit} onFieldChange={onFieldChange}>
					<TextField
						name="first_name"
						placeholder="Prénom"
						label="Prénom"
						defaultValue={customer?.contact?.first_name}
						validationError={validationError.find((error) => error.property === "first_name")}
					/>
					<TextField
						name="last_name"
						placeholder="Nom"
						label="Nom"
						defaultValue={customer?.contact?.last_name}
						validationError={validationError.find((error) => error.property === "last_name")}
					/>
					<TextField
						name="email"
						placeholder="E-mail"
						label="E-mail"
						defaultValue={customer?.contact?.email}
						validationError={validationError.find((error) => error.property === "email")}
					/>
					<TextField
						name="cell_phone_number"
						placeholder="Numéro de téléphone"
						label="Numéro de téléphone"
						defaultValue={customer?.contact?.cell_phone_number ?? ""}
						validationError={validationError.find((error) => error.property === "cell_phone_number")}
					/>
					<TextField
						name="birthdate"
						placeholder="Date de naissance"
						label="Date de naissance (facultatif)"
						required={false}
						defaultValue={customer?.contact?.birthdate?.toString() ?? ""}
						validationError={validationError.find((error) => error.property === "birthdate")}
					/>
					<TextField
						name="address"
						placeholder="Adresse"
						label="Adresse (facultatif)"
						required={false}
						defaultValue={customer?.contact?.address?.address ?? ""}
					/>
					<div className={classes["button-container"]}>
						{!doesInputHasChanged ? (
							<Link href={backwardPath} className={classes["cancel-button"]}>
								<Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED}>
									Annuler
								</Button>
							</Link>
						) : (
							<Button
								variant={EButtonVariant.PRIMARY}
								styletype={EButtonstyletype.OUTLINED}
								onClick={open}
								className={classes["cancel-button"]}>
								Annuler
							</Button>
						)}
						<Button type="submit">Enregistrer les modifications</Button>
					</div>
				</Form>
				<Modal
					title={"Quitter sans enregistrer ?"}
					isOpen={isOpen}
					onClose={close}
					firstButton={{ children: "Annuler", onClick: close }}
					secondButton={{ children: "Oui, quitter sans enregistrer", onClick: leavePage }}>
					Si vous quittez, toutes les modifications que vous avez effectuées ne seront pas enregistrées.
				</Modal>
			</div>
		</DefaultDoubleSidePage>
	);
}
