'use client';
import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(true);
  const [mounted, setMounted] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isCheckingAuth, setIsCheckingAuth] = useState(true);
  const pathname = usePathname();
  const router = useRouter();

  const isLoginPage = pathname === '/admin/login' || pathname === '/login';

  useEffect(() => {
    setMounted(true);
    
    // Check authentication status
    async function checkAuth() {
      if (isLoginPage) {
        setIsCheckingAuth(false);
        return;
      }
      try {
        const res = await fetch('/api/admin/auth/verify');
        if (res.ok) {
          setIsAuthenticated(true);
        } else {
          router.push('/admin/login');
        }
      } catch (err) {
        router.push('/admin/login');
      } finally {
        setIsCheckingAuth(false);
      }
    }
    checkAuth();
  }, [isLoginPage, router]);

  if (isCheckingAuth) {
    return (
      <div className="min-h-screen bg-surface-container-lowest flex items-center justify-center">
        <div className="w-12 h-12 border-4 border-emerald-100 border-t-emerald-600 rounded-full animate-spin"></div>
      </div>
    );
  }

  if (!isLoginPage && !isAuthenticated) {
    return null; // Will redirect
  }

  if (isLoginPage) {
    return <>{children}</>;
  }

  return (
    <div className="min-h-screen bg-surface-container-lowest flex" suppressHydrationWarning>
      {/* Sidebar */}
      <aside 
        className={`${isSidebarCollapsed ? 'w-16' : 'w-64'} bg-primary text-on-primary flex flex-col fixed h-full shadow-2xl z-40 transition-all duration-300 overflow-hidden border-r border-white/5`}
        suppressHydrationWarning
      >
        {mounted ? (
          <>
            <div className="p-4 border-b border-white/10 flex flex-col items-center whitespace-nowrap relative">
              <button 
                onClick={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
                className="absolute -right-4 top-24 bg-primary text-white w-8 h-8 rounded-full flex items-center justify-center border border-white/10 shadow-xl z-50 hover:scale-110 transition-all hover:bg-emerald-600 active:scale-95"
              >
                <span className="material-symbols-outlined text-[18px]">
                  {isSidebarCollapsed ? 'keyboard_double_arrow_right' : 'keyboard_double_arrow_left'}
                </span>
              </button>
              <Link href="/admin" className="text-2xl font-serif tracking-tight text-white flex items-center gap-2">
                <span className={`${isSidebarCollapsed ? 'block' : 'hidden'}`}>M</span>
                <span className={`${isSidebarCollapsed ? 'hidden' : 'block'}`}>Marich Admin</span>
              </Link>
            </div>
            
            <nav className="flex-grow p-2 space-y-1 mt-4 overflow-x-hidden">
              <AdminNavLink href="/admin" icon="dashboard" label="Dashboard" isCollapsed={isSidebarCollapsed} />
              <AdminNavLink href="/admin/products" icon="inventory_2" label="Products" isCollapsed={isSidebarCollapsed} />
              <AdminNavLink href="/admin/interface" icon="auto_fix_high" label="Interface" isCollapsed={isSidebarCollapsed} />
              <AdminNavLink href="/admin/visitors" icon="group" label="Visitors" isCollapsed={isSidebarCollapsed} />
              <AdminNavLink href="/admin/audit" icon="security" label="Audit" isCollapsed={isSidebarCollapsed} />
              <AdminNavLink href="/admin/settings" icon="settings" label="Settings" isCollapsed={isSidebarCollapsed} />
            </nav>
            
            <div className="p-2 border-t border-white/10 space-y-1">
              <Link href="/" className="flex items-center gap-4 p-3 rounded-xl hover:bg-white/10 transition-colors text-sm font-bold whitespace-nowrap">
                <span className="material-symbols-outlined text-xl">open_in_new</span>
                {!isSidebarCollapsed && <span>View Website</span>}
              </Link>
              <button 
                onClick={async () => {
                  await fetch('/api/admin/auth/logout', { method: 'POST' });
                  router.push('/admin/login');
                }}
                className="flex w-full items-center gap-4 p-3 rounded-xl hover:bg-red-500/20 text-red-200 transition-colors text-sm font-bold whitespace-nowrap"
              >
                <span className="material-symbols-outlined text-xl">logout</span>
                {!isSidebarCollapsed && <span>Logout</span>}
              </button>
            </div>
          </>
        ) : (
          <div className="flex-grow animate-pulse bg-white/5" />
        )}
      </aside>

      {/* Main Content */}
      <main 
        className={`flex-grow ${isSidebarCollapsed ? 'ml-16' : 'ml-64'} p-8 lg:p-12 transition-all duration-300`}
        suppressHydrationWarning
      >
        {children}
      </main>
    </div>
  );
}

function AdminNavLink({ href, icon, label, isCollapsed }: { href: string; icon: string; label: string; isCollapsed: boolean }) {
  return (
    <Link 
      href={href} 
      prefetch={true}
      className={`flex items-center ${isCollapsed ? 'justify-center' : 'gap-4'} p-3 rounded-xl hover:bg-white/10 transition-all group active:scale-95 whitespace-nowrap`}
      title={isCollapsed ? label : ''}
    >
      <span className="material-symbols-outlined text-xl group-hover:scale-110 transition-transform">{icon}</span>
      {!isCollapsed && <span className="text-xs font-bold tracking-widest uppercase">{label}</span>}
    </Link>
  );
}
