'use client';

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

interface FileObject {
  path: string;
  size: number;
}

const clean = (text: string): string => {
  // remove \x1B[A\x1B[A
  text = text.replace(/\x1B\[A/g, '');
  return text;
};

export default function useJobLog(jobID: string, reloadInterval: null | number = null) {
  const [log, setLog] = useState<string>('');
  const didInitialLoadRef = useRef(false);
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error' | 'refreshing'>('idle');
  const { status: authStatus } = useAuth();

  const refresh = () => {
    let loadStatus: 'loading' | 'refreshing' = 'loading';
    if (didInitialLoadRef.current) {
      loadStatus = 'refreshing';
    }
    setStatus(loadStatus);
    if (usingBrowserDb) {
      setLog('');
      setStatus('success');
      didInitialLoadRef.current = true;
      return;
    }
    if (authStatus !== 'authenticated') {
      setLog('');
      setStatus('idle');
      return;
    }
    apiClient
      .get(`/api/jobs/${jobID}/log`)
      .then(res => res.data)
      .then(data => {
        if (data.log) {
          let cleanLog = clean(data.log);
          setLog(cleanLog);
        }
        setStatus('success');
        didInitialLoadRef.current = true;
      })
      .catch(error => {
        console.error('Error fetching log:', error);
        setStatus('error');
      });
  };

  useEffect(() => {
    if (authStatus !== 'authenticated') {
      setLog('');
      setStatus('idle');
      return;
    }
    refresh();

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

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

  return { log, setLog, status, refresh };
}
