import { useState, useEffect } from "react";
import { Category } from "@/types/categories";
import { ServerChannels } from "@/ipc/channels/serverChannels";
import { useLicense } from "@/ui/hooks/useLicense";

interface UseWallpaperCategoriesReturn {
  wallpaperCategories: Category[];
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

export function useWallpaperCategories(): UseWallpaperCategoriesReturn {
  const [wallpaperCategories, setWallpaperCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { isPremium } = useLicense();

  const fetchCategories = async () => {
    try {
      setLoading(true);
      setError(null); // Clear any previous errors
      const categories = await window.electron.ipcRenderer.invoke(ServerChannels.GET_CATEGORIES);
      setWallpaperCategories(categories as Category[]);
    } catch (err) {
      console.warn("[useWallpaperCategories] Failed to fetch categories:", err);

      // Check if the error is a network-related error
      const errorMessage = err instanceof Error ? err.message : String(err);
      const isNetworkError =
        errorMessage.includes("No response from server") ||
        errorMessage.includes("network") ||
        errorMessage.includes("ECONNREFUSED") ||
        errorMessage.includes("timeout");

      if (isNetworkError) {
        // For network errors, set a user-friendly message but don't completely fail
        console.warn("[useWallpaperCategories] Network error detected, using fallback behavior");
        setError("Unable to load latest style categories. Some features may be limited.");
        // Keep any existing categories in state if we have them
      } else {
        // For other errors, set a generic error message
        setError("Failed to load style categories. Please try again later.");
      }
    } finally {
      setLoading(false);
    }
  };

  // Initial fetch and refetch when license plan changes
  useEffect(() => {
    fetchCategories();
  }, [isPremium]); // Refetch when isPremium changes

  return {
    wallpaperCategories,
    loading,
    error,
    refetch: fetchCategories,
  };
}
