import React from "react";
import classes from "./classes.module.scss";
import Typography, { ETypo, ETypoColor } 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";
import Check from "@Front/Components/Elements/Icons/Check";

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);
		this.readAllNotifications = this.readAllNotifications.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={ETypo.TEXT_MD_SEMIBOLD}>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={ETypo.TEXT_SM_REGULAR} color={ETypoColor.COLOR_SECONDARY_500}>
							Tout marquer comme lu
						</Typography>
						<Check color={ETypoColor.COLOR_SECONDARY_500} />
					</div>
					<div className={classes["notification-body"]}>
						<>
							{!this.state.toastList || this.state.toastList.length === 0 ? (
								<div className={classes["missing-notification"]}>
									<Typography typo={ETypo.TEXT_LG_REGULAR} color={ETypoColor.COLOR_NEUTRAL_500}>
										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();
		this.props.closeModal();
	}

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