'use client';

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

export default function useJobsList(onlyActive = false) {
  const [jobs, setJobs] = useState<JobRecord[]>([]);
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const { status: authStatus } = useAuth();

  const refreshJobs = () => {
    if (authStatus !== 'authenticated') {
      setJobs([]);
      setStatus('idle');
      return;
    }
    setStatus('loading');
    listJobs()
      .then(data => {
        let items = data;
        if (onlyActive) {
          items = items.filter(job => {
            if (job.status === 'running') {
              return true;
            }
            try {
              const jobConfig = JSON.parse(job.job_config);
              return Boolean(jobConfig?.is_hf_job && jobConfig?.hf_job_id);
            } catch (error) {
              return false;
            }
          });
        }
        setJobs(items);
        setStatus('success');
      })
      .catch(error => {
        console.error('Error fetching jobs:', error);
        setStatus('error');
      });
  };
  useEffect(() => {
    if (authStatus !== 'authenticated') {
      setJobs([]);
      return;
    }
    refreshJobs();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authStatus]);

  return { jobs, setJobs, status, refreshJobs };
}
