import React from "react";
import classes from "./classes.module.scss";
import DepositDocumentIcon from "@Assets/Icons/deposit-document.svg";
import PlusIcon from "@Assets/Icons/plus.svg";
import CrossIcon from "@Assets/Icons/cross.svg";
import DocumentCheckIcon from "@Assets/Icons/document-check.svg";
import Image from "next/image";

import Button, { EButtonVariant } from "../Button";
import Typography, { ITypo, ITypoColor } from "../Typography";

type IProps = {
	onChange: (documentList: File[]) => void;
};

interface IState {
	documents: File[];
	errorMessage: string;
}

type fileAccepted = {
	extension: string;
	size: number;
};

const filesAccepted: { [key: string]: fileAccepted } = {
	"application/pdf": {
		extension: "pdf",
		size: 41943040,
	},
	"image/jpeg": {
		extension: "jpeg",
		size: 41943040,
	},
	"image/png": {
		extension: "png",
		size: 41943040,
	},
	"image/jpg": {
		extension: "jpg",
		size: 41943040,
	},
};

export default class DepositRib extends React.Component<IProps, IState> {
	fileInput: HTMLInputElement | null = null;
	constructor(props: IProps) {
		super(props);
		this.state = {
			documents: [],
			errorMessage: "",
		};
	}

	handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault();
		const file = e.dataTransfer.files[0];
		this.handleFile(file!);
	};

	handleFile = (file: File) => {
		if (!file) return;
		if (file.type === "application/pdf" || file.type === "image/jpeg" || file.type === "image/png") {
			this.setState({
				documents: [file],
				errorMessage: "",
			});
			this.props.onChange([file]);
		} else {
			this.setState({ errorMessage: "Only PDF, JPEG, and PNG files are allowed." });
		}
	};

	handleRemove = () => {
		const updatedDocuments = [...this.state.documents];
		updatedDocuments.splice(0, 1);
		this.setState({ documents: updatedDocuments });
		this.props.onChange(updatedDocuments);
	};

	// handleValidate = async () => {
	// 	// Send documents to the backend for validation
	// 	if (this.state.documents.length === 0) return;
	// 	const formData = new FormData();
	// 	formData.append("file", this.state.documents[0]!, this.state.documents[0]!.name);

	// 	const sentFile = await Bucket.getInstance().post(formData);

	// 	// Reset documents state
	// 	this.setState({ documents: [] });
	// };

	// handleCancel = () => {
	// 	// Reset documents state
	// 	this.setState({ documents: [] });
	// };

	handleAddFile = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files && e.target.files[0];
		if (file) {
			this.handleFile(file);
		}
	};

	private shortName(name: string): string {
		const maxLength = 20;
		if (name.length > maxLength) {
			return name.substring(0, maxLength / 2) + "..." + name.substring(name.length - maxLength / 2, name.length);
		}
		return name;
	}

	public override render(): JSX.Element {
		return (
			<div className={classes["container"]}>
				<div className={classes["root"]} onDragOver={(e) => e.preventDefault()} onDrop={(e) => this.handleDrop(e)}>
					<input
						type="file"
						accept={Object.keys(filesAccepted).join(",")}
						onChange={this.handleAddFile}
						style={{ display: "none" }}
						ref={(input) => (this.fileInput = input)}
					/>

					<div className={classes["top-container"]}>
						<div className={classes["left"]}>
							<Image src={DepositDocumentIcon} alt="Deposit document" />
						</div>
						<div className={classes["separator"]} />

						<div className={classes["right"]}>
							<Typography typo={ITypo.TEXT_MD_SEMIBOLD} color={ITypoColor.COLOR_GENERIC_BLACK} className={classes["title"]}>
								<div>Déposer un RIB</div>
							</Typography>
							<Typography color={ITypoColor.COLOR_NEUTRAL_500} typo={ITypo.TEXT_SM_REGULAR}>
								Sélectionnez des documents .jpg, .pdf ou .png
							</Typography>
						</div>
					</div>

					<div className={classes["documents-container"]}>
						{this.state.documents.map((file) => {
							return (
								<div className={classes["file-container"]} key="0">
									<div className={classes["left-part"]}>
										<Image src={DocumentCheckIcon} alt="Document check" />
										<Typography typo={ITypo.TEXT_MD_REGULAR} color={ITypoColor.COLOR_NEUTRAL_500} title={file.name}>
											{this.shortName(file.name)}
										</Typography>
									</div>
									<Image
										src={CrossIcon}
										alt="Cross icon"
										className={classes["cross"]}
										onClick={() => this.handleRemove()}
									/>
								</div>
							);
						})}
					</div>

					<div className={classes["bottom-container"]}>
						<Button variant={EButtonVariant.LINE} className={classes["add-button"]} onClick={() => this.fileInput!.click()}>
							<Typography
								typo={ITypo.TEXT_MD_SEMIBOLD}
								color={ITypoColor.COLOR_SECONDARY_500}
								className={classes["add-document"]}>
								Ajouter un document <Image src={PlusIcon} alt="Plus icon" />
							</Typography>
						</Button>
					</div>

					{/* <button onClick={this.handleValidate}>Enregistrer</button>
					<button onClick={this.handleCancel}>Annuler</button> */}
				</div>
				{this.state.errorMessage && <div style={{ color: "red" }}>{this.state.errorMessage}</div>}
			</div>
		);
	}
}
