'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { getProfile } from '@/store/slices/auth.slice';
import { useSidebar } from '@/store/zustand/use-sidebar';
import { cn } from '@/lib/utils';
import { Sidebar } from '@/components/layout/sidebar';
import { Header } from '@/components/layout/header';
import { Loader2 } from 'lucide-react';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { token, isAuthenticated, user } = useAppSelector((state) => state.auth);
  const { isCollapsed } = useSidebar();
  const [isInitialized, setIsInitialized] = useState(false);

  // 等待客户端 hydration 完成后再检查 token
  useEffect(() => {
    // 在客户端检查 localStorage 中是否有 token
    const storedToken = localStorage.getItem('admin_token');
    if (!storedToken) {
      // 确实没有 token，跳转到登录页
      router.push('/login');
    } else {
      setIsInitialized(true);
    }
  }, [router]);

  useEffect(() => {
    if (isInitialized && token && !user) {
      dispatch(getProfile());
    }
  }, [isInitialized, token, user, dispatch]);

  // 等待初始化完成
  if (!isInitialized) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  if (!token) {
    return null;
  }

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

  return (
    <div className="min-h-screen bg-muted/30">
      <Sidebar />
      <Header />
      <main
        className={cn(
          'pt-16 transition-all duration-300',
          isCollapsed ? 'pl-16' : 'pl-64'
        )}
      >
        <div className="p-6">{children}</div>
      </main>
    </div>
  );
}
