import Customers from "@Front/Api/LeCoffreApi/Notary/Customers/Customers";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form from "@Front/Components/DesignSystem/Form";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Confirm from "@Front/Components/DesignSystem/Modal/Confirm";
import Typography, { ITypo } from "@Front/Components/DesignSystem/Typography";
import BackArrow from "@Front/Components/Elements/BackArrow";
import DefaultNotaryDashboard from "@Front/Components/LayoutTemplates/DefaultNotaryDashboard";
import Module from "@Front/Config/Module";
import { Contact, Customer, OfficeFolder } from "le-coffre-resources/dist/Notary";
import Link from "next/link";
import { NextRouter, useRouter } from "next/router";
import { ChangeEvent } from "react";

import BasePage from "../../Base";
import classes from "./classes.module.scss";
import { Address } from "le-coffre-resources/dist/Customer";
import { ValidationError } from "class-validator";

type IProps = {};

type IPropsClass = IProps & {
	selectedFolderUid: string;
	router: NextRouter;
	customerUid: string;
};
type IState = {
	selectedFolder: OfficeFolder | null;
	inputNameValue: string;
	inputFirstNameValue: string;
	inputEmailValue: string;
	inputPhoneNumberValue: string;
	isOpenLeavingModal: boolean;
	doesInputHaveValues: boolean;
	inputBirthdate: Date | null;
	inputAddress: string;
	folder: OfficeFolder | null;
	customer: Customer | null;
	validationError: ValidationError[];
};
class UpdateClientClass extends BasePage<IPropsClass, IState> {
	constructor(props: IPropsClass) {
		super(props);
		this.state = {
			selectedFolder: null,
			inputNameValue: "",
			inputFirstNameValue: "",
			inputEmailValue: "",
			inputPhoneNumberValue: "",
			isOpenLeavingModal: false,
			doesInputHaveValues: false,
			inputBirthdate: null,
			inputAddress: "",
			folder: null,
			customer: null,
			validationError: [],
		};
		this.onSelectedFolder = this.onSelectedFolder.bind(this);
		this.onChangeNameInput = this.onChangeNameInput.bind(this);
		this.onChangeFirstNameInput = this.onChangeFirstNameInput.bind(this);
		this.onChangeEmailInput = this.onChangeEmailInput.bind(this);
		this.onChangePhoneNumberInput = this.onChangePhoneNumberInput.bind(this);
		this.openLeavingModal = this.openLeavingModal.bind(this);
		this.closeLeavingModal = this.closeLeavingModal.bind(this);
		this.leavePage = this.leavePage.bind(this);
		this.onChangeBirthDateInput = this.onChangeBirthDateInput.bind(this);
		this.onChangeAddressInput = this.onChangeAddressInput.bind(this);
		this.onFormSubmit = this.onFormSubmit.bind(this);
	}

	private backwardPath = Module.getInstance()
		.get()
		.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", this.props.selectedFolderUid);

	public override render(): JSX.Element {
		return (
			<DefaultNotaryDashboard title={"Ajouter client(s)"} onSelectedFolder={this.onSelectedFolder}>
				<div className={classes["root"]}>
					<div className={classes["back-arrow"]}>
						<BackArrow url={this.backwardPath} />
					</div>
					<Typography typo={ITypo.H1Bis}>Modifier les informations du client</Typography>
					<Form className={classes["form"]} onSubmit={this.onFormSubmit}>
						<div className={classes["content"]}>
							<TextField
								name="first_name"
								placeholder="Nom"
								onChange={this.onChangeNameInput}
								defaultValue={this.state.customer?.contact?.first_name}
								validationError={this.state.validationError.find((error) => error.property === "first_name")}
							/>
							<TextField
								name="last_name"
								placeholder="Prénom"
								onChange={this.onChangeFirstNameInput}
								defaultValue={this.state.customer?.contact?.last_name}
								validationError={this.state.validationError.find((error) => error.property === "last_name")}
							/>
							<TextField
								name="email"
								placeholder="E-mail"
								onChange={this.onChangeEmailInput}
								defaultValue={this.state.customer?.contact?.email}
								validationError={this.state.validationError.find((error) => error.property === "email")}
							/>
							<TextField
								name="cell_phone_number"
								placeholder="Numéro de téléphone"
								onChange={this.onChangePhoneNumberInput}
								defaultValue={this.state.customer?.contact?.cell_phone_number ?? ""}
								validationError={this.state.validationError.find((error) => error.property === "cell_phone_number")}
							/>
							<TextField
								name="birthdate"
								placeholder="Date de naissance"
								required={false}
								onChange={this.onChangeBirthDateInput}
								defaultValue={this.state.customer?.contact?.birthdate?.toString() ?? ""}
								validationError={this.state.validationError.find((error) => error.property === "birthdate")}
							/>
							<TextField
								name="address"
								placeholder="Adresse"
								required={false}
								onChange={this.onChangeAddressInput}
								defaultValue={this.state.customer?.contact?.address?.address ?? ""}
							/>
						</div>

						<div className={classes["button-container"]}>
							{!this.doesInputsHaveValues() ? (
								<Link href={this.backwardPath} className={classes["cancel-button"]}>
									<Button variant={EButtonVariant.GHOST}>Annuler</Button>
								</Link>
							) : (
								<Button variant={EButtonVariant.GHOST} onClick={this.openLeavingModal} className={classes["cancel-button"]}>
									Annuler
								</Button>
							)}
							<Button type="submit">Enregistrer</Button>
						</div>
					</Form>
					<Confirm
						isOpen={this.state.isOpenLeavingModal}
						onClose={this.closeLeavingModal}
						closeBtn
						header={"Êtes-vous sur de vouloir quitter sans enregistrer ?"}
						cancelText={"Annuler"}
						confirmText={"Quitter"}
						onAccept={this.leavePage}>
						Si vous quittez, toutes les modifications que vous avez effectuées ne seront pas enregistrées.{" "}
					</Confirm>
				</div>
			</DefaultNotaryDashboard>
		);
	}

