import { useState, useCallback } from 'react';
import type { ProductCategoryDTO } from '@effigenix/api-client';
import { client } from '../utils/api-client.js';

interface CategoriesState {
  categories: ProductCategoryDTO[];
  loading: boolean;
  error: string | null;
}

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

export function useCategories() {
  const [state, setState] = useState<CategoriesState>({
    categories: [],
    loading: false,
    error: null,
  });

  const fetchCategories = useCallback(async () => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const categories = await client.categories.list();
      setState({ categories, loading: false, error: null });
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
    }
  }, []);

  const createCategory = useCallback(async (name: string, description?: string) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const req: Record<string, string> = { name };
      if (description) req.description = description;
      const cat = await client.categories.create(req as { name: string; description?: string });
      setState((s) => ({ categories: [...s.categories, cat], loading: false, error: null }));
      return cat;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const updateCategory = useCallback(
    async (id: string, name: string, description: string | null) => {
      try {
        const req: Record<string, string> = { name };
        if (description !== null) req.description = description;
        const updated = await client.categories.update(id, req as { name: string; description?: string });
        setState((s) => ({
          ...s,
          categories: s.categories.map((c) => (c.id === id ? updated : c)),
        }));
        return updated;
      } catch (err) {
        setState((s) => ({ ...s, error: errorMessage(err) }));
        return null;
      }
    },
    [],
  );

  const deleteCategory = useCallback(async (id: string) => {
    try {
      await client.categories.delete(id);
      setState((s) => ({
        ...s,
        categories: s.categories.filter((c) => c.id !== id),
      }));
      return true;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return false;
    }
  }, []);

  const clearError = useCallback(() => {
    setState((s) => ({ ...s, error: null }));
  }, []);

  return {
    ...state,
    fetchCategories,
    createCategory,
    updateCategory,
    deleteCategory,
    clearError,
  };
}
