import React, { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { 
  LayoutDashboard, 
  Users, 
  Settings, 
  FileText, 
  BarChart3,
  Globe,
  ChevronLeft,
  ChevronRight,
  LogIn,
  LogOut,
  Menu,
  X
} from 'lucide-react';
import useAuthStore from '../../store/useAuthStore';

interface SidebarAdminProps {
  isCollapsed?: boolean;
  onToggle?: () => void;
}

const SidebarAdmin: React.FC<SidebarAdminProps> = ({ 
  isCollapsed: controlledCollapsed,
  onToggle 
}) => {
  const [internalCollapsed, setInternalCollapsed] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [isMobileOpen, setIsMobileOpen] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const { logout } = useAuthStore();
  
  const handleLogout = async () => {
    try {
      await logout();
      navigate('/');
      if (isMobile) {
        setIsMobileOpen(false);
      }
    } catch (error) {
      console.error('Logout error:', error);
    }
  };
  
  
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 1024); 
      if (window.innerWidth >= 1024) {
        setIsMobileOpen(false);
      }
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);
  
  const isCollapsed = 
    controlledCollapsed !== undefined 
      ? controlledCollapsed 
      : internalCollapsed;
  
  const handleToggle = () => {
    if (onToggle) {
      onToggle();
    } else {
      setInternalCollapsed(!internalCollapsed);
    }
  };

  const handleMobileToggle = () => {
    setIsMobileOpen(!isMobileOpen);
  };

  const handleLinkClick = () => {
    if (isMobile) {
      setIsMobileOpen(false);
    }
  };

  const menuItems = [
    { 
      path: '/admin/dashboard', 
      icon: LayoutDashboard, 
      label: 'Dashboard' 
    },
    { 
      path: '/admin/users', 
      icon: Users, 
      label: 'Users' 
    },
    { 
      path: '/admin/business', 
      icon: FileText, 
      label: 'Business' 
    },
    { 
      path: '/admin/reception', 
      icon: LogIn, 
      label: 'Reception' 
    },
    { 
      path: '/admin/page-content', 
      icon: Globe, 
      label: 'Page Content' 
    },
    { 
      path: '/admin/analytics', 
      icon: BarChart3, 
      label: 'Analytics' 
    },
    { 
      path: '/admin/settings', 
      icon: Settings, 
      label: 'Settings' 
    },
  ];

  const isActive = (path: string) => {
    
    if (location.pathname === path) return true;
    
    if (path === '/admin/settings' || path === '/admin/analytics' || path === '/admin/business' || path === '/admin/reception' || path === '/admin/page-content') {
      return location.pathname === path;
    }
    
    if (path === '/admin/reception') {
      return location.pathname === path || location.pathname.startsWith(`${path}/`);
    }
    
    return location.pathname.startsWith(`${path}/`);
  };

  return (
    <>
      {}
      {isMobile && (
        <button
          onClick={handleMobileToggle}
          className="fixed top-4 left-4 z-50 lg:hidden p-3 bg-gradient-to-r from-slate-900 to-slate-800 text-white rounded-xl shadow-2xl border border-slate-700 hover:from-slate-800 hover:to-slate-700 transition-all duration-200"
          aria-label="Toggle menu"
        >
          {isMobileOpen ? (
            <X className="w-6 h-6" />
          ) : (
            <Menu className="w-6 h-6" />
          )}
        </button>
      )}

      {}
      {isMobile && isMobileOpen && (
        <div
          className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 lg:hidden"
          onClick={handleMobileToggle}
        />
      )}

      {}
      <aside 
        className={`
          fixed lg:static inset-y-0 left-0 z-40
          bg-gradient-to-b from-slate-900 via-slate-800 to-slate-900
          text-white shadow-2xl
          transition-all duration-300 ease-in-out flex flex-col
          ${isMobile 
            ? (isMobileOpen ? 'translate-x-0' : '-translate-x-full')
            : ''
          }
          ${!isMobile && (isCollapsed ? 'w-20' : 'w-72')}
          ${isMobile ? 'w-72' : ''}
          border-r border-slate-700/50
        `}
      >
        {}
        <div className="p-6 border-b border-slate-700/50 flex items-center justify-between bg-gradient-to-r from-slate-800/50 to-slate-900/50 backdrop-blur-sm">
          {!isCollapsed && (
            <div className="flex items-center gap-3">
              <div className="h-1 w-12 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
              <h2 className="text-xl font-bold bg-gradient-to-r from-amber-100 to-amber-200 bg-clip-text text-transparent">
                Admin Panel
              </h2>
            </div>
          )}
          {isCollapsed && !isMobile && (
            <div className="w-full flex justify-center">
              <div className="h-8 w-8 bg-gradient-to-br from-amber-400 to-amber-600 rounded-xl flex items-center justify-center shadow-lg">
                <span className="text-slate-900 font-bold text-sm">A</span>
              </div>
            </div>
          )}
          {!isMobile && (
            <button
              onClick={handleToggle}
              className="p-2.5 rounded-xl bg-slate-800/50 hover:bg-slate-700/50 border border-slate-700/50 hover:border-amber-500/50 transition-all duration-200 ml-auto shadow-lg hover:shadow-xl"
              aria-label="Toggle sidebar"
            >
              {isCollapsed ? (
                <ChevronRight className="w-5 h-5 text-amber-200" />
              ) : (
                <ChevronLeft className="w-5 h-5 text-amber-200" />
              )}
            </button>
          )}
        </div>

        {}
        <nav className="flex-1 overflow-y-auto py-4 px-3 custom-scrollbar">
          <ul className="space-y-2">
            {menuItems.map((item) => {
              const Icon = item.icon;
              const active = isActive(item.path);
              
              return (
                <li key={item.path}>
                  <Link
                    to={item.path}
                    onClick={handleLinkClick}
                    className={`
                      flex items-center 
                      space-x-3 px-4 py-3.5 rounded-xl 
                      transition-all duration-200 group relative
                      ${active 
                        ? 'bg-gradient-to-r from-amber-500/20 to-amber-600/20 text-amber-100 shadow-lg border border-amber-500/30' 
                        : 'text-slate-300 hover:bg-slate-800/50 hover:text-amber-100 border border-transparent hover:border-slate-700/50'
                      }
                      ${isCollapsed && !isMobile ? 'justify-center' : ''}
                    `}
                    title={isCollapsed && !isMobile ? item.label : undefined}
                  >
                    {active && (
                      <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-gradient-to-b from-amber-400 to-amber-600 rounded-r-full"></div>
                    )}
                    <Icon className={`
                      flex-shrink-0 transition-transform duration-200
                      ${active ? 'text-amber-400' : 'text-slate-400 group-hover:text-amber-400'}
                      ${isCollapsed && !isMobile ? 'w-6 h-6' : 'w-5 h-5'}
                    `} />
                    {(!isCollapsed || isMobile) && (
                      <span className={`
                        font-semibold transition-all duration-200
                        ${active ? 'text-amber-100' : 'group-hover:text-amber-100'}
                      `}>
                        {item.label}
                      </span>
                    )}
                    {active && !isCollapsed && (
                      <div className="ml-auto w-2 h-2 bg-amber-400 rounded-full animate-pulse"></div>
                    )}
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        {}
        <div className="p-4 border-t border-slate-700/50">
          <button
            onClick={handleLogout}
            className={`
              w-full flex items-center 
              space-x-3 px-4 py-3.5 rounded-xl 
              transition-all duration-200 group relative
              text-slate-300 hover:bg-gradient-to-r hover:from-rose-600/20 hover:to-rose-700/20 
              hover:text-rose-100 border border-transparent hover:border-rose-500/30
              ${isCollapsed && !isMobile ? 'justify-center' : ''}
            `}
            title={isCollapsed && !isMobile ? 'Logout' : undefined}
          >
            <LogOut className={`
              flex-shrink-0 transition-transform duration-200
              text-slate-400 group-hover:text-rose-400 group-hover:rotate-12
              ${isCollapsed && !isMobile ? 'w-6 h-6' : 'w-5 h-5'}
            `} />
            {(!isCollapsed || isMobile) && (
              <span className="font-semibold transition-all duration-200 group-hover:text-rose-100">
                Logout
              </span>
            )}
          </button>
        </div>

        {}
        <div className="p-4 border-t border-slate-700/50 bg-gradient-to-r from-slate-800/50 to-slate-900/50 backdrop-blur-sm">
          {(!isCollapsed || isMobile) ? (
            <div className="text-xs text-slate-400 text-center space-y-1">
              <p className="font-semibold text-amber-200/80">Admin Dashboard</p>
              <p className="text-slate-500">
                © {new Date().getFullYear()} Luxury Hotel
              </p>
            </div>
          ) : (
            <div className="flex justify-center">
              <div className="w-3 h-3 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-full shadow-lg animate-pulse"></div>
            </div>
          )}
        </div>
      </aside>
    </>
  );
};

export default SidebarAdmin;
