/**
 * Custom hook for managing tags
 */

import { useState, useEffect } from 'react';
import { fetchTags, createTag } from '../services/api';
import type { Tag } from '../types/recipe';

interface UseTagsReturn {
  tags: Tag[];
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  addTag: (name: string, color?: string) => Promise<Tag>;
}

/**
 * Hook to fetch and manage tags
 */
export function useTags(): UseTagsReturn {
  const [tags, setTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadTags = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await fetchTags();
      setTags(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load tags');
    } finally {
      setLoading(false);
    }
  };

  const addTag = async (name: string, color?: string): Promise<Tag> => {
    try {
      const newTag = await createTag({ name, color });
      setTags([...tags, newTag].sort((a, b) => a.name.localeCompare(b.name)));
      return newTag;
    } catch (err) {
      throw new Error(err instanceof Error ? err.message : 'Failed to create tag');
    }
  };

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

  return {
    tags,
    loading,
    error,
    refresh: loadTags,
    addTag,
  };
}
