import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '../api/client';
import type { Monster, Item, Recipe } from '../api/types';

const guideApi = {
  monsters:  () => api.get<(Monster & { zone: string })[]>('/monsters/bestiary'),
  items:     () => api.get<Item[]>('/items'),
  materials: () => api.get<any[]>('/materials'),
  recipes:   () => api.get<Recipe[]>('/craft/recipes'),
};

export function useGuideData(search: string) {
  const { data: monsters = [] }  = useQuery({ queryKey: ['guide-monsters'],  queryFn: guideApi.monsters,  staleTime: 5 * 60_000 });
  const { data: items = [] }     = useQuery({ queryKey: ['guide-items'],     queryFn: guideApi.items,     staleTime: 5 * 60_000 });
  const { data: materials = [] } = useQuery({ queryKey: ['guide-materials'], queryFn: guideApi.materials, staleTime: 5 * 60_000 });
  const { data: recipes = [] }   = useQuery({ queryKey: ['guide-recipes'],   queryFn: guideApi.recipes,   staleTime: 5 * 60_000 });

  const q = search.toLowerCase().trim();

  const filteredMonsters = useMemo(
    () => q ? monsters.filter(m => m.name.toLowerCase().includes(q) || (m as any).zone?.toLowerCase().includes(q)) : monsters,
    [monsters, q],
  );

  const filteredItems = useMemo(
    () => q ? items.filter(i => i.name.toLowerCase().includes(q) || i.rarity.toLowerCase().includes(q) || i.description?.toLowerCase().includes(q)) : items,
    [items, q],
  );

  const matMap = useMemo(() => new Map<string, any>(materials.map(m => [m.id, m])), [materials]);

  const filteredRecipes = useMemo(() => {
    if (!q) return recipes;
    return recipes.filter(r =>
      r.name.toLowerCase().includes(q) ||
      r.resultItem?.name.toLowerCase().includes(q) ||
      r.ingredients.some(ing => matMap.get(ing.materialId)?.name.toLowerCase().includes(q))
    );
  }, [recipes, matMap, q]);

  return { monsters, items, materials, recipes, filteredMonsters, filteredItems, filteredRecipes, matMap, q };
}
