'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { ReactNode } from 'react';

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

export default function AuthLayout({ children, params }: AuthLayoutProps) {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [locale, setLocale] = useState<string>('');
  const [isLoading, setIsLoading] = useState(true);
  const [hasRedirected, setHasRedirected] = useState(false);

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

  useEffect(() => {
    if (status === 'loading' || !locale || hasRedirected) return;

    if (session?.user) {
      // User is already authenticated, redirect to appropriate dashboard
      const role = session.user.role?.toLowerCase();
      if (role === 'client') {
        router.push(`/${locale}/client/my-projects`);
      } else if (role === 'freelancer') {
        router.push(`/${locale}/freelancer/my-projects`);
      } else if (role === 'admin') {
        // Admin dashboard not implemented yet, redirect to home
        router.push(`/${locale}`);
      } else {
        // Fallback to home page if role is unknown
        router.push(`/${locale}`);
      }
      setHasRedirected(true);
      return;
    }

    setIsLoading(false);
  }, [session, status, router, locale, hasRedirected]);

  // Reset redirect state when session changes
  useEffect(() => {
    if (!session?.user) {
      setHasRedirected(false);
    }
  }, [session]);

  // Show loading spinner while checking authentication
  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 user is authenticated, don't render auth pages
  if (session?.user) {
    return null;
  }

  // User is not authenticated, show auth pages
  return <>{children}</>;
}
