"use client";
import { useState, useEffect, useRef } from "react";
import { useSessionStore } from "@store/Sesion.Store";
import { EVENT_TYPES, useEventHandlerStore } from "@store/EventHandler.Store";
import { useAlert } from "@store/Alert.Store";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import AccountCircleOutlinedIcon from "@mui/icons-material/AccountCircleOutlined";
import {
    DeleteSystemNotificationParams,
    ISystemNotification,
    PaginateSystemNotificationsParams,
    PaginateSystemNotificationsResults,
    UpdateSystemNotificationParams,
    NotificationType,
} from "@core/Models/SystemNotifications.model";
import API from "@services/Api.Service";
import { useRouter } from "next/navigation";
import {
    deleteNotificationsByDate,
    deleteSystemNotification,
    findSystemNotifications,
    setStateNotificationByUser,
    updateSystemNotification,
} from "./Notifications.Service";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import MarkReadIcon from "@mui/icons-material/MarkChatReadOutlined";
import MarkUnReadIcon from "@mui/icons-material/MarkUnreadChatAltOutlined";
import ReloadIcon from "@mui/icons-material/Autorenew";
import DoneAllIcon from "@mui/icons-material/DoneAll";
import NotificationsActiveIcon from "@mui/icons-material/NotificationsActive";
import InboxIcon from "@mui/icons-material/Inbox";
import IconButton from "@mui/material/IconButton";
import Pagination from "@mui/material/Pagination";
import { useConfirmStore } from "@core/Store/Confirm.Store";
import HeaderConfProvider from "@core/app/components/HeaderConfProvider/HeaderConfProvider";
import { useMenuStore } from "@core/Store/Menu.Store";
import dayjs from "dayjs";
import "dayjs/locale/es";
import { motion, AnimatePresence } from "motion/react";

export type SystemNotificationRow = ISystemNotification & { _id: string };

