import { useState, useEffect } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { 
  LayoutDashboard, 
  Package, 
  Tag, 
  ShoppingBag, 
  Users, 
  FileText, 
  Settings, 
  LogOut,
  Menu,
  X,
  Home,
  Grid
} from 'lucide-react';
import Image from 'next/image';
import authService from '../../services/auth';
import { userService } from '../../services/users';

// Компонент элемента бокового меню
interface SidebarItemProps {
  icon: React.ReactNode;
  text: string;
  href: string;
  active: boolean;
}

const SidebarItem = ({ icon, text, href, active }: SidebarItemProps) => {
  return (
    <Link 
      href={href}
      className={`flex items-center px-4 py-3 rounded-lg ${active ? 'bg-indigo-50 text-indigo-600' : 'text-gray-600 hover:bg-gray-50'}`}
    >
      <span className={`${active ? 'text-indigo-600' : 'text-gray-500'}`}>{icon}</span>
      <span className={`ml-3 font-medium ${active ? 'text-indigo-600' : 'text-gray-700'}`}>{text}</span>
    </Link>
  );
};

interface AdminLayoutProps {
  children: React.ReactNode;
  title: string;
}

export default function AdminLayout({ children, title }: AdminLayoutProps) {
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [loading, setLoading] = useState(true);

  // Проверка прав администратора при загрузке компонента
  useEffect(() => {
    const checkAdminAccess = async () => {
      try {
        if (!authService.isAuthenticated()) {
          // Если пользователь не авторизован, перенаправляем на страницу входа
          router.push('/login');
          return;
        }
        
        const user = await userService.getCurrentUser();
        
        if (!user) {
          // Если не удалось получить данные пользователя, перенаправляем на страницу входа
          router.push('/login');
          return;
        }
        
        if (!user.is_admin) {
          // Если пользователь не администратор, перенаправляем на главную страницу
          router.push('/');
          return;
        }
        
        setLoading(false);
      } catch (error) {
        console.error('Ошибка при проверке прав администратора:', error);
        router.push('/login');
      }
    };
    
    checkAdminAccess();
  }, [router]);

  // Определяем активный пункт меню на основе текущего пути
  const currentPath = router.pathname;
  
  const menuItems = [
    {
      icon: <Home className="w-5 h-5" />,
      text: 'Панель управления',
      href: '/admin',
      active: currentPath === '/admin'
    },
    {
      icon: <Package className="w-5 h-5" />,
      text: 'Товары',
      href: '/admin/products',
      active: currentPath.startsWith('/admin/products')
    },
    {
      icon: <ShoppingBag className="w-5 h-5" />,
      text: 'Категории',
      href: '/admin/categories',
      active: currentPath.startsWith('/admin/categories')
    },
    {
      icon: <ShoppingBag className="w-5 h-5" />,
      text: 'Заказы',
      href: '/admin/orders',
      active: currentPath.startsWith('/admin/orders')
    },
    {
      icon: <Users className="w-5 h-5" />,
      text: 'Пользователи',
      href: '/admin/users',
      active: currentPath.startsWith('/admin/users')
    },
    {
      icon: <Settings className="w-5 h-5" />,
      text: 'Настройки',
      href: '/admin/settings',
      active: currentPath.startsWith('/admin/settings')
    },
    {
      icon: <Grid className="w-5 h-5" />,
      text: 'Коллекции',
      href: '/admin/collections',
      active: currentPath.startsWith('/admin/collections')
    }
  ];

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-100">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100">
      <Head>
        <title>{title} | Админ-панель</title>
      </Head>

      {/* Мобильная навигация */}
      <div className="lg:hidden">
        <div className="fixed top-0 left-0 right-0 z-30 bg-white shadow-sm px-4 py-2 flex items-center justify-between">
          <button 
            onClick={() => setSidebarOpen(true)}
            className="p-2 rounded-md text-gray-600 hover:bg-gray-100"
          >
            <Menu className="w-6 h-6" />
          </button>
          <div className="flex items-center">
            <div className="relative h-8 w-24">
              <Image
                src="/logo.png"
                alt="Brand Logo"
                fill
                className="object-contain"
                priority
              />
            </div>
            <span className="ml-2 font-semibold text-gray-800">Админ</span>
          </div>
        </div>
      </div>

      {/* Боковое меню (мобильное) */}
      {sidebarOpen && (
        <div className="fixed inset-0 z-40 lg:hidden">
          <div className="fixed inset-0 bg-gray-600 bg-opacity-75" onClick={() => setSidebarOpen(false)}></div>
          <div className="fixed inset-y-0 left-0 flex flex-col w-64 max-w-xs bg-white shadow-xl">
            <div className="h-16 flex items-center justify-between px-4 border-b border-gray-200">
              <div className="flex items-center">
                <div className="relative h-8 w-24">
                  <Image
                    src="/logo.png"
                    alt="Brand Logo"
                    fill
                    className="object-contain"
                    priority
                  />
                </div>
                <span className="ml-2 font-semibold text-gray-800">Админ</span>
              </div>
              <button 
                onClick={() => setSidebarOpen(false)}
                className="p-2 rounded-md text-gray-600 hover:bg-gray-100"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-4">
              <nav className="space-y-1">
                {menuItems.map((item, index) => (
                  <SidebarItem 
                    key={index}
                    icon={item.icon}
                    text={item.text}
                    href={item.href}
                    active={item.active}
                  />
                ))}
              </nav>
            </div>
            <div className="p-4 border-t border-gray-200">
              <Link 
                href="/"
                className="flex items-center px-4 py-3 text-indigo-600 rounded-lg hover:bg-indigo-50 w-full mb-3"
              >
                <Home className="w-5 h-5" />
                <span className="ml-3 font-medium">На главную</span>
              </Link>
              <button 
                onClick={() => {
                  authService.logout();
                  router.push('/login');
                }}
                className="flex items-center px-4 py-3 text-red-600 rounded-lg hover:bg-red-50 w-full"
              >
                <LogOut className="w-5 h-5" />
                <span className="ml-3 font-medium">Выйти</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Боковое меню (десктоп) */}
      <div className="hidden lg:fixed lg:inset-y-0 lg:flex lg:flex-col lg:w-64 lg:bg-white lg:border-r lg:border-gray-200">
        <div className="h-16 flex items-center px-6 border-b border-gray-200">
          <div className="flex items-center">
            <div className="relative h-8 w-24">
              <Image
                src="/logo.png"
                alt="Brand Logo"
                fill
                className="object-contain"
                priority
              />
            </div>
            <span className="ml-2 font-semibold text-gray-800">Админ</span>
          </div>
        </div>
        <div className="flex-1 overflow-y-auto p-4">
          <nav className="space-y-1">
            {menuItems.map((item, index) => (
              <SidebarItem 
                key={index}
                icon={item.icon}
                text={item.text}
                href={item.href}
                active={item.active}
              />
            ))}
          </nav>
        </div>
        <div className="p-4 border-t border-gray-200">
          <Link 
            href="/"
            className="flex items-center px-4 py-3 text-indigo-600 rounded-lg hover:bg-indigo-50 w-full mb-3"
          >
            <Home className="w-5 h-5" />
            <span className="ml-3 font-medium">На главную</span>
          </Link>
          <button 
            onClick={() => {
              authService.logout();
              router.push('/login');
            }}
            className="flex items-center px-4 py-3 text-red-600 rounded-lg hover:bg-red-50 w-full"
          >
            <LogOut className="w-5 h-5" />
            <span className="ml-3 font-medium">Выйти</span>
          </button>
        </div>
      </div>

      {/* Основной контент */}
      <div className="lg:pl-64 flex flex-col min-h-screen">
        <header className="hidden lg:flex h-16 bg-white shadow-sm px-6 items-center">
          <h1 className="text-2xl font-semibold text-gray-800">{title}</h1>
        </header>
        <main className="flex-1 p-6 pt-20 lg:pt-6">
          {children}
        </main>
        <footer className="bg-white border-t border-gray-200 p-4 text-center text-sm text-gray-600">
          &copy; {new Date().getFullYear()} Dressed for Success. Все права защищены.
        </footer>
      </div>
    </div>
  );
} 