	public override async componentDidMount() {
		const customer = await Customers.getInstance().getByUid(this.props.customerUid, {
			contact: {
				include: {
					address: true,
				},
			},
		});
		if (customer) {
			this.setState({
				customer,
			});
		}
	}

	private async onFormSubmit(
		e: React.FormEvent<HTMLFormElement> | null,
		values: {
			[key: string]: string;
		},
	) {
		if (!values["cell_phone_number"]) return;
		// remove every space from the phone number
		values["cell_phone_number"] = values["cell_phone_number"].replace(/\s/g, "");
		values["cell_phone_number"] = values["cell_phone_number"].replace(/\./g, "");
		if (values["cell_phone_number"] && values["cell_phone_number"].length === 10) {
			// get the first digit of the phone number
			const firstDigit = values["cell_phone_number"].charAt(0);
			// if the first digit is a 0 replace it by +33
			if (firstDigit === "0") {
				values["cell_phone_number"] = "+33" + values["cell_phone_number"].substring(1);
			}
		}
		const contact = Contact.hydrate<Contact>({
			first_name: values["first_name"],
			last_name: values["last_name"],
			email: values["email"],
			cell_phone_number: values["cell_phone_number"],
			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 });
		} catch (validationErrors) {
			this.setState({
				validationError: validationErrors as ValidationError[],
			});
			return;
		}

		try {
			await Customers.getInstance().put(this.props.customerUid, { contact });
			this.props.router.push(this.backwardPath);
		} catch (backError) {
			if (!Array.isArray(backError)) return;
			this.setState({
				validationError: backError as ValidationError[],
			});
			return;
		}
	}

	private leavePage() {
		this.props.router.push(this.backwardPath);
	}

	private openLeavingModal(): void {
		this.setState({ isOpenLeavingModal: true });
	}

	private closeLeavingModal(): void {
		this.setState({ isOpenLeavingModal: false });
	}

	private onChangeBirthDateInput(event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
		this.setState({ inputBirthdate: new Date(event.target.value) });
	}

	private onChangeAddressInput(event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
		this.setState({ inputAddress: event.target.value });
	}

	private onChangeNameInput(event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
		this.setState({ inputNameValue: event.target.value });
	}

	private onChangeFirstNameInput(event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
		this.setState({ inputFirstNameValue: event.target.value });
	}
	private onChangeEmailInput(event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
		this.setState({ inputEmailValue: event.target.value });
	}
	private onChangePhoneNumberInput(event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) {
		this.setState({ inputPhoneNumberValue: event.target.value });
	}

	private onSelectedFolder(folder: OfficeFolder): void {
		this.setState({ selectedFolder: folder });
	}

	private doesInputsHaveValues(): boolean {
		const doesInputsHaveValues: boolean =
			this.state.inputNameValue !== "" ||
			this.state.inputFirstNameValue !== "" ||
			this.state.inputEmailValue !== "" ||
			this.state.inputPhoneNumberValue !== "";
		return doesInputsHaveValues;
	}
}

export default function UpdateClient(props: IProps) {
	const router = useRouter();
	let { folderUid, customerUid } = router.query;
	folderUid = folderUid as string;
	customerUid = customerUid as string;
	return <UpdateClientClass {...props} router={router} selectedFolderUid={folderUid} customerUid={customerUid} />;
}
