'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 './style.css';

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

export default function FreelancerLayout({ children, params }: FreelancerLayoutProps) {
  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(() => {
    if (status === 'loading') return;

    if (!session?.user) {
      showError('Please login to access this page', 'Access Denied');
      router.push(`/${locale}/login`);
      return;
    }

    const userRole = (session.user as any).role;
    
    if (userRole !== 'FREELANCER') {
      showError('This page is only accessible to freelancers', 'Access Denied');
      
      // Redirect based on user role
      if (userRole === 'CLIENT') {
        router.push(`/${locale}/client/my-projects`);
      } else {
        router.push(`/${locale}`);
      }
      return;
    }

    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 as any).role !== 'FREELANCER') {
    return null;
  }

  return <>{children}</>;
}