import Folders from "@Front/Api/LeCoffreApi/Notary/Folders/Folders";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import Form from "@Front/Components/DesignSystem/Form";
import Select, { IOption } from "@Front/Components/DesignSystem/Form/SelectField";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
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 { Deed, OfficeFolder } from "le-coffre-resources/dist/Notary";
import Link from "next/link";
import { NextRouter, useRouter } from "next/router";

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

type IProps = {};

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

type IState = {
	selectedFolder: OfficeFolder | null;
};
class UpdateFolderMetadataClass extends BasePage<IPropsClass, IState> {
	constructor(props: IPropsClass) {
		super(props);
		this.state = {
			selectedFolder: null,
		};
		this.onSelectedFolder = this.onSelectedFolder.bind(this);
		this.getFolder = this.getFolder.bind(this);
		this.onFormSubmit = this.onFormSubmit.bind(this);
	}
	public override render(): JSX.Element {
		const backwardPath = Module.getInstance()
			.get()
			.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", this.state.selectedFolder?.uid!);
		const deedOption = {
			label: this.state.selectedFolder?.deed?.deed_type?.name,
			value: this.state.selectedFolder?.deed?.deed_type?.uid,
		} as IOption;
		const openingDate = new Date(this.state.selectedFolder?.created_at ?? "");
		return (
			<DefaultNotaryDashboard title={"Ajouter client(s)"} onSelectedFolder={this.onSelectedFolder}>
				<div className={classes["root"]}>
					<div className={classes["back-arrow"]}>
						<BackArrow url={backwardPath} />
					</div>
					<Typography typo={ITypo.H1Bis}>Modifier les informations du dossier</Typography>

					<Form className={classes["form"]} onSubmit={this.onFormSubmit}>
						<div className={classes["content"]}>
							<TextField name="name" placeholder="Intitulé du dossier" defaultValue={this.state.selectedFolder?.name} />
							<TextField
								name="folder_number"
								placeholder="Numéro de dossier"
								defaultValue={this.state.selectedFolder?.folder_number}
							/>
							<Select name="deed" options={[]} placeholder={"Type d'acte"} selectedOption={deedOption} disabled />
							<TextField placeholder="Ouverture du dossier" defaultValue={openingDate.toLocaleDateString("fr-FR")} disabled />
						</div>

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

	public override async componentDidMount() {
		const folder = await this.getFolder();
		this.setState({
			selectedFolder: folder,
		});
	}

	private async onFormSubmit(
		e: React.FormEvent<HTMLFormElement> | null,
		values: {
			[key: string]: string;
		},
	) {
		try {
			const newValues = OfficeFolder.hydrate<OfficeFolder>({
				...values,
				deed: Deed.hydrate<Deed>({
					uid: values["deed"],
				}),
			});

			await Folders.getInstance().put(this.props.folderUid, newValues);
			const url = Module.getInstance()
				.get()
				.modules.pages.Folder.pages.FolderInformation.props.path.replace("[folderUid]", this.props.folderUid);
			this.props.router.push(url);
		} catch (e) {
			console.error(e);
		}
	}

	private async getFolder(): Promise<OfficeFolder> {
		const query = {
			q: {
				deed: { include: { deed_type: true } },
				office: true,
				customers: { include: { contact: true } },
			},
		};
		const folder = await Folders.getInstance().getByUid(this.props.folderUid, query);
		return folder;
	}

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

export default function UpdateFolderMetadata(props: IProps) {
	const router = useRouter();
	let { folderUid } = router.query;
	folderUid = folderUid as string;
	return <UpdateFolderMetadataClass folderUid={folderUid} router={router} />;
}
