import React from "react";
import classes from "./classes.module.scss";
import Typography, { ITypo, ITypoColor } from "@Front/Components/DesignSystem/Typography";
import CloseIcon from "@Assets/Icons/cross.svg";
import Image from "next/image";
import ToastHandler from "@Front/Components/DesignSystem/Toasts/ToastsHandler";
import Toasts, { IToast } from "@Front/Stores/Toasts";

type IProps = {
	isOpen: boolean;
	closeModal: () => void;
};
type IState = {
	toastList: IToast[] | null;
};

export default class NotificationModal extends React.Component<IProps, IState> {
	private removeOnToastChange: () => void = () => {};

	constructor(props: IProps) {
		super(props);
		this.state = {
			toastList: Toasts.getInstance().toasts,
		};
		this.handleToastChange = this.handleToastChange.bind(this);
	}

	public override render(): JSX.Element | null {
		if (!this.props.isOpen) return null;
		return (
			<>
				<div className={classes["background"]} onClick={this.props.closeModal} />
				<div className={classes["root"]}>
					<div className={classes["notification-header"]}>
						<Typography typo={ITypo.P_SB_16}>Notifications</Typography>
						<div className={classes["close-icon"]} onClick={this.props.closeModal}>
							<Image src={CloseIcon} alt="Close notification modal" className={classes["close-icon"]}></Image>
						</div>
					</div>
					<div className={classes["notification-subheader"]} onClick={this.readAllNotifications}>
						<Typography typo={ITypo.CAPTION_14}>Tout marquer comme lu</Typography>
					</div>
					<div className={classes["notification-body"]}>
						<>
							{!this.state.toastList || this.state.toastList.length === 0 ? (
								<div className={classes["missing-notification"]}>
									<Typography typo={ITypo.P_18} color={ITypoColor.GREY}>
										Vous n'avez pas de notifications.
									</Typography>
								</div>
							) : (
								<ToastHandler />
							)}
						</>
					</div>
				</div>
			</>
		);
	}

	public override componentDidMount() {
		this.removeOnToastChange = Toasts.getInstance().onChange(this.handleToastChange);
	}

	public override componentWillUnmount() {
		this.removeOnToastChange();
	}

	private readAllNotifications() {
		Toasts.getInstance().closeAll();
	}

	private handleToastChange(toastList: IToast[] | null) {
		this.setState({
			toastList,
		});
	}
}
