import React, { useState, useRef, useEffect } from 'react';
import { Link, NavLink, useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { useProfileActions } from '../../contexts/ProfileActionsContext';
import { getFileUrl } from '../../services/pocketbaseService';
import { FaUserCircle, FaSignOutAlt, FaEdit, FaBars, FaTimes, FaTachometerAlt, FaBook, FaTrophy, FaCog, FaHeadset, FaHome, FaUser, FaBell } from 'react-icons/fa'; // Import FaBook, FaTrophy, FaCog, and FaHeadset
import { FiSearch } from 'react-icons/fi';
import SearchBar from '../ui/SearchBar';
import AlphaBadge from '../ui/AlphaBadge';
import localLogo from '/logo.png';
import { canManageSystem } from '../../utils/permissions';
import Dock from '../reactbits/Components/Dock/Dock';
import '../reactbits/Components/Dock/Dock.css';
import { AnimatePresence, motion } from 'framer-motion';
import { pb } from '../../services/pocketbaseService';
import { formatDistanceToNow } from 'date-fns';
import { ru } from 'date-fns/locale';

const Header = () => {
  const { user, userProfile, logout } = useAuth();
  const profileActions = useProfileActions();
  const navigate = useNavigate();
  const location = useLocation();
  const [isProfileMenuOpen, setIsProfileMenuOpen] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenu] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [logoSrc, setLogoSrc] = useState(localLogo);
  const profileMenuRef = useRef(null);
  const mobileMenuRef = useRef(null);
  const searchContainerRef = useRef(null); // Ref for the search dropdown container
  const [isNotificationsOpen, setIsNotificationsOpen] = useState(false);
  const notificationsRef = useRef(null);
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [logoError, setLogoError] = useState(false);

  // Эффект для проверки доступности локального логотипа при монтировании
  useEffect(() => {
    const img = new Image();
    img.onload = () => setLogoSrc(localLogo); // Если локальный загрузился, используем его
    img.onerror = () => setLogoSrc('https://campfiregg.ru/logo.png'); // Если локальный не загрузился, пробуем внешний
    img.src = localLogo;
  }, []); // Запускаем только один раз при монтировании

  const handleLogoError = () => {
    setLogoError(true);
  };

  const toggleProfileMenu = () => {
    setIsProfileMenuOpen(!isProfileMenuOpen);
    setIsMobileMenu(false); // Close mobile menu if profile opens
    setIsSearchOpen(false); // Close search if profile opens
  };
  
  const toggleNotificationMenu = () => {
    setIsNotificationsOpen(!isNotificationsOpen);
    setIsProfileMenuOpen(false);
    setIsMobileMenu(false);
    setIsSearchOpen(false);
  };

  const toggleMobileMenu = () => {
    setIsMobileMenu(!isMobileMenuOpen);
    setIsProfileMenuOpen(false); // Close profile menu if mobile opens
    setIsSearchOpen(false); // Close search if mobile opens
  };

  const toggleSearch = () => {
    setIsSearchOpen(!isSearchOpen);
    setIsProfileMenuOpen(false); // Close other menus
    setIsMobileMenu(false); // Close other menus
  };

  const closeMenus = () => {
    setIsProfileMenuOpen(false);
    setIsMobileMenu(false);
    // Keep search open if it was opened via its own button, close only if clicking outside
  };

  const closeSearch = () => {
      setIsSearchOpen(false);
  };

  // Close menus/search when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(event.target)) {
        setIsProfileMenuOpen(false);
      }
      if (mobileMenuRef.current && !mobileMenuRef.current.contains(event.target)) {
         setIsMobileMenu(false);
      }
       // Close search only if clicking outside the search container itself
       if (searchContainerRef.current && !searchContainerRef.current.contains(event.target)) {
           // Check if the click was NOT on the search toggle button
           const searchButton = document.getElementById('search-toggle-button');
           if (searchButton && searchButton !== event.target && !searchButton.contains(event.target)) {
               setIsSearchOpen(false);
           }
       }
    };

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

  // Handle Edit Profile click from Header
  const handleEditProfile = () => {
    if (userProfile) {
      navigate(`/profile/${userProfile.username}`, { state: { shouldOpenEditModal: true } });
    }
  };

  const canAccessAdmin = canManageSystem(user);

  const mainItems = [
    {
      icon: <FaHome className="w-5 h-5 text-campfire-light" />,
      label: 'Главная',
      onClick: () => navigate('/'),
      className: location.pathname === '/' ? 'bg-campfire-amber/20' : ''
    },
    {
      icon: <FaBook className="w-5 h-5 text-campfire-light" />,
      label: 'Каталог',
      onClick: () => navigate('/catalog'),
      className: location.pathname === '/catalog' ? 'bg-campfire-amber/20' : ''
    },
    {
      icon: <FaTrophy className="w-5 h-5 text-campfire-light" />,
      label: 'Рейтинги',
      onClick: () => navigate('/rating'),
      className: location.pathname === '/rating' ? 'bg-campfire-amber/20' : ''
    },
    {
      icon: <FiSearch className="w-5 h-5 text-campfire-light" />,
      label: 'Поиск',
      onClick: toggleSearch,
      className: isSearchOpen ? 'bg-campfire-amber/20' : ''
    }
  ];

  const profileItems = user ? [
    {
      icon: (
        <div className="flex items-center gap-2 px-2">
          <img
            src={userProfile?.profile_picture ? getFileUrl(userProfile, 'profile_picture') : 'https://pocketbase.campfiregg.ru/api/files/_pb_users_auth_/g520s25pzm0t6e1/photo_2025_05_17_22_26_21_g2bi9umsuu.jpg'}
            alt={userProfile?.username || 'User'}
            className="w-6 h-6 rounded-full object-cover border border-campfire-ash/30"
          />
          <span className="text-[10px] text-campfire-light truncate max-w-[60px]">{userProfile?.login || 'Профиль'}</span>
        </div>
      ),
      onClick: () => navigate(`/profile/${userProfile?.login}`),
      className: location.pathname.startsWith('/profile') ? 'bg-campfire-amber/20' : '',
      showLabel: false,
      isRectangular: true
    },
    {
      icon: <FaBell className={`w-5 h-5 ${isNotificationsOpen ? 'text-campfire-amber' : 'text-campfire-light'}`} />,
      onClick: toggleNotificationMenu,
      className: isNotificationsOpen ? 'bg-campfire-amber/20' : '',
      showLabel: false
    },
    {
      icon: <FaBars className="w-5 h-5 text-campfire-light" />,
      onClick: toggleProfileMenu,
      className: isProfileMenuOpen ? 'bg-campfire-amber/20' : '',
      showLabel: false
    }
  ] : [
    {
      icon: <FaUser className="w-5 h-5 text-campfire-light" />,
      onClick: () => navigate('/auth/login'),
      className: location.pathname === '/auth/login' ? 'bg-campfire-amber/20' : '',
      showLabel: false
    }
  ];

  // Закрываем меню при изменении маршрута
  useEffect(() => {
    setIsProfileMenuOpen(false);
    setIsNotificationsOpen(false);
  }, [location]);

  // Обработка клика вне меню
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(event.target)) {
        setIsProfileMenuOpen(false);
      }
      if (notificationsRef.current && !notificationsRef.current.contains(event.target)) {
        setIsNotificationsOpen(false);
      }
    };

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

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

  const loadNotifications = async () => {
    try {
      const records = await pb.collection('notifications').getList(1, 10, {
        filter: `user_id = "${user.id}"`,
        sort: '-created'
      });
      setNotifications(records.items);
      setUnreadCount(records.items.filter(n => !n.is_read).length);
    } catch (error) {
      console.error('Error loading notifications:', error);
    }
  };

  const markAsRead = async (notificationId) => {
    try {
      await pb.collection('notifications').update(notificationId, {
        is_read: true
      });
      setNotifications(notifications.map(n => 
        n.id === notificationId ? { ...n, is_read: true } : n
      ));
      setUnreadCount(prev => Math.max(0, prev - 1));
    } catch (error) {
      console.error('Error marking notification as read:', error);
    }
  };

  // Прокрутка страницы вверх при изменении маршрута
  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  }, [location.pathname]);

  const handleLogout = () => {
    logout();
    navigate('/auth');
  };

  return (
		<>
      <header className="fixed top-2 left-0 right-0 z-50">
        <div className="bg-campfire-charcoal/80 backdrop-blur-md border-b border-campfire-ash/20 rounded-t-lg">
          <div className="container-custom flex items-center justify-between h-16 px-4">
            {/* Logo */}
            <Link to="/" className="flex items-center space-x-2">
          <img
                src={logoSrc}
                alt="CampFire мнение"
                className="h-12"
                onError={handleLogoError}
              />
        </Link>

            {/* Main Dock Navigation */}
            <div className="hidden md:flex flex-1 justify-center">
              <div className="flex items-center gap-4">
                <Dock
                  items={mainItems}
                  className="bg-campfire-charcoal/50 backdrop-blur-sm"
                  distance={120}
                  panelHeight={50}
                  baseItemSize={32}
                  dockHeight={30}
                  magnification={40}
                  spring={{ mass: 0.2, stiffness: 200, damping: 15 }}
                />

                {/* Search Dock */}
                <AnimatePresence>
                  {isSearchOpen && (
                    <motion.div
                      initial={{ opacity: 0, width: 0 }}
                      animate={{ opacity: 1, width: '300px' }}
                      exit={{ opacity: 0, width: 0 }}
                      transition={{ duration: 0.2 }}
                      className="rounded-md overflow-hidden"
                    >
                      <div className="px-4 py-2">
                        <SearchBar onClose={closeSearch} />
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            </div>

            {/* Profile Dock */}
            <div className="hidden md:flex relative">
              <Dock
                items={profileItems}
                className="bg-campfire-charcoal/50 backdrop-blur-sm"
                distance={120}
                panelHeight={50}
                baseItemSize={32}
                dockHeight={30}
                magnification={40}
                spring={{ mass: 0.2, stiffness: 200, damping: 15 }}
              />

              {/* Notifications Dropdown */}
              <AnimatePresence>
                {isNotificationsOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2 }}
                    ref={notificationsRef}
                    className="absolute right-0 top-full mt-2 w-80 bg-campfire-charcoal rounded-md shadow-lg py-1 z-50 border border-campfire-ash/30"
                  >
                    <div className="p-4">
                      <h3 className="text-lg font-semibold text-campfire-light mb-4">Уведомления</h3>
                      {notifications.length === 0 ? (
                        <p className="text-campfire-light/70 text-center py-4">Нет новых уведомлений</p>
                      ) : (
                        <div className="space-y-2 max-h-96 overflow-y-auto">
                          {notifications.map(notification => (
                            <div
                              key={notification.id}
                              className={`p-3 rounded-md cursor-pointer transition-colors ${
                                notification.is_read 
                                  ? 'bg-campfire-ash/10 hover:bg-campfire-ash/20' 
                                  : 'bg-campfire-amber/10 hover:bg-campfire-amber/20'
                              }`}
                              onClick={() => markAsRead(notification.id)}
                            >
                              <div className="flex justify-between items-start">
                                <div>
                                  <h4 className="font-medium text-campfire-light">{notification.title}</h4>
                                  <p className="text-sm text-campfire-light/70">{notification.message}</p>
                                </div>
                                <span className="text-xs text-campfire-light/50">
                                  {formatDistanceToNow(new Date(notification.created), { 
                                    addSuffix: true,
                                    locale: ru 
                                  })}
                                </span>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>

              {/* Profile Dropdown Menu */}
              <AnimatePresence>
                {isProfileMenuOpen && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2 }}
                    ref={profileMenuRef}
                    className="absolute right-0 top-full mt-2 w-48 bg-campfire-charcoal rounded-md shadow-lg py-1 z-50 border border-campfire-ash/30"
                  >
                    <Link
                      to={`/profile/${userProfile?.login}`}
                      onClick={closeMenus}
                      className="block px-4 py-2 text-sm text-campfire-light hover:bg-campfire-ash/20 flex items-center space-x-2"
                    >
                      <FaUserCircle />
                      <span>Мой профиль</span>
                    </Link>
                    {canAccessAdmin && (
                       <Link
                           to="/admin"
                           onClick={closeMenus}
                           className="block px-4 py-2 text-sm text-campfire-light hover:bg-campfire-ash/20 flex items-center space-x-2"
                       >
                           <FaTachometerAlt />
                           <span>Админ панель</span>
                       </Link>
                   )}
                   {userProfile && (
                       <button
                           onClick={handleEditProfile}
                           className="block w-full text-left px-4 py-2 text-sm text-campfire-light hover:bg-campfire-ash/20 flex items-center space-x-2"
                       >
                           <FaEdit />
                           <span>Редактировать профиль</span>
                       </button>
                   )}
                    {user && (
                      <>
                        <Link
                          to="/support"
                          className="block px-4 py-2 text-sm text-campfire-light hover:bg-campfire-ash/20 flex items-center space-x-2"
                        >
                          <FaHeadset />
                          <span>Поддержка</span>
                        </Link>
                  <button
                    onClick={handleLogout}
                    className="block w-full text-left px-4 py-2 text-sm text-campfire-light hover:bg-campfire-ash/20 flex items-center space-x-2"
                  >
                    <FaSignOutAlt />
                    <span>Выйти</span>
                  </button>
                      </>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>
            </div>

          {/* Mobile Menu Button */}
          <div className="md:hidden">
            <button onClick={toggleMobileMenu} className="text-campfire-light focus:outline-none">
              {isMobileMenuOpen ? <FaTimes size={24} /> : <FaBars size={24} />}
            </button>
          </div>
        </div>
      </div>

        {/* Search Results Dropdown */}
        <AnimatePresence>
          {isSearchOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.2 }}
              className="bg-campfire-charcoal shadow-lg border-b border-campfire-ash/30 overflow-hidden"
            >
              <div className="container-custom mx-auto px-4 py-4">
                {/* Здесь будет компонент с результатами поиска */}
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Mobile Menu */}
        <AnimatePresence>
          {isMobileMenuOpen && (
            <motion.nav
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.2 }}
              ref={mobileMenuRef}
              className="md:hidden bg-campfire-charcoal border-t border-campfire-ash/20"
                 >
              <div className="container-custom py-4 px-4">
            <NavLink
              to="/catalog"
              onClick={closeMenus}
              className={({ isActive }) =>
                    `block px-4 py-2 hover:bg-campfire-ash/20 transition-colors ${isActive ? 'text-campfire-amber' : 'text-campfire-light'} flex items-center space-x-2`
              }
            >
                  <FaBook size={20} />
                  <span>Каталог</span>
            </NavLink>
             <NavLink
              to="/rating"
              onClick={closeMenus}
              className={({ isActive }) =>
                    `block px-4 py-2 hover:bg-campfire-ash/20 transition-colors ${isActive ? 'text-campfire-amber' : 'text-campfire-light'} flex items-center space-x-2`
              }
            >
                  <FaTrophy size={20} />
                  <span>Рейтинги</span>
            </NavLink>
             {user && (
                 <button
                     onClick={handleLogout}
                     className="block w-full text-left px-4 py-2 text-campfire-light hover:bg-campfire-ash/20 flex items-center space-x-2"
                 >
                     <FaSignOutAlt />
                     <span>Выйти</span>
                 </button>
             )}
          </div>
            </motion.nav>
      )}
        </AnimatePresence>
    </header>

      {/* Мобильный Dock */}
      <motion.div
        initial={{ y: 100, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        exit={{ y: 100, opacity: 0 }}
        transition={{ duration: 0.3 }}
        className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-campfire-charcoal/80 backdrop-blur-md border-t border-campfire-ash/20"
      >
        <div className="container-custom py-2">
          <div className="flex justify-between items-center">
            <Dock
              items={mainItems}
              className="bg-campfire-charcoal/50 backdrop-blur-sm rounded-md"
              distance={120}
              panelHeight={50}
              baseItemSize={32}
              dockHeight={30}
              magnification={40}
              spring={{ mass: 0.2, stiffness: 200, damping: 15 }}
            />
            <Dock
              items={profileItems}
              className="bg-campfire-charcoal/50 backdrop-blur-sm rounded-md"
              distance={120}
              panelHeight={50}
              baseItemSize={32}
              dockHeight={30}
              magnification={40}
              spring={{ mass: 0.2, stiffness: 200, damping: 15 }}
            />
          </div>
        </div>
      </motion.div>

      {/* Alpha Badge */}
      <AlphaBadge />
			</>
  );
};

export default Header;