import { useAtomValue, useSetAtom } from 'jotai';
import { useEffect } from 'react';
import { useFeatureFlagService } from 'src/contexts/featureFlagServiceContext/featureFlagServiceContext';
import {
  performProductRetrievalAtom,
  productRetrievalAtom,
  retrievedProductsAtom,
} from 'src/atoms/search/productRetrievalAPI';
import { SearchResponseProductAttributes } from 'src/application/models/api/response';
import { FeatureGates } from 'src/application/models';
import { useNewOrgConfig } from '../NewOrgConfig';

/**
 * A hook to get recommended products.
 * It checks the `IsRecommendedProductsEnabled` feature gate and triggers fetching if needed.
 * If the gate is enabled, it returns the list of recommended products.
 * If the gate is disabled, it returns an empty array.
 *
 * @returns The list of recommended products or an empty array.
 */
export const useRecommendedProducts = (): SearchResponseProductAttributes['attributes'][] => {
  const { featureFlagService } = useFeatureFlagService();
  const isEnabled = featureFlagService?.isFeatureGateEnabled(
    FeatureGates.IsRecommendedProductsEnabled,
  );
  const recommendedProducts = useAtomValue(retrievedProductsAtom);
  const performProductRetrieval = useSetAtom(performProductRetrievalAtom);
  const { lastProductIds } = useAtomValue(productRetrievalAtom);
  const orgUIConfig = useNewOrgConfig();

  useEffect(() => {
    const recommendedProductIds = orgUIConfig.frontendConfig?.uiConfigs?.searchConfig
      ? orgUIConfig.frontendConfig?.uiConfigs?.searchConfig.recommendedProducts
      : [];
    // Fetch only if the feature is enabled, there are IDs to fetch, and we haven't already fetched them.
    if (isEnabled && recommendedProductIds && recommendedProductIds.length > 0 && !lastProductIds) {
      performProductRetrieval({ productIds: recommendedProductIds });
    }
  }, [isEnabled, performProductRetrieval, lastProductIds, orgUIConfig]);

  return isEnabled ? recommendedProducts : [];
};
