'use client';

import { useEffect, useState } from 'react';
import { apiClient } from '@/utils/api';
import { usingBrowserDb } from '@/utils/env';
import { useAuth } from '@/contexts/AuthContext';

export default function useSampleImages(jobID: string, reloadInterval: null | number = null) {
  const [sampleImages, setSampleImages] = useState<string[]>([]);
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const { status: authStatus } = useAuth();

  const refreshSampleImages = () => {
    setStatus('loading');
    if (usingBrowserDb) {
      setSampleImages([]);
      setStatus('success');
      return;
    }
    if (authStatus !== 'authenticated') {
      setSampleImages([]);
      setStatus('idle');
      return;
    }
    apiClient
      .get(`/api/jobs/${jobID}/samples`)
      .then(res => res.data)
      .then(data => {
        console.log('Fetched sample images:', data);
        if (data.samples) {
          setSampleImages(data.samples);
        }
        setStatus('success');
      })
      .catch(error => {
        console.error('Error fetching datasets:', error);
        setStatus('error');
      });
  };

  useEffect(() => {
    if (authStatus !== 'authenticated') {
      setSampleImages([]);
      setStatus('idle');
      return;
    }
    refreshSampleImages();

    if (reloadInterval) {
      const interval = setInterval(() => {
        refreshSampleImages();
      }, reloadInterval);

      return () => {
        clearInterval(interval);
      };
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [jobID, authStatus]);

  return { sampleImages, setSampleImages, status, refreshSampleImages };
}
