import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { PanelLeft, Bell, User, LogOut } from "lucide-react";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { Divider, Typography } from "@mui/material";
import Badge from "@mui/material/Badge";
import { styled } from "@mui/material/styles";
import useAuth from "../../hooks/useAuth";
import { useNavigate } from "react-router-dom";
import backgroundImage from '../../assets/avatars/thumb-1.jpg';
import axios from "axios";

const API_BASE = import.meta.env.VITE_API_BASE_URL || "http://localhost:5000";

const StyledBadge = styled(Badge)(({ theme }) => ({
    "& .MuiBadge-badge": {
        right: -3,
        top: 13,
        border: `2px solid ${theme.palette.background.paper}`,
        padding: "0 4px",
    },
}));

const StudentHeader = ({ isSidebarCollapsed, toggleSidebar, isMobile }) => {
    const { user, logout } = useAuth();
    const navigate = useNavigate();

    const [anchorMyacc, setAnchorMyacc] = useState(null);
    const [anchorNotif, setAnchorNotif] = useState(null);
    const [notices, setNotices] = useState([]);

    const handleClickMyacc = (event) => {
        setAnchorMyacc(event.currentTarget);
    };

    const handleCloseMyacc = () => {
        setAnchorMyacc(null);
    };

    const handleClickNotif = (event) => {
        setAnchorNotif(event.currentTarget);
    };

    const handleCloseNotif = () => {
        setAnchorNotif(null);
    };

    const handleLogout = () => {
        logout();
        navigate("/login");
    };

    const handleProfile = () => {
        handleCloseMyacc();
        if (user?.role) {
            navigate(`/${user.role}/edit-profile`);
        }
    };

    const handleLogoutClick = () => {
        handleCloseMyacc();
        handleLogout();
    };

    const handleViewNotice = async (noticeId) => {
        if (!user?.token) return;
        try {
            const config = {
                headers: { Authorization: `Bearer ${user.token}` }
            };
            // Mark the notice as read
            await axios.post(`${API_BASE}/api/auth/notices/${noticeId}/read`, {}, config);
            // Update the notices state to reflect the read status
            setNotices(notices.map(notice => 
                notice._id === noticeId ? { ...notice, unread: false } : notice
            ));
            handleCloseNotif();
            navigate(`/student/notice/${noticeId}`);
        } catch (err) {
            console.error("Error marking notice as read:", err);
        }
    };

    const handleSeeAllNotices = () => {
        handleCloseNotif();
        navigate("/student/notices");
    };

    useEffect(() => {
        if (!user?.token) return;
        const fetchNotices = async () => {
            try {
                const config = {
                    headers: { Authorization: `Bearer ${user.token}` }
                };
                const { data } = await axios.get(`${API_BASE}/api/auth/notices/student`, config);
                setNotices(Array.isArray(data) ? data : []);
            } catch (err) {
                console.error("Error fetching notices:", err);
            }
        };
        fetchNotices();
    }, [user?.token]);

    const unreadCount = notices.filter((notice) => notice?.unread).length;

    const openMyAcc = Boolean(anchorMyacc);
    const openNotif = Boolean(anchorNotif);

    // Default profile picture
    const defaultProfilePicture = backgroundImage;

    return (
        <header
            className={`fixed top-0 left-0 z-40 flex w-full items-center justify-between border-b border-slate-200/80 bg-white/90 px-4 py-2 shadow-sm backdrop-blur-md transition-all duration-300 ${
                isSidebarCollapsed
                    ? "ml-[60px] w-[calc(100%-60px)]"
                    : "ml-[18%] w-[calc(100%-18%)] md:ml-[250px] md:w-[calc(100%-250px)]"
            }`}
        >
            <div className="part1">
                {!isMobile && (
                    <Button
                        onClick={toggleSidebar}
                        aria-label="Toggle sidebar"
                        className="!h-10 !min-w-[40px] !rounded-xl !p-2 !text-slate-600 hover:!bg-slate-100"
                    >
                        <PanelLeft size={20} strokeWidth={1.75} />
                    </Button>
                )}
            </div>

            <div className="part2 flex items-center justify-end gap-1 sm:gap-2">
                <div className="relative">
                    <IconButton
                        aria-label="notifications"
                        onClick={handleClickNotif}
                        sx={{
                            color: "rgb(71 85 105)",
                            borderRadius: "12px",
                            "&:hover": { backgroundColor: "rgba(15, 23, 42, 0.06)" },
                        }}
                    >
                        <StyledBadge badgeContent={unreadCount} color="secondary">
                            <Bell size={20} strokeWidth={1.75} />
                        </StyledBadge>
                    </IconButton>

                    <Menu
                        anchorEl={anchorNotif}
                        open={openNotif}
                        onClose={handleCloseNotif}
                        slotProps={{
                            paper: {
                                elevation: 0,
                                sx: {
                                    overflow: "visible",
                                    filter: "drop-shadow(0px 2px 8px rgba(0,0,0,0.32))",
                                    mt: 1.5,
                                    maxWidth: 300, // Increased width
                                    width: "100%", // Ensure it uses the max width
                                    "&::before": {
                                        content: '""',
                                        display: "block",
                                        position: "absolute",
                                        top: 0,
                                        right: 14,
                                        width: 10,
                                        height: 10,
                                        bgcolor: "background.paper",
                                        transform: "translateY(-50%) rotate(45deg)",
                                        zIndex: 0,
                                    },
                                },
                            },
                        }}
                        transformOrigin={{ horizontal: "right", vertical: "top" }}
                        anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
                    >
                        <MenuItem disabled>
                            <Typography variant="h6">Notifications</Typography>
                        </MenuItem>
                        <Divider />
                        {notices.length > 0 ? (
                            notices.slice(0, 5).map((notice) => (
                                <MenuItem
                                    key={notice._id}
                                    onClick={() => handleViewNotice(notice._id)}
                                    sx={{ 
                                        display: "flex", 
                                        flexDirection: "column", 
                                        alignItems: "flex-start", 
                                        py: 1,
                                        bgcolor: notice.unread ? "rgba(0, 128, 0, 0.1)" : "white" // Green background for unread notices
                                    }}
                                >
                                    <Typography variant="body1" sx={{ fontWeight: "bold" }}>
                                        {notice.title}
                                    </Typography>
                                    <Typography variant="body2" color="text.secondary">
                                        Class: {notice.classId?.subject ?? "—"}
                                    </Typography>
                                    <Typography variant="body2" color="text.secondary">
                                        {new Date(notice.createdAt).toLocaleString()}
                                    </Typography>
                                    <Typography variant="caption" color="primary">
                                        View full notification
                                    </Typography>
                                </MenuItem>
                            ))
                        ) : (
                            <MenuItem disabled sx={{ py: 2, justifyContent: "center" }}>
                                <Typography variant="body2" color="text.secondary">
                                    No new notifications
                                </Typography>
                            </MenuItem>
                        )}
                        <Divider />
                        <MenuItem onClick={handleSeeAllNotices} sx={{ justifyContent: "center" }}>
                            <Typography variant="caption" color="primary">
                                See all
                            </Typography>
                        </MenuItem>
                    </Menu>
                </div>

                <div className="relative">
                    <div
                        className="h-9 w-9 cursor-pointer overflow-hidden rounded-full ring-2 ring-slate-200/80 ring-offset-2 transition hover:ring-indigo-200"
                        onClick={handleClickMyacc}
                    >
                        <img
                            src={user?.profilePicture ? `${API_BASE}${user.profilePicture}` : defaultProfilePicture}
                            alt={user?.name || "User"}
                            className="w-full h-full object-cover"
                        />
                    </div>

                    <Menu
                        anchorEl={anchorMyacc}
                        id="account-menu"
                        open={openMyAcc}
                        onClose={handleCloseMyacc}
                        slotProps={{
                            paper: {
                                elevation: 0,
                                sx: {
                                    overflow: "visible",
                                    filter: "drop-shadow(0px 2px 8px rgba(0,0,0,0.32))",
                                    mt: 1.5,
                                    "& .MuiAvatar-root": {
                                        width: 32,
                                        height: 32,
                                        ml: -0.5,
                                        mr: 1,
                                    },
                                    "&::before": {
                                        content: '""',
                                        display: "block",
                                        position: "absolute",
                                        top: 0,
                                        right: 14,
                                        width: 10,
                                        height: 10,
                                        bgcolor: "background.paper",
                                        transform: "translateY(-50%) rotate(45deg)",
                                        zIndex: 0,
                                    },
                                },
                            },
                        }}
                        transformOrigin={{ horizontal: "right", vertical: "top" }}
                        anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
                    >
                        <MenuItem onClick={handleCloseMyacc} className="!bg-white">
                            <div className="flex items-center gap-3">
                                <div className="rounded-full w-[35px] h-[35px] overflow-hidden">
                                    <img
                                        src={user?.profilePicture ? `${API_BASE}${user.profilePicture}` : defaultProfilePicture}
                                        alt={user?.name || "User"}
                                        className="w-full h-full object-cover"
                                    />
                                </div>
                                <div className="info">
                                    <h3 className="text-[15px] font-[500] leading-5">{user?.name || "User"}</h3>
                                    <p className="text-[12px] font-[400] opacity-70">{user?.email || "No email"}</p>
                                </div>
                            </div>
                        </MenuItem>
                        <Divider />
                        <MenuItem onClick={handleProfile} className="flex items-center gap-3 !rounded-lg">
                            <User size={18} strokeWidth={1.75} className="text-slate-500" />
                            <span className="text-[14px] text-slate-800">Profile</span>
                        </MenuItem>
                        <MenuItem onClick={handleLogoutClick} className="flex items-center gap-3 !rounded-lg">
                            <LogOut size={18} strokeWidth={1.75} className="text-slate-500" />
                            <span className="text-[14px] text-slate-800">Log out</span>
                        </MenuItem>
                    </Menu>
                </div>
            </div>
        </header>
    );
};

StudentHeader.propTypes = {
    isSidebarCollapsed: PropTypes.bool.isRequired,
    toggleSidebar: PropTypes.func.isRequired,
    isMobile: PropTypes.bool.isRequired,
};

export default StudentHeader;