'use client';

import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { ReactNode, useEffect } from 'react';
import { useTenant } from '../contexts/tenant-context';

export function AuthGuard({ children }: { children: ReactNode }) {
  const { data: session, status } = useSession();
  const { activeClubId, clubs, setActiveClub } = useTenant();
  const router = useRouter();

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/login');
    }
  }, [status, router]);

  useEffect(() => {
    if (status === 'authenticated' && clubs.length > 0) {
      if (clubs.length === 1 && !activeClubId) {
        setActiveClub(clubs[0].id);
      } else if (clubs.length > 1 && !activeClubId) {
        router.push('/select-club');
      }
    }
  }, [status, clubs, activeClubId, router, setActiveClub]);

  if (status === 'loading') {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <p>Loading...</p>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return null;
  }

  if (clubs.length === 0 && status === 'authenticated') {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen gap-4">
        <h2 className="text-2xl font-bold">No Clubs Found</h2>
        <p>Contact admin to get access to a club</p>
      </div>
    );
  }

  if (clubs.length > 1 && !activeClubId) {
    return null;
  }

  return <>{children}</>;
}
