import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { getCountryDataByDomain } from '@/lib/countries';

interface ProjectCounts {
  recommended: number;
  proposed: number;
  awarded: number;
  cancelled: number;
  completed: number;
}

export const useProjectCounts = () => {
  const { data: session } = useSession();
  const [projectCounts, setProjectCounts] = useState<ProjectCounts>({
    recommended: 0,
    proposed: 0,
    awarded: 0,
    cancelled: 0,
    completed: 0
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchProjectCounts = async () => {
      if (!session?.user) return;
      
      setLoading(true);
      setError(null);
        
      const params = new URLSearchParams({});
      const datacounter =    getCountryDataByDomain();
      if(!datacounter?.id){
          setError('Country is missing');
          return false;
      }
      params.set('countryId', datacounter?.id);
      
      try {
        const response = await fetch(`/api/projects/my-projects/counts?${params.toString()}`);
        if (response.ok) {
          const data = await response.json();
          if (data.success) {
            setProjectCounts(data.data);
          } else {
            setError('Failed to fetch project counts');
          }
        } else {
          setError('Failed to fetch project counts');
        }
      } catch (error) {
        console.error('Error fetching project counts:', error);
        setError('Failed to fetch project counts');
      } finally {
        setLoading(false);
      }
    };

    fetchProjectCounts();
  }, [session]);

  return { projectCounts, loading, error };
};
