import styles from "./styles.module.css";
import { Link, NavLink } from "react-router";
import { useEffect, useState } from "react";
import { LuPanelLeftClose, LuPanelLeftOpen, LuTvMinimalPlay } from "react-icons/lu";
import { LuGraduationCap } from "react-icons/lu";
import { LuUsers } from "react-icons/lu";
import { LuMail } from "react-icons/lu";
import { LuLayoutDashboard } from "react-icons/lu";
import { LuLogOut } from "react-icons/lu";
import { useGetCurrentUser } from "../../hooks/useGetCurrentUser";
import { motion, AnimatePresence } from "framer-motion";

// ✅ Fora do Sidebar — evita recriar a cada render
const MenuLabel = ({ show, children }: { show: boolean; children: React.ReactNode }) => (
    <AnimatePresence>
        {show && (
            <motion.span
                initial={{ opacity: 0, width: 0 }}
                animate={{ opacity: 1, width: "auto" }}
                exit={{ opacity: 0, width: 0 }}
                transition={{ duration: 0.25, ease: "easeInOut" }}
                style={{ overflow: "hidden", whiteSpace: "nowrap", display: "inline-block" }}
            >
                {children}
            </motion.span>
        )}
    </AnimatePresence>
);

export default function Sidebar() {
    const { getCurrentUser } = useGetCurrentUser();
    const [role, setRole] = useState(0);
    const [sideMenu, setSideMenu] = useState(true);

    const containerVariants = {
        initial: {},
        animate: {
            transition: {
                staggerChildren: 0.1, 
                staggerDirection: 1 
            }
        }, 
        exit: {
            transition: {
                staggerChildren: 0.1, 
                staggerDirection: -1 
            }
        }
    };

    const itemVariants = {
        initial: { opacity: 0, x: -10 },
        animate: { opacity: 1, x: 0 },
        exit: { opacity: 0, x: -10 }
    };

    useEffect(() => {
        const fetchCurrentUser = async () => {
            const currentUser = await getCurrentUser();
            setRole(currentUser.data.role_id);
        };
        fetchCurrentUser();
    }, []);

    return (
        // ✅ motion.aside anima a largura suavemente
        <motion.aside
            className={styles.sidebar}
            animate={{ width: sideMenu ? 260 : 100 }}
            transition={{ duration: 0.3, ease: "easeInOut" }}
        >
            <div className="d-flex justify-content-center" style={{ minHeight: '100px' }}>
                <AnimatePresence mode="wait">
                    {sideMenu ? (
                        <motion.div
                            key="logo"
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            transition={{ duration: 0.2 }}
                        >
                            <Link className={`${styles.logoLink} justify-content-center`} to="/dashboard">
                                <img className={`${styles.logo}`} src="/src/assets/logo.png" alt="Logo" />
                            </Link>
                        </motion.div>
                    ) : (
                        <motion.div
                            key="open-btn"
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            transition={{ duration: 0.2 }}
                            className="d-flex px-2 mb-4 mt-2"
                        >
                            <button
                                type="button"
                                className={`${styles.sidebarOpen} align-self-start bg-transparent border-0 justify-content-center`}
                                onClick={() => setSideMenu(true)}
                            >
                                <LuPanelLeftOpen size={30} />
                            </button>
                        </motion.div>
                    )}
                </AnimatePresence>

                {sideMenu ? (
                    <AnimatePresence>
                        <motion.button
                            key="close-btn"
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            transition={{ duration: 0.2, delay: 0.3 }}
                            className={`${styles.sidebarClose} align-items-center justify-content-center`} onClick={() => setSideMenu(prev => !prev)} style={{ position: 'absolute', left: '280px', top: '8px' }}> {sideMenu ? <LuPanelLeftClose size={30} /> : <LuPanelLeftOpen size={30} />} </motion.button>
                    </AnimatePresence>
                ) : null}
            </div>

            <nav className={styles.nav}>
                <motion.ul className={styles.navList}
                    variants={containerVariants}
                    initial="initial"
                    animate="animate"
                    exit="exit">
                    <motion.li variants={itemVariants} className={`${styles.navItem} px-2 ${sideMenu ? "text-start" : "text-center"}`}>
                        <NavLink className={({ isActive }) => isActive ? `${styles.navLink} ${styles.navLinkActive}` : styles.navLink} to="/dashboard">
                            <LuLayoutDashboard className={sideMenu ? "me-2" : "w-100"} size={24} />
                            <MenuLabel show={sideMenu}>Dashboard</MenuLabel>
                        </NavLink>
                    </motion.li>
                    <motion.li variants={itemVariants} className={`${styles.navItem} px-2 ${sideMenu ? "text-start" : "text-center"}`}>
                        <NavLink className={({ isActive }) => isActive ? `${styles.navLink} ${styles.navLinkActive}` : styles.navLink} to="/videos">
                            <LuTvMinimalPlay className={sideMenu ? "me-2" : "w-100"} size={24} />
                            <MenuLabel show={sideMenu}>Videos</MenuLabel>
                        </NavLink>
                    </motion.li>
                    <motion.li variants={itemVariants} className={`${styles.navItem} px-2 ${sideMenu ? "text-start" : "text-center"}`}>
                        <NavLink className={({ isActive }) => isActive ? `${styles.navLink} ${styles.navLinkActive}` : styles.navLink} to="/workshops">
                            <LuGraduationCap className={sideMenu ? "me-2" : "w-100"} size={24} />
                            <MenuLabel show={sideMenu}>Workshops</MenuLabel>
                        </NavLink>
                    </motion.li>
                    {role === 1 && (
                        <motion.li variants={itemVariants} className={`${styles.navItem} px-2 ${sideMenu ? "text-start" : "text-center"}`}>
                            <NavLink className={({ isActive }) => isActive ? `${styles.navLink} ${styles.navLinkActive}` : styles.navLink} to="/admin/users">
                                <LuUsers className={sideMenu ? "me-2" : "w-100"} size={24} />
                                <MenuLabel show={sideMenu}>Utilizadores</MenuLabel>
                            </NavLink>
                        </motion.li>
                    )}
                    <motion.li variants={itemVariants} className={`${styles.navItem} px-2 ${sideMenu ? "text-start" : "text-center"}`}>
                        <NavLink className={({ isActive }) => isActive ? `${styles.navLink} ${styles.navLinkActive}` : styles.navLink} to="/contactos">
                            <LuMail className={sideMenu ? "me-2" : "w-100"} size={24} />
                            <MenuLabel show={sideMenu}>Contactos</MenuLabel>
                        </NavLink>
                    </motion.li>
                </motion.ul>
            </nav>

            <div className={`${styles.logoutWrapper} px-2`}>
                <Link className={styles.logoutButton} to="/logout">
                    <LuLogOut className={sideMenu ? "me-2" : "w-100"} size={24} />
                    <MenuLabel show={sideMenu}>Logout</MenuLabel>
                </Link>
            </div>
        </motion.aside>
    );
}