/** Hook for workspace file operations. */

import { useCallback, useEffect, useState } from "react";
import {
	listWorkspaceFiles,
	getWorkspaceFileContent,
	saveWorkspaceFile,
	type FileEntry,
} from "../api/workspace-files";

export interface UseWorkspaceFilesResult {
	entries: FileEntry[];
	content: string | null;
	currentPath: string;
	loading: boolean;
	error: string | null;
	refresh: () => Promise<void>;
	loadFile: (path: string) => Promise<void>;
	saveFile: (path: string, content: string, message?: string) => Promise<void>;
	navigateTo: (path: string) => void;
}

export function useWorkspaceFiles(
	workspaceId: string,
): UseWorkspaceFilesResult {
	const [entries, setEntries] = useState<FileEntry[]>([]);
	const [content, setContent] = useState<string | null>(null);
	const [currentPath, setCurrentPath] = useState("");
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState<string | null>(null);

	const refresh = useCallback(async () => {
		setLoading(true);
		setError(null);
		try {
			const data = await listWorkspaceFiles(workspaceId, currentPath);
			setEntries(data);
		} catch (err) {
			setError(err instanceof Error ? err.message : "Failed to load files");
		} finally {
			setLoading(false);
		}
	}, [workspaceId, currentPath]);

	const navigateTo = useCallback((path: string) => {
		setCurrentPath(path);
		setContent(null);
	}, []);

	const loadFile = useCallback(
		async (path: string) => {
			try {
				const data = await getWorkspaceFileContent(workspaceId, path);
				setContent(data);
			} catch (err) {
				setContent(null);
				setError(err instanceof Error ? err.message : "Failed to load file");
			}
		},
		[workspaceId],
	);

	const saveFile = useCallback(
		async (path: string, fileContent: string, message?: string) => {
			await saveWorkspaceFile(workspaceId, path, fileContent, message);
			await refresh();
		},
		[workspaceId, refresh],
	);

	useEffect(() => {
		refresh();
	}, [refresh]);

	return {
		entries,
		content,
		currentPath,
		loading,
		error,
		refresh,
		loadFile,
		saveFile,
		navigateTo,
	};
}
