import React from "react";
import classes from "./classes.module.scss";
import Image from "next/image";
import NotificationIcon from "@Assets/icons/notification.svg";
import Toasts, { IToast } from "@Front/Stores/Toasts";
import NotificationModal from "./NotificationModal";
import InfoIcon from "@Assets/icons/info.svg";

type IProps = {};
type IState = {
	hasNotifications: boolean;
	isModalOpen: boolean;
	toastList: IToast[] | null;
};

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

	constructor(props: IProps) {
		super(props);
		this.state = {
			isModalOpen: false,
			toastList: Toasts.getInstance().toasts, //TODO : Get from bbd
			hasNotifications: Toasts.getInstance().toasts.length > 0, // TODO: Change this when we have notification stored in bbd, unread notifications
		};
		this.openModal = this.openModal.bind(this);
		this.closeModal = this.closeModal.bind(this);
		this.handleToastChange = this.handleToastChange.bind(this);
	}

	public override render(): JSX.Element {
		return (
			<div className={classes["root"]}>
				<div className={classes["icon-container"]} onClick={this.openModal}>
					<Image alt="notifications" src={NotificationIcon} className={classes["notification-icon"]} />
					{this.state.hasNotifications && (
						<Image className={classes["notification-dot"]} src={InfoIcon} alt="Unread notification" />
					)}
				</div>

				{this.state.isModalOpen && <NotificationModal isOpen={this.state.isModalOpen} closeModal={this.closeModal} />}
			</div>
		);
	}

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

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

	private handleToastChange(toastList: IToast[] | null) {
		this.setState({
			toastList,
			hasNotifications: toastList ? toastList.length > 0 : false,
		});
	}

	private openModal() {
		this.setState({ isModalOpen: true });
	}

	private closeModal() {
		this.setState({ isModalOpen: false });
	}
}