export default function EditProfile() {
    const alert = useAlert();
    const confirm = useConfirmStore();
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const location = useLocationStore();
    const menu = useMenuStore();
    const router = useRouter();
    const [filterType, setFilterType] = useState<string>("ALL");
    const [pageSize] = useState<number>(
        parseInt(
            process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE ? process.env.NEXT_PUBLIC_DATAGRID_PAGE_SIZE : "10"
        )
    );
    const [notifications, setNotifications] = useState<PaginateSystemNotificationsResults>();
    const notificationsRef = useRef(notifications);

    const handleMarkRead = (notif: SystemNotificationRow) => {
        const data: UpdateSystemNotificationParams = {
            id: notif._id,
            readed: !notif.readed,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        const loadPage = notificationsRef.current?.page;

        updateSystemNotification(data)
            .then(() => {
                loadNotifications(loadPage, pageSize);
            })
            .catch((err) => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
                alert.showError(err.desc);
            });
    };

    const handleDelete = (notif: SystemNotificationRow) => {
        confirm.show(
            "¿Está seguro de que desea eliminar esta notificación?",
            () => {
                eventHandler.setEventType(EVENT_TYPES.LOADING);
                const data: DeleteSystemNotificationParams = {
                    id: notif._id,
                    sessionUser: SessionInfo.userId,
                };

                let loadPage = 1;

                if (notificationsRef.current) {
                    loadPage = notificationsRef.current.page;
                }

                deleteSystemNotification(data)
                    .then(() => {
                        loadNotifications(loadPage, pageSize);
                    })
                    .catch((err) => {
                        eventHandler.setEventType(EVENT_TYPES.SLEEP);
                        alert.showError(err.desc);
                    });
            },
            () => {
                // Do nothing
            }
        );
    };

    const setNotiState = (state: boolean) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        setStateNotificationByUser({
            state: state,
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                loadNotifications(1, pageSize);
                alert.showSuccess("Las notificaciones han sido actualizadas");
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const handleNotificationClick = async (notif: SystemNotificationRow) => {
        if (!notif.readed) {
            handleMarkRead(notif);
        }

        if (!notif.type || !notif.code) return;

        eventHandler.setEventType(EVENT_TYPES.LOADING);
        try {
            let companyId = notif.companyId;

            switch (notif.type) {
                case NotificationType.APPOINTMENT:
                    // Fetch appointment to get clientId and companyId
                    const aptRes = await API.post<any>("appointments/get-event", {
                        appointmentId: notif.code,
                        sessionUser: SessionInfo.userId,
                    });
                    if (aptRes && aptRes.clientId) {
                        companyId = companyId || aptRes.companyId;
                        if (companyId) {
                            router.push(`/admin/org/${companyId}/client/${aptRes.clientId}/appointments/${notif.code}`);
                        }
                    }
                    break;
                case NotificationType.COMPANY:
                    router.push(`/admin/org/profile/${notif.code}`);
                    break;
                case NotificationType.EMPLOYEE:
                case NotificationType.SCHEDULE:
                case NotificationType.SCHEDULE_EXCEPTION:
                case NotificationType.SCHEDULE_RESTRICTION:
                    if (!companyId) {
                        const empRes = await API.post<any>("employees/get-by-id", {
                            id: notif.code,
                            sessionUser: SessionInfo.userId,
                        });
                        companyId = companyId || empRes?.companyId;
                    }
                    if (companyId) {
                        if (notif.type === NotificationType.EMPLOYEE || notif.type === NotificationType.SCHEDULE) {
                            router.push(`/admin/org/profile/${companyId}/collaborators/${notif.code}`);
                        } else if (notif.type === NotificationType.SCHEDULE_EXCEPTION) {
                            router.push(`/admin/org/profile/${companyId}/collaborators/${notif.code}/exceptions`);
                        } else {
                            router.push(`/admin/org/profile/${companyId}/collaborators/${notif.code}/restrictions`);
                        }
                    }
                    break;
                case NotificationType.BILLING:
                    companyId = companyId || Object.keys(SessionInfo.organizationSubscriptions || {})[0];
                    if (companyId) {
                        router.push(`/admin/org/profile/${companyId}/dashboard`);
                    }
                    break;
                case NotificationType.MESSAGE:
                    if (notif.conversationId) {
                        router.push(`/messages?conversation=${notif.conversationId}`);
                    }
                    break;
            }
        } catch (e: any) {
            console.error("Error navigating from notification", e);
            alert.showError(e.format ? e.format() : "Error al navegar: " + (e.message || "Desconocido"));
        } finally {
            eventHandler.setEventType(EVENT_TYPES.SLEEP);
        }
    };

    const handleDeleteByDate = (dateFrom: Date | undefined, dateTo: Date | undefined) => {
        if (!SessionInfo.userId) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        deleteNotificationsByDate({
            userId: SessionInfo.userId,
            dateFrom: dateFrom,
            dateTo: dateTo,
            sessionUser: SessionInfo.userId,
        })
            .then(() => {
                loadNotifications(1, pageSize);
                alert.showSuccess("Las notificaciones han sido eliminadas");
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    const createMenu = () => {
        menu.clear();

        menu.add({
            text: "Marcar todas como leidas",
            onClick: () => {
                setNotiState(true);
            },
            icon: <MarkReadIcon />,
        });

        menu.add({
            text: "Marcar todas como no leidas",
            onClick: () => {
                setNotiState(false);
            },
            icon: <MarkUnReadIcon />,
        });

        menu.divider();

        menu.add({
            text: "Eliminar las notificaciones de hoy",
            onClick: () => {
                confirm.show(
                    "¿Está seguro que desea eliminar las notificaciones de hoy?",
                    () => {
                        const filterFrom = dayjs().startOf("day").toDate();
                        const filterTo = dayjs().endOf("day").toDate();
                        handleDeleteByDate(filterFrom, filterTo);
                    },
                    () => {}
                );
            },
            icon: <DeleteIcon />,
        });

        menu.add({
            text: "Eliminar las notificaciones de la semana",
            onClick: () => {
                confirm.show(
                    "¿Está seguro que desea eliminar las notificaciones de la semana?",
                    () => {
                        const filterFrom = dayjs().startOf("week").toDate();
                        const filterTo = dayjs().endOf("week").toDate();
                        handleDeleteByDate(filterFrom, filterTo);
                    },
                    () => {}
                );
            },
            icon: <DeleteIcon />,
        });

        menu.add({
            text: "Eliminar las notificaciones del mes",
            onClick: () => {
                confirm.show(
                    "¿Está seguro que desea eliminar las notificaciones del mes?",
                    () => {
                        const filterFrom = dayjs().startOf("month").toDate();
                        const filterTo = dayjs().endOf("month").toDate();
                        handleDeleteByDate(filterFrom, filterTo);
                    },
                    () => {}
                );
            },
            icon: <DeleteIcon />,
        });

        menu.add({
            text: "Eliminar las notificaciones del año",
            onClick: () => {
                confirm.show(
                    "¿Está seguro que desea eliminar las notificaciones del año?",
                    () => {
                        const filterFrom = dayjs().startOf("year").toDate();
                        const filterTo = dayjs().endOf("year").toDate();
                        handleDeleteByDate(filterFrom, filterTo);
                    },
                    () => {}
                );
            },
            icon: <DeleteIcon />,
        });

        menu.add({
            text: "Eliminar todas las notificaciones",
            onClick: () => {
                confirm.show(
                    "¿Está seguro que desea eliminar todas las notificaciones?",
                    () => {
                        handleDeleteByDate(undefined, undefined);
                    },
                    () => {}
                );
            },
            icon: <DeleteIcon />,
        });
    };

    useEffect(() => {
        location.clear();

        location.add({
            url: "/user/profile",
            title: "Perfil de usuario",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        location.add({
            url: "/user/profile/edit",
            title: "Notificaciones",
            icon: <AccountCircleOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });

        createMenu();

        return () => {
            menu.clear();
        };
    }, []);

    useEffect(() => {
        if (!SessionInfo.userId) {
            return;
        }

        loadNotifications(1, pageSize);
    }, [SessionInfo.userId]);

    useEffect(() => {
        notificationsRef.current = notifications;
    }, [notifications]);

    const loadNotifications = (page: number = 1, pageSize: number = 30) => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        const filterData: PaginateSystemNotificationsParams = {
            userId: SessionInfo.userId,
            sessionUser: SessionInfo.userId,
            page: page,
            limit: pageSize,
        };

        findSystemNotifications(filterData)
            .then((res) => {
                if (res.page > res.pages && res.page > 1) {
                    loadNotifications(res.page - 1, pageSize);
                    return;
                }
                setNotifications(res);
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.SLEEP);
            });
    };

    // Derived states for UI gamification
    const allDataList = (notifications?.data || []) as SystemNotificationRow[];
    
    // Apply type filter
    const dataList = allDataList.filter(n => {
        if (filterType === "ALL") return true;
        if (filterType === "APPOINTMENT") return n.type === NotificationType.APPOINTMENT;
        if (filterType === "COMPANY") return n.type === NotificationType.COMPANY || n.type === NotificationType.EMPLOYEE || n.type === NotificationType.SCHEDULE || n.type === NotificationType.SCHEDULE_EXCEPTION || n.type === NotificationType.SCHEDULE_RESTRICTION;
        if (filterType === "BILLING") return n.type === NotificationType.BILLING;
        if (filterType === "MESSAGE") return n.type === NotificationType.MESSAGE;
        if (filterType === "SYSTEM") return n.type === NotificationType.SYSTEM || !n.type;
        return true;
    });

    const unreadCount = allDataList.filter(n => !n.readed).length;
    const isInboxZero = allDataList.length > 0 && unreadCount === 0;

    return (
        <>
            <Location />
            <HeaderConfProvider />
            
            <div style={{ padding: "20px 40px", maxWidth: "900px", margin: "0 auto", paddingBottom: "100px" }}>
                
                {/* Header and Controls */}
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "30px", borderBottom: "1px solid #eaeaea", paddingBottom: "20px" }}>
                    <div>
                        <h1 style={{ margin: 0, fontSize: "28px", color: "var(--black-light)", display: "flex", alignItems: "center", gap: "10px" }}>
                            <NotificationsActiveIcon sx={{ color: "var(--wine-dark)" }} /> 
                            Bandeja de Entrada
                        </h1>
                        <p style={{ margin: "5px 0 0 0", color: "#666", fontSize: "14px" }}>
                            {unreadCount > 0 ? `Tienes ${unreadCount} notificación(es) sin leer.` : "No tienes notificaciones pendientes."}
                        </p>
                    </div>
                    
                    <div style={{ display: "flex", gap: "10px" }}>
                        {unreadCount > 0 && (
                            <button
                                onClick={() => setNotiState(true)}
                                style={{
                                    backgroundColor: "var(--wine-lighterX2)",
                                    color: "var(--wine-darkest)",
                                    border: "none",
                                    padding: "8px 16px",
                                    borderRadius: "20px",
                                    cursor: "pointer",
                                    fontWeight: "bold",
                                    display: "flex",
                                    alignItems: "center",
                                    gap: "5px",
                                    transition: "all 0.2s"
                                }}
                                onMouseOver={e => e.currentTarget.style.backgroundColor = "var(--wine-light)"}
                                onMouseOut={e => e.currentTarget.style.backgroundColor = "var(--wine-lighterX2)"}
                            >
                                <DoneAllIcon fontSize="small" /> Marcar leídas
                            </button>
                        )}
                        <IconButton
                            onClick={() => loadNotifications(notifications?.page, pageSize)}
                            color="secondary"
                            style={{ backgroundColor: "#f5f5f5" }}
                        >
                            <ReloadIcon sx={{ color: "var(--black)" }} />
                        </IconButton>
                    </div>
                </div>

                {/* Filters */}
                {allDataList.length > 0 && (
                    <div style={{ display: "flex", gap: "10px", marginBottom: "25px", flexWrap: "wrap" }}>
                        {[
                            { id: "ALL", label: "Todas" },
                            { id: "APPOINTMENT", label: "Turnos" },
                            { id: "MESSAGE", label: "Mensajes" },
                            { id: "COMPANY", label: "Negocio y Equipo" },
                            { id: "BILLING", label: "Suscripciones y Pagos" },
                            { id: "SYSTEM", label: "Sistema" }
                        ].map(f => (
                            <button
                                key={f.id}
                                onClick={() => setFilterType(f.id)}
                                style={{
                                    padding: "8px 16px",
                                    borderRadius: "20px",
                                    border: "1px solid",
                                    borderColor: filterType === f.id ? "var(--wine-dark)" : "#eaeaea",
                                    backgroundColor: filterType === f.id ? "var(--wine-dark)" : "#fff",
                                    color: filterType === f.id ? "#fff" : "#666",
                                    cursor: "pointer",
                                    fontWeight: filterType === f.id ? "bold" : "normal",
                                    transition: "all 0.2s"
                                }}
                            >
                                {f.label}
                            </button>
                        ))}
                    </div>
                )}

                {/* Inbox Zero State */}
                {isInboxZero && dataList.length > 0 && (
                    <motion.div 
                        initial={{ opacity: 0, y: 20 }} 
                        animate={{ opacity: 1, y: 0 }}
                        style={{ textAlign: "center", padding: "40px 20px", backgroundColor: "#f9fafc", borderRadius: "15px", marginBottom: "30px" }}
                    >
                        <InboxIcon sx={{ fontSize: "64px", color: "var(--wine-light)", marginBottom: "15px" }} />
                        <h2 style={{ margin: 0, color: "var(--wine-darkest)" }}>¡Estás al día! 🌟</h2>
                        <p style={{ color: "#666" }}>Has gestionado todas tus notificaciones recientes.</p>
                    </motion.div>
                )}

                {dataList.length === 0 && (
                    <div style={{ textAlign: "center", padding: "80px 20px" }}>
                        <InboxIcon sx={{ fontSize: "64px", color: "#ccc", marginBottom: "15px" }} />
                        <h2 style={{ margin: 0, color: "#999" }}>Bandeja Vacía</h2>
                        <p style={{ color: "#aaa" }}>Aún no has recibido ninguna notificación.</p>
                    </div>
                )}

                {/* Notifications List */}
                <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
                    <AnimatePresence>
                        {dataList.map((notif) => (
                            <motion.div
                                key={notif._id}
                                initial={{ opacity: 0, x: -20 }}
                                animate={{ opacity: 1, x: 0 }}
                                exit={{ opacity: 0, scale: 0.95 }}
                                transition={{ duration: 0.2 }}
                                style={{
                                    backgroundColor: notif.readed ? "#ffffff" : "var(--wine-lighterX2)",
                                    border: notif.readed ? "1px solid #eaeaea" : "1px solid var(--wine-light)",
                                    borderRadius: "12px",
                                    padding: "16px 20px",
                                    display: "flex",
                                    alignItems: "flex-start",
                                    justifyContent: "space-between",
                                    boxShadow: notif.readed ? "none" : "0 4px 12px rgba(127, 42, 255, 0.1)",
                                    transition: "all 0.2s ease",
                                    cursor: notif.type && notif.code ? "pointer" : "default"
                                }}
                                onClick={() => handleNotificationClick(notif)}
                                onMouseOver={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 6px 16px rgba(0,0,0,0.08)"; }}
                                onMouseOut={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = notif.readed ? "none" : "0 4px 12px rgba(127, 42, 255, 0.1)"; }}
                            >
                                <div style={{ display: "flex", gap: "15px", alignItems: "flex-start", flex: 1 }}>
                                    <div style={{ marginTop: "4px" }}>
                                        {notif.readed ? 
                                            <MarkReadIcon sx={{ color: "#ccc" }} /> : 
                                            <MarkUnReadIcon sx={{ color: "var(--wine-dark)" }} />
                                        }
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "4px" }}>
                                            <h3 style={{ margin: 0, fontSize: "16px", fontWeight: notif.readed ? "normal" : "bold", color: notif.readed ? "#444" : "var(--wine-darkest)" }}>
                                                {notif.subject}
                                            </h3>
                                        </div>
                                        <p style={{ margin: 0, fontSize: "14px", color: notif.readed ? "#777" : "#333", lineHeight: "1.5" }}>
                                            {notif.message}
                                        </p>
                                    </div>
                                </div>
                                <div style={{ display: "flex", gap: "5px", opacity: 0.8 }} onClick={(e) => e.stopPropagation()}>
                                    <IconButton size="small" onClick={() => handleMarkRead(notif)} title={notif.readed ? "Marcar como no leída" : "Marcar como leída"}>
                                        {notif.readed ? <MarkUnReadIcon fontSize="small" /> : <MarkReadIcon fontSize="small" color="primary" />}
                                    </IconButton>
                                    <IconButton size="small" onClick={() => handleDelete(notif)} title="Eliminar">
                                        <DeleteIcon fontSize="small" sx={{ color: "#d32f2f" }} />
                                    </IconButton>
                                </div>
                            </motion.div>
                        ))}
                    </AnimatePresence>
                </div>

                {/* Pagination */}
                {notifications && notifications.pages > 1 && (
                    <div style={{ display: "flex", justifyContent: "center", marginTop: "40px" }}>
                        <Pagination 
                            count={notifications.pages} 
                            page={notifications.page} 
                            onChange={(e, value) => loadNotifications(value, pageSize)}
                            color="secondary"
                        />
                    </div>
                )}
            </div>
        </>
    );
}
