import { useContext, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { EgovNotification } from '../../../models/EgovNotifications';
import { markNotificationAsRead } from '../../../API/notifications';
import Loader from '../../UI/Loader/Loader';
import NotificationsContext from "../../../context/notifications-context";
import useLoading from "../../../hooks/useLoading";
import dayjs from "dayjs";
import AuthContext from "../../../context/auth-context";
import { LinkWithRole } from "../../HOC/LinkWithRole";

interface IObjectKeys {
    [key: string]: string;
}

const dictionary: IObjectKeys = {
    'support': 'category-color-support',
    'announcements': 'category-color-announcements',
    'personal': 'category-color-personal',
    'service': 'category-color-service',
    'dpass': 'category-color-dpass',
    'anakoinosi': 'category-color-anakoinosi',
    'net support':'category-color-net-support',
    'service is down': 'category-color-service-is-down',
};

const NotificationPopup = ({ close }: { close: () => void }) => {
    const { updateUnread, getUnreadMessages, resetUnreadMessages } = useContext(NotificationsContext);
    const { currentUser } = useContext(AuthContext);
    const [messages, setMessages] = useState<EgovNotification[]>([]);
    const [isLoading, setIsLoading] = useLoading(true);

    const markAsReadMessagesAPI = async (id: number) => {
        setIsLoading(true);
        resetUnreadMessages();

        // Mark the notification as read in the DB
        await markNotificationAsRead(id);

        // Remove from the unread notification list
        const newMessages = messages.filter(i => i.id !== id);
        if (newMessages.length === 0) close();
        setMessages(newMessages);
        setIsLoading(false);
    };

    const getUnreadMessagesAPI = async () => {
        const mes = await getUnreadMessages();
        setMessages(mes);
        setIsLoading(false);
    };

    useEffect(() => {
        getUnreadMessagesAPI();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // Ensure that currentUser is available and valid
    if (!currentUser) return null;

    const uniqueMicroservices = Object.keys(currentUser.microservice_permissions);
    const uniqueRoles = Object.values(currentUser.roles);

    return (
        <div className="profile--dd-list" id="notification-popup">
            {isLoading ? (
                <div className="loader-wrapper">
                    <Loader />
                </div>
            ) : (
                messages && messages.length > 0 ? (
                    messages.map((item, index) => {
                        const itemRead = item.is_read;
                        const categoryColor = dictionary[item.tag];
                        const isTagInArray =
                            item.tag &&
                            uniqueMicroservices.includes(item.tag) &&
                            item.role &&
                            uniqueRoles.includes(item.role) &&
                            item.module;

                        return (
                            <div
                                className="profile--dd-list--wrapper row"
                                onClick={(e) => {
                                    if (item.is_read) return;
                                    e.stopPropagation();
                                    markAsReadMessagesAPI(item.id);
                                    updateUnread();
                                }}
                                key={index}
                            >
                                <div className="offset-xxl-2 gx-5 col-xxl-10 col-10 profile--dd-list--wrapper--date">
                                    <p>{dayjs(item.published_at).format('DD/MM/YYYY')}</p>
                                </div>
                                <div className="profile--dd-list--wrapper--main row col-12">
                                    <div className="col-2 profile--dd-list--wrapper--main--category">
                                        <span className={categoryColor}>{item.tag}</span>
                                    </div>
                                    <div className="col-xxl-9 col-11 gx-5 profile--dd-list--wrapper--main--title">
                                        {isTagInArray ? (
                                            <LinkWithRole
                                                inheritRole={item.role}
                                                to={
                                                    ( item.tag === 'dpass' && item.role === 'hr_support' ||item.tag === 'difo')
                                                        ? ``
                                                        : `/applications/${item.tag}/services/${item.module}`
                                                }
                                            >
                                                <span className="title-black">{item.title}</span>&nbsp;
                                                <span>{item.body}</span>
                                            </LinkWithRole>
                                        ) : (
                                            <>
                                                <span className="title-black">{item.title}</span>&nbsp;
                                                <span>{item.body}</span>
                                            </>
                                        )}
                                    </div>
                                    <div className="col-1 profile--dd-list--wrapper--main--state" id={itemRead ? 'read' : 'notRead'}>
                                        <span className="state-circle"></span>
                                    </div>
                                </div>
                            </div>
                        );
                    })
                ) : (
                    <div className="loader-wrapper">
                        <Loader />
                    </div>
                )
            )}

            {/* Notification popup - read more button */}
            <div className="profile--dd-list--wrapper--allNotifications row">
                <Link to="/messages">
                    <button>
                        <span>Όλες οι ειδοποιήσεις</span>
                    </button>
                </Link>
            </div>
        </div>
    );
};

export default NotificationPopup;
