import React, { useState, useRef, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
    Avatar,
    Divider,
    IconButton,
    AppBar,
    Toolbar
} from '@mui/material';
import MenuIcon from '@mui/icons-material/Menu';
import PersonIcon from '@mui/icons-material/Person';
import AddIcon from '@mui/icons-material/Add';
import LogoutIcon from '@mui/icons-material/Logout';
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
import Picker from './Picker'
import { useUser } from '../contexts/UserContext';
import AdminTable from "../pages/AdminTable";
import { Role } from '../types/user';

const Navbar = () => {
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
    const [showProfileMenu, setShowProfileMenu] = useState(false);
    const navigate = useNavigate();
    const menuRef = useRef(null);

    const { user, logout: onLogout } = useUser();

    useEffect(() => {
        const handleClickOutside = (event) => {
            if (menuRef.current && !menuRef.current.contains(event.target)) {
                setShowProfileMenu(false);
            }
        };

        document.addEventListener('click', handleClickOutside);
        return () => {
            document.removeEventListener('click', handleClickOutside);
        };
    }, []);

    useEffect(() => {
        if (user) {
            setShowProfileMenu(false);
        }
    }, [user]);

    const toggleMobileMenu = () => {
        setIsMobileMenuOpen(!isMobileMenuOpen);
    };

    const handleLogout = () => {
        onLogout();
        navigate('/');

    };

    return (
        <AppBar position="sticky" style={{ backgroundColor: '#032e15' }}>
            <Toolbar className="px-2 md:px-8">
                {/* Logo (Left) */}
                <div className="mr-6">
                    <Link to="/" className="text-2xl font-bold text-white no-underline">
                        <img src="/assets/logo.png" className="w-[40px] m-auto"></img>
                    </Link>
                </div>

                {/* Navigation Links - Desktop only */}
                <div className="hidden md:flex items-center gap-6">
                    <a onClick={() => navigate('/about')} className="hover:underline cursor-pointer">O projektu</a>
                    <Picker />
                </div>

                {/* Search and User Controls - Right side */}
                <div className="flex ml-auto items-center gap-4">
                    {/* Search - Desktop only */}
                    <div className="hidden md:block">
                        <input type="text" placeholder="Hledat článek..." className="px-2 py-1 rounded outline-none text-white" />
                    </div>

                    {/* User Profile - Desktop only */}
                    <div className="hidden md:block">
                        {user ? (
                            <div ref={menuRef} className="relative">
                                {user?.profilePicture && (user.profilePicture.trim() !== import.meta.env.VITE_PROFILE_PICTURES_URL) ? (
                                    <div
                                        className="w-10 h-10 cursor-pointer overflow-hidden rounded-full border shadow-lg"
                                        onClick={() => setShowProfileMenu(!showProfileMenu)}
                                    >
                                        <img
                                            src={user.profilePicture}
                                            alt="Profilový obrázek"
                                            className="w-full h-full object-cover"
                                        />
                                    </div>
                                ) : (
                                    <Avatar onClick={() => setShowProfileMenu(!showProfileMenu)} className="cursor-pointer">
                                        {user?.username.charAt(0)}
                                    </Avatar>
                                )}

                                {showProfileMenu && (
                                    <div className="absolute min-w-[300px] right-0 top-12 bg-yellow-50 text-black border border-gray-300 p-3 shadow-lg w-40 z-50">
                                        <p className="font-semibold text-center">{user?.username}</p>
                                        <p className="text-sm mb-2 text-center">{user?.email}</p>
                                        <Divider />
                                        <div className="flex mt-2 p-2 justify-center items-center cursor-pointer space-x-1 hover:bg-yellow-300 transition rounded" onClick={() => { navigate('/profile'); setShowProfileMenu(false); }}>
                                            <button className="text-green-950 cursor-pointer">
                                                Profil
                                            </button>
                                            <PersonIcon />
                                        </div>

                                        {user?.role === Role.SPRAVCE && (
                                            <div className="flex mt-2 p-2 items-center justify-center cursor-pointer space-x-1 hover:bg-yellow-600 rounded transition" onClick={() => { navigate('/admin'); setShowProfileMenu(false); }}>
                                                <button className="text-black cursor-pointer" >
                                                    Admin panel
                                                </button>
                                                <AdminPanelSettingsIcon />
                                            </div>
                                        )}

                                        <div className="flex my-2 p-2 justify-center items-center cursor-pointer space-x-1 hover:bg-green-600 transition rounded" onClick={() => { navigate('/editor'); setShowProfileMenu(false); }}>
                                            <button className="text-green-500 cursor-pointer">
                                                Nový článek
                                            </button>
                                            <AddIcon />
                                        </div>

                                        <div className="flex p-2 justify-center items-center space-x-1 cursor-pointer hover:bg-red-600 transition rounded" onClick={handleLogout}>
                                            <button className="text-red-800 cursor-pointer">
                                                Odhlásit se
                                            </button>
                                            <LogoutIcon />
                                        </div>
                                    </div>
                                )}
                            </div>
                        ) : (
                            <Link to="/login">
                                <button className="bg-green-900 hover:bg-green-800 text-white px-4 py-2 rounded transition">Login</button>
                            </Link>
                        )}
                    </div>

                    {/* Mobile menu toggle */}
                    <div className="block md:hidden">
                        <IconButton
                            color="inherit"
                            aria-label="open drawer"
                            onClick={toggleMobileMenu}
                        >
                            <MenuIcon />
                        </IconButton>
                    </div>
                </div>
            </Toolbar>

            {/* Mobile Menu */}
            {isMobileMenuOpen && (
                <div className="block md:hidden bg-green-950 mx-8 p-4">
                    <div className="flex flex-col gap-4">
                        <a onClick={() => { navigate('/about'); toggleMobileMenu(); }} className="hover:underline text-white cursor-pointer">O projektu</a>
                        <Picker />

                        <div className="py-2">
                            <input type="text" placeholder="Hledat článek..." className="w-full px-2 py-1 rounded outline-none text-white" />
                        </div>

                        {/* User Profile Info - Always expanded in mobile menu */}
                        {user ? (
                            <div className="bg-green-950 p-4 w-80">
                                <div className="flex flex-col items-center mb-3">
                                    {user?.profilePicture && (user.profilePicture.trim() !== import.meta.env.VITE_PROFILE_PICTURES_URL) ? (
                                        <div className="w-8 h-8 mr-3 overflow-hidden rounded-full border shadow-lg">
                                            <img
                                                src={user.profilePicture}
                                                alt="Profilový obrázek"
                                                className="object-cover w-full h-full"
                                            />
                                        </div>
                                    ) : (
                                        <Avatar className="mr-3">
                                            {user?.username.charAt(0)}
                                        </Avatar>
                                    )}
                                    <div className="">
                                        <p className="pt-2 font-semibold text-white">{user?.username}</p>
                                        <p className="text-sm text-gray-300">{user?.email}</p>
                                    </div>
                                </div>
                                <Divider className="bg-orange-50" />

                                <div className="flex my-2 mx-8 cursor-pointer items-center justify-center space-x-2 hover:bg-yellow-300 rounded p-2 transition">
                                    <PersonIcon sx={{ color: 'white' }} />
                                    <button className="text-white" onClick={() => { navigate('/profile'); toggleMobileMenu(); }}>
                                        Profil
                                    </button>
                                </div>
                                {(user?.role === Role.SPRAVCE) && (
                                    <div className="flex my-2 mx-8 items-center justify-center space-x-2 hover:bg-yellow-600 rounded p-2 transition" onClick={() => { navigate('/admin'); setShowProfileMenu(false); }}>
                                        <AdminPanelSettingsIcon />
                                        <button className="text-white" >
                                            Admin panel
                                        </button>
                                    </div>)}

                                <div className="flex my-2 mx-8 items-center justify-center space-x-2 hover:bg-green-600 rounded p-2 transition">
                                    <AddIcon sx={{ color: 'white' }} />
                                    <button className="text-white" onClick={() => { navigate('/editor'); toggleMobileMenu(); }}>
                                        Nový článek
                                    </button>
                                </div>

                                <div className="flex my-2 mx-8 items-center justify-center space-x-2 hover:bg-red-600 rounded p-2 transition">
                                    <LogoutIcon sx={{ color: 'white' }} />
                                    <button className="text-white" onClick={() => { handleLogout(); toggleMobileMenu(); }}>
                                        Odhlásit se
                                    </button>
                                </div>
                            </div>
                        ) : (
                            <div className="flex justify-center py-2">
                                <Link to="/login" onClick={toggleMobileMenu}>
                                    <button className="bg-green-700 hover:bg-green-600 text-white px-6 py-2 rounded transition w-full">
                                        Login
                                    </button>
                                </Link>
                            </div>
                        )}
                    </div>
                </div>
            )}
        </AppBar>
    );
};

export default Navbar;