'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { ReactNode } from 'react';
import { useToast } from '@/components/ui/ToastContext';
import Footer from '@/components/Footer';

interface ClientLayoutProps {
  children: ReactNode;
  params: Promise<{
    locale: string;
  }>;
}

export default function ClientLayout({ children, params }: ClientLayoutProps) {
  const { data: session, status } = useSession();
  const router = useRouter();
  const { showError } = useToast();
  const [locale, setLocale] = useState<string>('');
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const getLocale = async () => {
      const resolvedParams = await params;
      setLocale(resolvedParams.locale);
    };
    getLocale();
  }, [params]);

  useEffect(() => {
    console.log('🏠 Client Layout - Session check:', {
      status,
      hasSession: !!session,
      userRole: session?.user ? session.user.role : 'no-session',
      userName: session?.user?.name
    });
    
    if (status === 'loading') return;

    if (!session?.user) {
      console.log('❌ Client Layout - No session, redirecting to login');
      showError('Please login to access this page', 'Access Denied');
      router.push(`/${locale}/login`);
      return;
    }

    const userRole = session.user.role;
    console.log('👤 Client Layout - User role:', userRole);
    
    if (userRole !== 'CLIENT') {
      console.log('❌ Client Layout - Wrong role, redirecting');
      showError('This page is only accessible to clients', 'Access Denied');
      
      // Redirect based on user role
      if (userRole === 'FREELANCER') {
        router.push(`/${locale}/freelancer/my-projects`);
      } else {
        router.push(`/${locale}`);
      }
      return;
    }

    console.log('✅ Client Layout - Access granted');
    setIsLoading(false);
  }, [session, status, router, locale, showError]);

  if (status === 'loading' || isLoading) {
    return (
      <div className="d-flex align-items-center justify-content-center loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (!session?.user || session.user.role !== 'CLIENT') {
    return null;
  }

  return (<>
    {children}
    <Footer locale={locale} />
  </>);
}