// components/admin/AdminLayout.jsx
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';

export default function AdminLayout({ children }) {
  const router = useRouter();
  const [user, setUser] = useState(null);
  const [sidebarOpen, setSidebarOpen] = useState(true);

  useEffect(() => {
    checkAuth();
  }, []);

  const checkAuth = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        router.push('/admin/login');
        return;
      }

      const response = await fetch('/api/auth/me', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setUser(data.user);
        
        if (!['Admin', 'Staff'].includes(data.user.role)) {
          router.push('/');
        }
      } else {
        router.push('/admin/login');
      }
    } catch (error) {
      router.push('/admin/login');
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    router.push('/admin/login');
  };

  if (!user) {
    return <div className="flex items-center justify-center min-h-screen">Loading...</div>;
  }

  return (
    <div className="flex h-screen bg-gray-100">
      {/* Sidebar */}
      <aside className={`bg-gray-900 text-white transition-all duration-300 ${sidebarOpen ? 'w-64' : 'w-20'}`}>
        <div className="p-4 flex items-center justify-between border-b border-gray-700">
          {sidebarOpen && <h1 className="text-xl font-bold">Admin Panel</h1>}
          <button 
            onClick={() => setSidebarOpen(!sidebarOpen)}
            className="p-2 hover:bg-gray-800 rounded"
          >
            ☰
          </button>
        </div>

        <nav className="mt-4">
          <NavItem href="/admin" icon="🏠" label="Dashboard" open={sidebarOpen} />
          
          <NavSection title="Matrimonial" open={sidebarOpen} />
          <NavItem href="/admin/matrimonial/profiles" icon="👥" label="Profiles" open={sidebarOpen} />
          
          <NavSection title="Classifieds" open={sidebarOpen} />
          <NavItem href="/admin/classifieds/ads" icon="📢" label="Ads" open={sidebarOpen} />
          <NavItem href="/admin/classifieds/categories" icon="📁" label="Categories" open={sidebarOpen} />
          
          <NavSection title="Events" open={sidebarOpen} />
          <NavItem href="/admin/events/listings" icon="🎉" label="Listings" open={sidebarOpen} />
          <NavItem href="/admin/events/categories" icon="📁" label="Categories" open={sidebarOpen} />
          
          <NavSection title="System" open={sidebarOpen} />
          <NavItem href="/admin/users" icon="👤" label="Users" open={sidebarOpen} />
          <NavItem href="/admin/roles" icon="🔐" label="Roles" open={sidebarOpen} />
          <NavItem href="/admin/seo" icon="🔍" label="SEO Settings" open={sidebarOpen} />
        </nav>
      </aside>

      {/* Main Content */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Header */}
        <header className="bg-white shadow-sm">
          <div className="flex items-center justify-between px-6 py-4">
            <h2 className="text-xl font-semibold text-gray-800">
              {getPageTitle(router.pathname)}
            </h2>
            
            <div className="flex items-center gap-4">
              <span className="text-sm text-gray-600">
                {user.firstName} {user.lastName}
              </span>
              <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">
                {user.role}
              </span>
              <button
                onClick={handleLogout}
                className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
              >
                Logout
              </button>
            </div>
          </div>
        </header>

        {/* Content */}
        <main className="flex-1 overflow-y-auto p-6">
          {children}
        </main>
      </div>
    </div>
  );
}

function NavSection({ title, open }) {
  if (!open) return null;
  return (
    <div className="px-4 pt-4 pb-2 text-xs font-semibold text-gray-400 uppercase">
      {title}
    </div>
  );
}

function NavItem({ href, icon, label, open }) {
  const router = useRouter();
  const isActive = router.pathname === href;

  return (
    <Link href={href}>
      <div className={`flex items-center px-4 py-3 cursor-pointer transition-colors ${
        isActive 
          ? 'bg-gray-800 text-white border-l-4 border-blue-500' 
          : 'text-gray-300 hover:bg-gray-800'
      }`}>
        <span className="text-xl">{icon}</span>
        {open && <span className="ml-3">{label}</span>}
      </div>
    </Link>
  );
}

function getPageTitle(pathname) {
  const titles = {
    '/admin': 'Dashboard',
    '/admin/matrimonial/profiles': 'Matrimonial Profiles',
    '/admin/classifieds/ads': 'Classified Ads',
    '/admin/classifieds/categories': 'Classified Categories',
    '/admin/events/listings': 'Event Listings',
    '/admin/events/categories': 'Event Categories',
    '/admin/users': 'User Management',
    '/admin/roles': 'Role Management',
    '/admin/seo': 'SEO Settings'
  };
  return titles[pathname] || 'Admin Panel';
}