import { ReactNode, useEffect, useState } from "react";
import { Outlet, useNavigate, useParams } from "react-router-dom";
import CourseEditorHeader from "./CourseEditorHeader";
import { motion } from "framer-motion";
import { NavItem } from "@nice/client"
import CourseEditorSidebar from "./CourseEditorSidebar";
import { CourseFormProvider } from "../context/CourseEditorContext";
import { getNavItems } from "../navItems";


export default function CourseEditorLayout() {
    const { id } = useParams();
    const [isHovered, setIsHovered] = useState(false);
    const [selectedSection, setSelectedSection] = useState<number>(0);
    const [navItems, setNavItems] = useState<NavItem[]>(getNavItems(id));
    useEffect(() => {
        setNavItems(getNavItems(id))
    }, [id])
    useEffect(() => {
        const currentPath = location.pathname;
        const index = navItems.findIndex(item => item.path === currentPath);
        if (index !== -1) {
            setSelectedSection(index);
        }
    }, [location.pathname, navItems]);
    const navigate = useNavigate();
    const handleNavigation = (item: NavItem, index: number) => {
        setSelectedSection(index);
        navigate(item.path, { replace: true });
    };
    return (
        <CourseFormProvider editId={id}>
            <div className="min-h-screen bg-gray-50">
                <CourseEditorHeader />
                <div className="flex pt-16">
                    <CourseEditorSidebar
                        isHovered={isHovered}
                        setIsHovered={setIsHovered}
                        navItems={navItems}
                        selectedSection={selectedSection}
                        onNavigate={handleNavigation}
                    />
                    <motion.main
                        animate={{ marginLeft: isHovered ? "16rem" : "5rem" }}
                        transition={{ type: "spring", stiffness: 200, damping: 25, mass: 1 }}
                        className="flex-1 p-8"
                    >
                        <div className="max-w-6xl mx-auto bg-white rounded-xl shadow-lg">
                            <header className="p-6 border-b border-gray-100">
                                <h1 className="text-2xl font-bold text-gray-900">
                                    {navItems[selectedSection]?.label}
                                </h1>
                            </header>
                            <div className="p-6">
                                <Outlet></Outlet>
                            </div>
                        </div>
                    </motion.main>
                </div>
            </div>
        </CourseFormProvider>

    );
}