"use client";

import { useState, useEffect, useCallback } from 'react';
import { useProducts } from './useProducts';
import { useCategories } from './useCategories';
import { cache, cacheKeys, cacheTTL } from '@/lib/cache';
import type { ApiProduct, ApiCategory } from '@/types/api';

interface HomePageData {
  categories: ApiCategory[];
  featuredProducts: ApiProduct[];
  newArrivals: ApiProduct[];
  flashSaleProducts: ApiProduct[];
}

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

export function useHomePageData(options: UseHomePageDataOptions = {}) {
  const [homeData, setHomeData] = useState<HomePageData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [fromCache, setFromCache] = useState(false);

  const { enableCache = true, ttl = cacheTTL.homePageData } = options;

  // Individual hooks for fallback
  const { categories, loading: categoriesLoading } = useCategories({ enableCache });
  const { products: featuredProducts, loading: featuredLoading } = useProducts({ 
    enableCache,
    autoFetch: false // We'll control fetching manually
  });

  const fetchHomePageData = useCallback(async (forceRefresh = false) => {
    console.log('useHomePageData: Starting to fetch home page data...');
    setLoading(true);
    setError(null);
    setFromCache(false);

    try {
      const cacheKey = cacheKeys.homePageData();
      
      // Try cache first if enabled and not forcing refresh
      if (enableCache && !forceRefresh) {
        const cachedData = cache.get<HomePageData>(cacheKey);
        if (cachedData) {
          console.log('useHomePageData: Retrieved from cache:', cachedData);
          setHomeData(cachedData);
          setFromCache(true);
          setLoading(false);
          return;
        }
      }

      // If we have some data from individual hooks, use it while loading
      if (categories.length > 0 && featuredProducts.length > 0) {
        setHomeData({
          categories,
          featuredProducts: featuredProducts.slice(0, 12),
          newArrivals: featuredProducts.slice(0, 8),
          flashSaleProducts: featuredProducts.slice(0, 6),
        });
      }

      // Parallel fetch for better performance
      const [categoriesResponse, productsResponse] = await Promise.all([
        // Only fetch categories if not cached or if forcing refresh
        enableCache && !forceRefresh && categories.length > 0 
          ? Promise.resolve(categories)
          : fetch('/api/categories').then(res => res.json()),
        
        // Fetch products
        fetch('/api/products?limit=20').then(res => res.json()),
      ]);

      const homePageData: HomePageData = {
        categories: Array.isArray(categoriesResponse) ? categoriesResponse : categories,
        featuredProducts: productsResponse.data?.slice(0, 12) || [],
        newArrivals: productsResponse.data?.slice(0, 8) || [],
        flashSaleProducts: productsResponse.data?.slice(0, 6) || [],
      };

      // Cache the combined data
      if (enableCache) {
        cache.set(cacheKey, homePageData, { ttl });
      }

      setHomeData(homePageData);
      console.log('useHomePageData: Data fetched successfully:', homePageData);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch home page data';
      console.error('useHomePageData: Error:', err);
      setError(errorMessage);

      // Fallback to individual hook data if available
      if (categories.length > 0 || featuredProducts.length > 0) {
        setHomeData({
          categories,
          featuredProducts: featuredProducts.slice(0, 12),
          newArrivals: featuredProducts.slice(0, 8),
          flashSaleProducts: featuredProducts.slice(0, 6),
        });
      }
    } finally {
      setLoading(false);
    }
  }, [categories, featuredProducts, enableCache, ttl]);

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

  // Prefetch next page data
  const prefetchNextPage = useCallback(async () => {
    try {
      // Prefetch products page 2
      const cacheKey = cacheKeys.products({ page: 2 });
      if (!cache.has(cacheKey)) {
        fetch('/api/products?page=2')
          .then(res => res.json())
          .then(data => cache.set(cacheKey, data, { ttl: cacheTTL.products }))
          .catch(console.warn);
      }
    } catch (error) {
      console.warn('Prefetch failed:', error);
    }
  }, []);

  // Auto-prefetch after initial load
  useEffect(() => {
    if (homeData && !loading) {
      const timer = setTimeout(prefetchNextPage, 2000); // Prefetch after 2 seconds
      return () => clearTimeout(timer);
    }
  }, [homeData, loading, prefetchNextPage]);

  const refresh = useCallback(() => {
    return fetchHomePageData(true);
  }, [fetchHomePageData]);

  return {
    homeData,
    loading: loading || (categoriesLoading && featuredLoading),
    error,
    fromCache,
    refresh,
    prefetchNextPage,
  };
}

/**
 * Background preloading hook for non-critical data
 */
export function useBackgroundPreload() {
  useEffect(() => {
    // Preload common routes after initial page load
    const preloadTimer = setTimeout(() => {
      // Preload products page
      const link = document.createElement('link');
      link.rel = 'prefetch';
      link.href = '/products';
      document.head.appendChild(link);

      // Preload category data if not cached
      if (!cache.has(cacheKeys.categories())) {
        fetch('/api/categories')
          .then(res => res.json())
          .then(data => cache.set(cacheKeys.categories(), data, { ttl: cacheTTL.categories }))
          .catch(console.warn);
      }
    }, 3000);

    return () => clearTimeout(preloadTimer);
  }, []);
}