import { useState, useEffect } from 'react';
import { careerService, JobPosition } from '../api/careerService';

/**
 * Custom hook to fetch all job positions
 */
export const useJobs = () => {
  const [jobs, setJobs] = useState<JobPosition[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchJobs = async () => {
      try {
        setLoading(true);
        const data = await careerService.getAllJobs();
        setJobs(data);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    fetchJobs();
  }, []);

  return { jobs, loading, error };
};

/**
 * Custom hook to fetch a single job by slug
 */
export const useJob = (slug: string) => {
  const [job, setJob] = useState<JobPosition | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    console.log('🔍 useJob hook called with slug:', slug);
    
    if (!slug) {
      console.log('❌ No slug provided, setting loading to false');
      setLoading(false);
      return;
    }

    const fetchJob = async () => {
      try {
        console.log('📡 Fetching job data for slug:', slug);
        setLoading(true);
        const data = await careerService.getJobBySlug(slug);
        console.log('✅ Job data fetched successfully:', data);
        setJob(data);
        setError(null);
      } catch (err) {
        console.error('❌ Error fetching job data:', err);
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        console.log('🔄 Setting loading to false');
        setLoading(false);
      }
    };

    fetchJob();
  }, [slug]);

  return { job, loading, error };
};

/**
 * Custom hook to fetch featured jobs
 */
export const useFeaturedJobs = () => {
  const [jobs, setJobs] = useState<JobPosition[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchFeaturedJobs = async () => {
      try {
        setLoading(true);
        const data = await careerService.getFeaturedJobs();
        setJobs(data);
        setError(null);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    fetchFeaturedJobs();
  }, []);

  return { jobs, loading, error };
};

