"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useAppSelector } from "@/lib/hooks";
import { Loader2 } from "lucide-react";
import Cookies from "js-cookie";
import { SidebarProvider, SidebarInset, SidebarTrigger } from "@/components/ui/sidebar";
import { AppSidebar } from "@/components/app-sidebar";

export default function AdminLayout({
    children,
}: {
    children: React.ReactNode;
}) {
    const { isAuthenticated, isLoading, user } = useAppSelector((state) => state.auth);
    const router = useRouter();
    const [authorized, setAuthorized] = useState(false);

    useEffect(() => {
        // If we're not loading and not authenticated, redirect
        // We wait for initial restoration to complete (managed by StoreProvider and authSlice)
        const checkAuth = () => {
            const token = Cookies.get("access_token");
            if (!token) {
                router.push("/login");
                return;
            }

            // Get user from state or localStorage
            let currentUser = user;
            if (!currentUser && typeof window !== 'undefined') {
                const userStr = localStorage.getItem("user");
                if (userStr) {
                    try {
                        currentUser = JSON.parse(userStr);
                    } catch (e) { }
                }
            }

            if (currentUser) {
                const isAdmin = currentUser.roles?.some((r: any) => r.name === "admin");
                if (isAdmin) {
                    setAuthorized(true);
                } else {
                    // Redirect non-admins to home page
                    router.push("/");
                }
            } else {
                // Token exists but user data is missing/loading. 
                // If strictly protected, redirect to login.
                router.push("/login");
            }
        };
        checkAuth();
    }, [isAuthenticated, user, router]);

    if (!authorized) {
        return (
            <div className="flex h-screen items-center justify-center">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
        );
    }

    return (
        <SidebarProvider style={{ "--sidebar-width": "16rem" } as React.CSSProperties}>
            <AppSidebar />
            <SidebarInset>
                <header className="flex h-14 shrink-0 items-center gap-2 px-4">
                    <SidebarTrigger className="-ml-1" />
                    <div className="h-4 w-[1px] bg-slate-200 dark:bg-slate-800" />
                    <span className="text-sm font-medium">Yönetim Paneli</span>
                </header>

                <div className="flex flex-1 flex-col gap-4 p-4 pt-0">
                    {children}
                </div>
            </SidebarInset>
        </SidebarProvider>
    );
}
