"use client";

import { useEffect, useState } from "react";
import React, { ReactNode } from "react";
import { ThemeProvider } from "./theme-context";
import { motion, AnimatePresence } from "framer-motion";
import { SidebarProvider } from "./sidebar-context";
import { ModernSidebar } from "./modern-sidebar";
import { ModernHeader } from "./modern-header";

export const AdminLayout = ({ children }: { children: ReactNode }) => {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [hasMounted, setHasMounted] = useState(false);

  const toggleSidebar = () => {
    setSidebarOpen(!sidebarOpen);
  };

  // Hooks
  useEffect(() => {
    setHasMounted(true);
    // Auto-collapse sidebar on mobile
    const handleResize = () => {
      if (window.innerWidth < 1024) {
        setSidebarOpen(false);
      } else {
        setSidebarOpen(true);
      }
    };

    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Render loading state until mounted
  if (!hasMounted) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  return (
    <ThemeProvider>
      <SidebarProvider>
        <div className="min-h-screen bg-gray-50">
          <div className="flex h-screen overflow-hidden">
            {/* Modern Sidebar */}
            <ModernSidebar isOpen={sidebarOpen} onToggle={toggleSidebar} />

            {/* Main Content Area */}
            <div 
              className={`flex-1 flex flex-col overflow-hidden transition-all duration-300 ml-0`}
            >
              {/* Modern Header */}
              <ModernHeader 
                onMenuToggle={toggleSidebar} 
                sidebarOpen={sidebarOpen}
              />

              {/* Main Content */}
              <motion.main
                className="flex-1 overflow-auto bg-gray-50"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1, duration: 0.3 }}
              >
                <div className="p-6">
                  {children}
                </div>
              </motion.main>
            </div>
          </div>
        </div>
      </SidebarProvider>
    </ThemeProvider>
  );
};
