'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/useAuthStore';
import { Sidebar } from '@/components/layout/Sidebar';
import { Header } from '@/components/layout/Header';
import { api, apiEndpoints } from '@/lib/api';
import { Toaster } from '@/components/ui/toaster';

interface DashboardLayoutProps {
  children: React.ReactNode;
}

export default function DashboardLayout({ children }: DashboardLayoutProps) {
  const router = useRouter();
  const { isAuthenticated, token, refreshToken, login, setLoading, setError, logout } = useAuthStore();
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isHydrated, setIsHydrated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // Wait for Zustand hydration from localStorage
  useEffect(() => {
    setIsHydrated(true);
  }, []);

  useEffect(() => {
    // Don't run auth check until Zustand has hydrated
    if (!isHydrated) return;

    const checkAuth = async () => {
      // No token and not authenticated → redirect to login
      if (!token && !isAuthenticated) {
        setIsLoading(false);
        router.push('/login');
        return;
      }

      // Already authenticated with token → proceed
      if (isAuthenticated && token) {
        setIsLoading(false);
        return;
      }

      // Has token but not authenticated → verify token with API
      if (token && !isAuthenticated) {
        try {
          setLoading(true);
          const user = await api.get<{
            id: string;
            email: string;
            username: string;
            createdAt: string;
            lastLoginAt: string;
          }>(apiEndpoints.auth.me);
          // Use login() to properly set all auth state including token
          login(user, token, refreshToken ?? undefined);
          setIsLoading(false);
        } catch (error) {
          setError('Sesión expirada. Por favor inicia sesión nuevamente.');
          // Clear the correct localStorage key used by Zustand persist
          if (typeof window !== 'undefined') {
            localStorage.removeItem('math-platform-auth');
          }
          logout();
          router.push('/login');
        } finally {
          setLoading(false);
        }
      }
    };

    void checkAuth();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isHydrated, isAuthenticated, token]);

  // Show loading spinner while hydrating or checking auth
  if (!isHydrated || isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          <p className="text-sm text-muted-foreground">Cargando...</p>
        </div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div className="flex h-screen overflow-hidden bg-background">
      <Toaster />
      <Sidebar />
      <div className="flex flex-1 flex-col overflow-hidden">
        <Header onMobileMenuToggle={() => setIsSidebarOpen(!isSidebarOpen)} />
        <main className="flex-1 overflow-y-auto p-4 md:p-6">
          {children}
        </main>
      </div>
    </div>
  );
}