import { useState, useEffect, useCallback } from 'react';
import { fetchLocalFiles, type LocalFileEntry } from '../api';

export function useFileBrowser(taskId: number | null) {
  const [section, setSection] = useState<'workspace' | 'input' | 'output' | 'logs'>('workspace');
  const [currentPath, setCurrentPath] = useState('');
  const [entries, setEntries] = useState<LocalFileEntry[]>([]);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Fetch entries when taskId/section/path changes
  useEffect(() => {
    if (!taskId) return;
    fetchLocalFiles(taskId, section, currentPath)
      .then(r => setEntries(r.entries))
      .catch(() => setEntries([]));
  }, [taskId, section, currentPath]);

  // Reset when task changes
  useEffect(() => {
    setSection('output');
    setCurrentPath('');
  }, [taskId]);

  const refresh = useCallback(async () => {
    if (!taskId) return;
    setIsRefreshing(true);
    try {
      const r = await fetchLocalFiles(taskId, section, currentPath);
      setEntries(r.entries);
    } catch {
      setEntries([]);
    } finally {
      setIsRefreshing(false);
    }
  }, [taskId, section, currentPath]);

  const pathSegments = currentPath ? currentPath.split('/').filter(Boolean) : [];

  return {
    section, setSection,
    currentPath, setCurrentPath,
    entries,
    isRefreshing,
    refresh,
    pathSegments,
  };
}
