import Button, { EButtonstyletype, EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form from "@Front/Components/DesignSystem/Form";
import TextAreaField from "@Front/Components/DesignSystem/Form/TextareaField";
import Typography, { ETypo } 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 { OfficeFolder } from "le-coffre-resources/dist/Customer";
import Link from "next/link";
import { NextRouter, useRouter } from "next/router";

import BasePage from "../../Base";
import classes from "./classes.module.scss";
import Customer from "le-coffre-resources/dist/Customer";
import Note from "le-coffre-resources/dist/Customer/Note";

import FolderService from "src/common/Api/LeCoffreApi/sdk/FolderService";
import CustomerService from "src/common/Api/LeCoffreApi/sdk/CustomerService";
import NoteService from "src/common/Api/LeCoffreApi/sdk/NoteService";
import LoaderService from "src/common/Api/LeCoffreApi/sdk/Loader/LoaderService";

type IProps = {};

type IPropsClass = IProps & {
	folderUid: string;
	customerUid: string;
	router: NextRouter;
};

type IState = {
	folder: OfficeFolder | null;
	customer: Customer | null;
	note: Note | null;
};
class CreateCustomerNoteClass extends BasePage<IPropsClass, IState> {
	private backwardPath = Module.getInstance()
		.get()
		.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", this.props.folderUid!);
	constructor(props: IPropsClass) {
		super(props);
		this.state = {
			folder: null,
			customer: null,
			note: null,
		};
		this.onFormSubmit = this.onFormSubmit.bind(this);
	}
	public override render(): JSX.Element {
		return (
			<DefaultNotaryDashboard title={"Modifier la note client"}>
				<div className={classes["root"]}>
					<div className={classes["back-arrow"]}>
						<BackArrow url={this.backwardPath} />
					</div>
					<Typography typo={ETypo.TITLE_H1}>Modifier la note du client</Typography>

					<Form className={classes["form"]} onSubmit={this.onFormSubmit}>
						<div className={classes["content"]}>
							<TextAreaField
								name="content"
								placeholder="Note à l'attention du client"
								defaultValue={this.state.note?.content ?? ""}
							/>
						</div>

						<div className={classes["button-container"]}>
							<Link href={this.backwardPath} className={classes["cancel-button"]}>
								<Button variant={EButtonVariant.PRIMARY} styletype={EButtonstyletype.OUTLINED}>
									Annuler
								</Button>
							</Link>
							<Button type="submit">Enregistrer</Button>
						</div>
					</Form>
				</div>
			</DefaultNotaryDashboard>
		);
	}

	public override async componentDidMount() {
		/* TODO: review
		// const note = await Notes.getInstance().getByUid(this.props.noteUid, query);
		const folder = await Folders.getInstance().getByUid(this.props.folderUid, { note: true });
		const customer = await Customers.getInstance().getByUid(this.props.customerUid);
		*/

		LoaderService.getInstance().show();

		const folder: any = await FolderService.getFolderByUid(this.props.folderUid).then((process: any) => {
			if (process) {
				const folder: any = process.processData;
				return folder;
			}
		});

		const customer: any = await CustomerService.getCustomerByUid(this.props.customerUid).then((process: any) => {
			if (process) {
				const customer: any = process.processData;
				return customer;
			}
		});

		LoaderService.getInstance().hide();

		//get the note of the folder that has customer_uid = this.props.customer.uid
		// const folderNote = folder.notes?.find((note) => note.customer?.uid === this.props.customerUid);
		// this.setState({ note, folder: note.office_folder || null, customer: note.customer || null });
		this.setState({ note: null, folder: folder, customer: customer });
	}

	private async onFormSubmit(e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) {
		try {
			if (!this.state.folder || !this.state.customer) {
				throw new Error("Folder or customer not found");
			}

			// TODO: review
			const noteData: any = {
				content: values["content"],
				folder: {
					uid: this.state.folder.uid
				},
				customer: {
					uid: this.state.customer.uid
				}
			};
			const validatorId: string = '884cb36a346a79af8697559f16940141f068bdf1656f88fa0df0e9ecd7311fb8:0';

			LoaderService.getInstance().show();
			NoteService.createNote(noteData, validatorId).then(() => {
				this.props.router.push(this.backwardPath);
			});
		} catch (error) {
			console.error(error);
		}
	}
}

export default function UpdateCustomerNote(props: IProps) {
	const router = useRouter();
	let { folderUid, customerUid } = router.query;

	folderUid = folderUid as string;
	customerUid = customerUid as string;

	return <CreateCustomerNoteClass folderUid={folderUid} customerUid={customerUid} router={router} />;
}
