// src/hooks/useFlyerSelection.ts
import { useState, useCallback, useEffect } from 'react';
import { useLocation, matchPath } from 'react-router-dom';
import { logger } from '../services/logger.client';
import type { Flyer } from '../types';

interface UseFlyerSelectionOptions {
  flyers: Flyer[];
  debugLogging?: boolean;
}

interface UseFlyerSelectionReturn {
  selectedFlyer: Flyer | null;
  handleFlyerSelect: (flyer: Flyer) => void;
  flyerIdFromUrl: string | undefined;
}

/**
 * A custom hook to manage flyer selection state, including:
 * - Manual flyer selection via handleFlyerSelect
 * - URL-based flyer selection (e.g., /flyers/:flyerId)
 * - Auto-selection of the first flyer when none is selected
 *
 * @param options.flyers - Array of available flyers
 * @param options.debugLogging - Enable debug logging (default: false, enabled in test env)
 * @returns Object with selectedFlyer, handleFlyerSelect callback, and flyerIdFromUrl
 *
 * @example
 * ```tsx
 * const { selectedFlyer, handleFlyerSelect, flyerIdFromUrl } = useFlyerSelection({
 *   flyers,
 *   debugLogging: process.env.NODE_ENV === 'test',
 * });
 * ```
 */
export const useFlyerSelection = ({
  flyers,
  debugLogging = process.env.NODE_ENV === 'test',
}: UseFlyerSelectionOptions): UseFlyerSelectionReturn => {
  const [selectedFlyer, setSelectedFlyer] = useState<Flyer | null>(null);
  const location = useLocation();

  // Extract flyerId from URL if present
  const match = matchPath('/flyers/:flyerId', location.pathname);
  const flyerIdFromUrl = match?.params.flyerId;

  const handleFlyerSelect = useCallback((flyer: Flyer) => {
    setSelectedFlyer(flyer);
  }, []);

  // Auto-select first flyer when none is selected and flyers are available
  useEffect(() => {
    if (!selectedFlyer && flyers.length > 0) {
      if (debugLogging) {
        logger.debug('[useFlyerSelection] Auto-selecting first flyer');
      }
      handleFlyerSelect(flyers[0]);
    }
  }, [flyers, selectedFlyer, handleFlyerSelect, debugLogging]);

  // Handle URL-based flyer selection
  useEffect(() => {
    if (flyerIdFromUrl && flyers.length > 0) {
      const flyerId = parseInt(flyerIdFromUrl, 10);
      const flyerToSelect = flyers.find((f) => f.flyer_id === flyerId);
      if (flyerToSelect && flyerToSelect.flyer_id !== selectedFlyer?.flyer_id) {
        if (debugLogging) {
          logger.debug(
            { flyerId, flyerToSelect: flyerToSelect.flyer_id },
            '[useFlyerSelection] Selecting flyer from URL',
          );
        }
        handleFlyerSelect(flyerToSelect);
      }
    }
  }, [flyers, handleFlyerSelect, selectedFlyer, flyerIdFromUrl, debugLogging]);

  return {
    selectedFlyer,
    handleFlyerSelect,
    flyerIdFromUrl,
  };
};
