'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useStorageService } from '@/core/storage';
import { TagService } from './tag-service';
import type { Tag, TagCategory } from './types';

export function useTags(category?: TagCategory) {
  const storage = useStorageService();
  const service = useMemo(() => new TagService(storage), [storage]);
  const [tags, setTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    const result = category
      ? await service.getTagsByCategory(category)
      : await service.getAllTags();
    setTags(result);
    setLoading(false);
  }, [service, category]);

  // Load initial data from external storage
  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => { refresh(); }, [refresh]);

  const createTag = useCallback(
    async (data: Omit<Tag, 'id' | 'createdAt'>) => {
      const tag = await service.createTag(data);
      await refresh();
      return tag;
    },
    [service, refresh]
  );

  const updateTag = useCallback(
    async (id: string, updates: Partial<Omit<Tag, 'id' | 'createdAt'>>) => {
      const tag = await service.updateTag(id, updates);
      await refresh();
      return tag;
    },
    [service, refresh]
  );

  const deleteTag = useCallback(
    async (id: string) => {
      await service.deleteTag(id);
      await refresh();
    },
    [service, refresh]
  );

  const importTags = useCallback(
    async (data: Omit<Tag, 'id' | 'createdAt'>[]) => {
      const count = await service.importTags(data);
      await refresh();
      return count;
    },
    [service, refresh]
  );

  const searchTags = useCallback(
    async (query: string) => {
      return service.searchTags(query);
    },
    [service]
  );

  return { tags, loading, createTag, updateTag, deleteTag, importTags, searchTags, refresh, service };
}
