'use client';

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

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

export default function DashboardLayout({ children, params }: DashboardLayoutProps) {
  const { data: session, status } = useSession();
  const router = useRouter();
  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) {
      router.push(`/${locale}/login`);
      return;
    }

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

  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) {
    return null;
  }

  return <>{children}</>;
}