'use client';

import { useEffect, useState } from 'react';
import { JobRecord } from '@/types';
import { getJob } from '@/utils/storage/jobStorage';
import { useAuth } from '@/contexts/AuthContext';

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

  const refreshJob = () => {
    if (authStatus !== 'authenticated') {
      setJob(null);
      setStatus('idle');
      return;
    }
    setStatus('loading');
    getJob(jobID)
      .then(data => {
        if (data) {
          setJob(data);
          setStatus('success');
        } else {
          setStatus('error');
        }
      })
      .catch(error => {
        console.error('Error fetching job:', error);
        setStatus('error');
      });
  };

  useEffect(() => {
    if (authStatus !== 'authenticated') {
      setJob(null);
      setStatus('idle');
      return;
    }
    refreshJob();

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

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

  return { job, setJob, status, refreshJob };
}
