"use client";

import { useState, useEffect, useCallback, useRef } from 'react';
import { productApi } from '@/lib/services/productService';
import { cache, cacheKeys, cacheTTL } from '@/lib/cache';
import type { ApiCategory } from '@/types/api';

interface UseCategoriesOptions {
  enableCache?: boolean;
  ttl?: number;
}

export function useCategories(options: UseCategoriesOptions = {}) {
  const [categories, setCategories] = useState<ApiCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [fromCache, setFromCache] = useState(false);
  
  const abortControllerRef = useRef<AbortController | null>(null);
  const { enableCache = true, ttl = cacheTTL.categories } = options;

  useEffect(() => {
    const fetchCategories = async () => {
      console.log('useCategories: Starting to fetch categories...');
      
      // Cancel previous request
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      
      const abortController = new AbortController();
      abortControllerRef.current = abortController;
      
      setLoading(true);
      setError(null);
      setFromCache(false);
      
      try {
        const cacheKey = cacheKeys.categories();
        
        // Try to get from cache first if enabled
        if (enableCache) {
          const cachedData = cache.get<ApiCategory[]>(cacheKey);
          if (cachedData) {
            console.log('useCategories: Retrieved from cache:', cachedData);
            setCategories(cachedData);
            setFromCache(true);
            setLoading(false);
            return;
          }
        }
        
        // Fetch from API
        const response = await productApi.getCategories();
        
        // Check if request was aborted
        if (abortController.signal.aborted) {
          return;
        }
        
        console.log('useCategories: Categories fetched successfully:', response);
        
        // Cache the response if caching is enabled
        if (enableCache) {
          cache.set(cacheKey, response, { ttl });
        }
        
        setCategories(response);
      } catch (err) {
        if (err instanceof Error && err.name === 'AbortError') {
          console.log('useCategories: Request aborted');
          return;
        }
        
        const errorMessage = err instanceof Error ? err.message : 'Failed to fetch categories';
        console.error('useCategories: Error fetching categories:', err);
        setError(errorMessage);
      } finally {
        if (!abortController.signal.aborted) {
          setLoading(false);
          console.log('useCategories: Fetch completed');
        }
      }
    };

    fetchCategories();
    
    // Cleanup function
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, [enableCache, ttl]);

  // Force refresh function
  const refresh = useCallback(() => {
    const fetchCategories = async () => {
      console.log('useCategories: Force refreshing categories...');
      
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
      
      const abortController = new AbortController();
      abortControllerRef.current = abortController;
      
      setLoading(true);
      setError(null);
      
      try {
        const response = await productApi.getCategories();
        
        if (abortController.signal.aborted) return;
        
        if (enableCache) {
          cache.set(cacheKeys.categories(), response, { ttl });
        }
        
        setCategories(response);
      } catch (err) {
        if (err instanceof Error && err.name !== 'AbortError') {
          setError(err.message);
        }
      } finally {
        if (!abortController.signal.aborted) {
          setLoading(false);
        }
      }
    };

    fetchCategories();
  }, [enableCache, ttl]);

  return {
    categories,
    loading,
    error,
    fromCache,
    refresh,
  };
}
