import { useCallback, useEffect, useState } from 'react';
import { api } from '@/api/client';
import type { Project } from '@/api/types';

export function useProjects() {
  const [projects, setProjects] = useState<Project[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    try {
      const list = await api.projects.list();
      setProjects(list);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'failed to load projects');
    }
  }, []);

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

  const add = useCallback(
    async (body: { path: string; name?: string }) => {
      const created = await api.projects.add(body);
      await refresh();
      return created;
    },
    [refresh]
  );

  const remove = useCallback(
    async (id: string) => {
      await api.projects.remove(id);
      await refresh();
    },
    [refresh]
  );

  return { projects, error, refresh, add, remove };
}
