/**
 * Hook para gerenciar projetos salvos (IndexedDB).
 */

import { useEffect, useState, useCallback } from 'react';
import {
  saveProject as dbSave,
  listProjects as dbList,
  loadProject as dbLoad,
  deleteProject as dbDelete,
  type SavedProject,
} from '../storage';

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

  const refresh = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await dbList();
      setProjects(list.sort((a: SavedProject, b: SavedProject) => b.updatedAt - a.updatedAt));
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Erro desconhecido');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const save = useCallback(async (project: SavedProject): Promise<number> => {
    const id = await dbSave(project);
    await refresh();
    return id;
  }, [refresh]);

  const load = useCallback(async (id: number): Promise<SavedProject | undefined> => {
    return dbLoad(id);
  }, []);

  const remove = useCallback(async (id: number): Promise<void> => {
    await dbDelete(id);
    await refresh();
  }, [refresh]);

  return { projects, loading, error, save, load, remove, refresh };
}