'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { ROUTES } from '@/constants/routes';
import { auth, onAuthStateChanged, signOut, User } from '@/lib/firebase';
import { toast } from 'sonner';

export default function Dashboard() {
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<User | null>(null);
  const router = useRouter();

  const checkUserRole = async (email: string) => {
    try {
      const response = await fetch(ROUTES.API.CHECK_ROLE, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email })
      });

      if (!response.ok) {
        return false;
      }

      return true;
    } catch (error) {
      console.error('Role check error:', error);
      return false;
    }
  };

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      if (currentUser && currentUser.email) {
        console.log('User is authenticated:', currentUser);

        // Check if user has admin role
        const hasAdminRole = await checkUserRole(currentUser.email);

        if (hasAdminRole) {
          setUser(currentUser);
        } else {
          // Sign out user if they don't have admin role
          await signOut(auth);
          toast.error(
            'Access denied. Only administrators can access this application.'
          );
          router.push(ROUTES.AUTH.SIGN_IN);
          return;
        }
      } else {
        console.log('User is not authenticated, redirecting to sign-in page');
        router.push(ROUTES.AUTH.SIGN_IN);
        return;
      }
      setLoading(false);
    });

    return () => unsubscribe();
  }, [router]);

  // Redirect authenticated users to overview page
  useEffect(() => {
    if (user && !loading) {
      router.push(ROUTES.APP.DASHBOARD + '/overview');
    }
  }, [user, loading, router]);

  if (loading) {
    return (
      <div className='flex h-screen w-full items-center justify-center'>
        <div className='h-32 w-32 animate-spin rounded-full border-b-2 border-gray-900'></div>
      </div>
    );
  }

  if (!user) {
    return null; // Will redirect to sign-in
  }

  return null; // Will redirect to overview
}
