import LeftArrowIcon from "@Assets/Icons/left-arrow.svg";
import RightArrowIcon from "@Assets/Icons/right-arrow.svg";
import Button from "@Front/Components/DesignSystem/Button";
import FilePreview from "@Front/Components/DesignSystem/FilePreview";
import Typography, { ETypo, ETypoColor } from "@Front/Components/DesignSystem/Typography";
import { DocumentNotary, File } from "le-coffre-resources/dist/Notary";
import Image from "next/image";
import { NextRouter, useRouter } from "next/router";
import React from "react";

import BasePage from "../../Base";
import classes from "./classes.module.scss";
import DocumentsNotary from "@Front/Api/LeCoffreApi/Customer/DocumentsNotary/DocumentsNotary";
import DefaultTemplate from "@Front/Components/LayoutTemplates/DefaultTemplate";
import FilesNotary from "@Front/Api/LeCoffreApi/Customer/FilesNotary/Files";

type IProps = {};
type IPropsClass = {
	documentUid: string;
	router: NextRouter;
};

type IState = {
	isRefuseModalVisible: boolean;
	isValidateModalVisible: boolean;
	refuseText: string;
	selectedFileIndex: number;
	selectedFile: File | null;
	documentNotary: DocumentNotary | null;
	fileBlob: Blob | null;
	isLoading: boolean;
};

class ViewDocumentsNotaryClass extends BasePage<IPropsClass, IState> {
	public constructor(props: IPropsClass) {
		super(props);

		this.state = {
			isValidateModalVisible: false,
			isRefuseModalVisible: false,
			refuseText: "",
			selectedFileIndex: 0,
			selectedFile: null,
			documentNotary: null,
			fileBlob: null,
			isLoading: true,
		};

		this.goToNext = this.goToNext.bind(this);
		this.goToPrevious = this.goToPrevious.bind(this);
		this.hasPrevious = this.hasPrevious.bind(this);
		this.hasNext = this.hasNext.bind(this);
		this.downloadFile = this.downloadFile.bind(this);
	}

	public override render(): JSX.Element | null {
		return (
			<DefaultTemplate title={"Visualiser le document"} hasBackArrow>
				{this.state.documentNotary && this.state.documentNotary.files && this.state.selectedFile && !this.state.isLoading && (
					<div className={classes["root"]}>
						<Typography typo={ETypo.TITLE_H5} color={ETypoColor.COLOR_GENERIC_BLACK} className={classes["subtitle"]}>
							{this.state.documentNotary.name}
						</Typography>
						<div className={classes["document-container"]}>
							{this.state.documentNotary.files.length > 1 && (
								<div
									className={classes["arrow-container"]}
									onClick={this.goToPrevious}
									data-disabled={(!this.hasPrevious()).toString()}>
									<Image src={LeftArrowIcon} alt="left arrow" />
								</div>
							)}
							<div className={classes["file-container"]}>
								{this.state.selectedFile.mimetype === "application/pdf" ||
								this.state.selectedFile.mimetype === "image/jpeg" ||
								this.state.selectedFile.mimetype === "image/png" ||
								this.state.selectedFile.mimetype === "image/jpg" ? (
									<FilePreview
										href={this.state.fileBlob ? URL.createObjectURL(this.state.fileBlob) : ""}
										fileName={this.state.selectedFile.file_name}
										key={this.state.selectedFile.uid}
									/>
								) : (
									<div className={classes["unsupported-format"]}>
										<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_GENERIC_BLACK}>
											L'affichage de ce format de fichier n'est pas supporté.
										</Typography>
									</div>
								)}
							</div>
							{this.state.documentNotary.files.length > 1 && (
								<div
									className={classes["arrow-container"]}
									onClick={this.goToNext}
									data-disabled={(!this.hasNext()).toString()}>
									<Image src={RightArrowIcon} alt="right arrow" />
								</div>
							)}
						</div>
						<div className={classes["footer"]}>
							{/* {this.state.document?.document_type?.name === "Document d'identité" && (
								<div className={classes["ocr-container"]}>
									<OcrResult percentage={this.state.validatedPercentage} />
								</div>
							)} */}

							<div className={classes["buttons-container"]}>
								<Button onClick={this.downloadFile}>Télécharger</Button>
							</div>
						</div>
					</div>
				)}
				{(!this.state.selectedFile || !this.state.documentNotary) && !this.state.isLoading && (
					<div className={classes["root"]}>
						<Typography typo={ETypo.TEXT_MD_REGULAR} color={ETypoColor.COLOR_GENERIC_BLACK} className={classes["refuse-text"]}>
							Document non trouvé
						</Typography>
					</div>
				)}
			</DefaultTemplate>
		);
	}

	override async componentDidMount() {
		try {
			const documentNotary = await DocumentsNotary.getInstance().getByUid(this.props.documentUid, {
				files: true,
				folder: true,
				depositor: true,
			});
			this.setState(
				{
					documentNotary,
					selectedFileIndex: 0,
					selectedFile: documentNotary.files![0]!,
					isLoading: false,
				},
				() => {
					this.getFilePreview();
				},
			);
		} catch (e) {
			this.setState({
				isLoading: false,
			});
			console.error(e);
		}
	}

	private async getFilePreview(): Promise<void> {
		try {
			const fileBlob: Blob = await FilesNotary.getInstance().download(this.state.selectedFile?.uid as string, this.props.documentUid);

			this.setState({
				fileBlob,
			});
		} catch (e) {
			console.error(e);
		}
	}

	private downloadFile() {
		if (!this.state.fileBlob) return;
		const url = window.URL.createObjectURL(this.state.fileBlob);
		const a = document.createElement("a");
		a.style.display = "none";
		a.href = url;
		// the filename you want
		a.download = this.state.selectedFile?.file_name as string;
		document.body.appendChild(a);
		a.click();
		window.URL.revokeObjectURL(url);
	}

	private goToPrevious() {
		const index = this.state.selectedFileIndex - 1;
		if (this.hasPrevious()) {
			this.setState(
				{
					selectedFile: this.state.documentNotary!.files![index]!,
					selectedFileIndex: index,
					fileBlob: null,
				},
				() => {
					this.getFilePreview();
				},
			);
		}
	}

	private goToNext() {
		if (this.hasNext()) {
			const index = this.state.selectedFileIndex + 1;
			this.setState(
				{
					selectedFile: this.state.documentNotary!.files![index]!,
					selectedFileIndex: index,
					fileBlob: null,
				},
				() => {
					this.getFilePreview();
				},
			);
		}
	}

	private hasPrevious() {
		const index = this.state.selectedFileIndex - 1;
		return index >= 0;
	}

	private hasNext() {
		const index = this.state.selectedFileIndex + 1;
		return index < this.state.documentNotary!.files!.length;
	}
}

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