'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/auth-store';
import { useThemeStore } from '@/stores/theme-store';
import { themes } from '@/themes';
import { Sidebar } from '@/components/layouts/sidebar';
import { TopNav } from '@/components/layouts/topnav';
import { SidebarCompact } from '@/components/layouts/sidebar-compact';
import { SidebarFloating } from '@/components/layouts/sidebar-floating';
import { SubscriptionBanner } from '@/components/subscription-banner';
import { cn } from '@horux/shared-ui';

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const { isAuthenticated, _hasHydrated } = useAuthStore();
  const { theme } = useThemeStore();

  const currentTheme = themes[theme];
  const layout = currentTheme.layout;

  useEffect(() => {
    // Solo verificar autenticación después de que el store se rehidrate
    if (_hasHydrated && !isAuthenticated) {
      router.push('/login');
    }
  }, [isAuthenticated, _hasHydrated, router]);

  // Mostrar loading mientras se rehidrata el store
  if (!_hasHydrated) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="animate-pulse text-muted-foreground">Cargando...</div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  // Render layout based on theme
  const renderNavigation = () => {
    switch (layout) {
      case 'topnav':
        return <TopNav />;
      case 'sidebar-compact':
        return <SidebarCompact />;
      case 'sidebar-floating':
        return <SidebarFloating />;
      case 'sidebar-standard':
      default:
        return <Sidebar />;
    }
  };

  const getContentClasses = () => {
    switch (layout) {
      case 'topnav':
        return 'pt-16'; // Top padding for fixed top nav
      case 'sidebar-compact':
        return 'pl-16'; // Small left padding for compact sidebar
      case 'sidebar-floating':
        return 'pl-72 pr-4 py-4'; // Padding for floating sidebar
      case 'sidebar-standard':
      default:
        return 'pl-64'; // Standard sidebar width
    }
  };

  return (
    <div className={cn(
      'min-h-screen bg-background',
      layout === 'sidebar-floating' && 'bg-gradient-to-br from-background via-background to-muted/20'
    )}>
      {renderNavigation()}
      <div className={getContentClasses()}>
        <SubscriptionBanner />
        {children}
      </div>
    </div>
  );
}
