// src/hooks/useActiveDeals.tsx
import { useEffect, useMemo } from 'react';
import { useFlyers } from './useFlyers';
import { useUserData } from '../hooks/useUserData';
import { useApi } from './useApi';
import type { FlyerItem, DealItem } from '../types';
import * as apiClient from '../services/apiClient';

interface FlyerItemCount {
  count: number;
}

/**
 * A custom hook to calculate currently active deals and total active items
 * based on flyer validity dates and a user's watched items.
 * @returns An object containing active deals, total active items, loading state, and any errors.
 */
export const useActiveDeals = () => {
  const { flyers } = useFlyers();
  const { watchedItems } = useUserData();
  // Centralize API call state management with the useApi hook. We can ignore isRefetching here.
  const { execute: executeCount, loading: loadingCount, error: errorCount, data: countData, reset: resetCount } = useApi<FlyerItemCount, [number[]]>(apiClient.countFlyerItemsForFlyers);
  const { execute: executeItems, loading: loadingItems, error: errorItems, data: itemsData, reset: resetItems } = useApi<FlyerItem[], [number[]]>(apiClient.fetchFlyerItemsForFlyers);

  // Consolidate loading and error states from both API calls.
  const isLoading = loadingCount || loadingItems;
  const error = errorCount || errorItems ? `Could not fetch active deals or totals: ${errorCount?.message || errorItems?.message}` : null;

  // Memoize the calculation of valid flyers to avoid re-computing on every render.
  const validFlyers = useMemo(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return flyers.filter(flyer => new Date(`${flyer.valid_from}T00:00:00`) <= today && today <= new Date(`${flyer.valid_to}T00:00:00`));
  }, [flyers]);

  useEffect(() => {
    // When dependencies change (e.g., user logs in/out), reset previous API data.
    // This prevents showing stale data from a previous session.
    resetCount();
    resetItems();

    const calculateActiveData = async () => {
      // If there are no valid flyers, don't make any API calls.
      // The hooks will remain in their initial state (data: null), which is handled below.
      if (validFlyers.length === 0) {
        return;
      }

      const validFlyerIds = validFlyers.map(f => f.flyer_id);

      // Execute API calls using the hooks.
      if (watchedItems.length > 0) {
        executeItems(validFlyerIds);
      }
      executeCount(validFlyerIds);
    };

    calculateActiveData();
  }, [validFlyers, watchedItems, executeCount, executeItems, resetCount, resetItems]); // Dependencies now include the reset functions.

  // Process the data returned from the API hooks.
  const activeDeals = useMemo(() => {
    if (!itemsData || watchedItems.length === 0) return [];

    const watchedItemIds = new Set(watchedItems.map(item => item.master_grocery_item_id));
    const dealItemsRaw = itemsData.filter(item => item.master_item_id && watchedItemIds.has(item.master_item_id));
    const flyerIdToStoreName = new Map(validFlyers.map(f => [f.flyer_id, f.store?.name || 'Unknown Store']));

    return dealItemsRaw.map((item): DealItem => ({
      item: item.item,
      price_display: item.price_display,
      price_in_cents: item.price_in_cents,
      quantity: item.quantity,
      storeName: flyerIdToStoreName.get(item.flyer_id!) || 'Unknown Store',
      master_item_name: item.master_item_name,
      unit_price: item.unit_price
    }));
  }, [itemsData, watchedItems, validFlyers]);

  const totalActiveItems = countData?.count ?? 0;
  return { activeDeals, totalActiveItems, isLoading, error };
};