import { Skeleton } from '@chakra-ui/react'
import { useQuery } from 'react-query'
import ProductSlider from '~/modules/product-slider'
import { getProductSimilar, getProductsByIds } from '~/services/product'
import { IProductDetail } from '~/types/product'

type Props = {
  product: IProductDetail;
  upsellIds?: number[];
}

const SimilarBottom = ({ product, upsellIds = [] }: Props) => {
  
  const hasUpsell = upsellIds.length > 0;

  // Query 1: Upsell
  const upsellQuery = useQuery({
    queryKey: ['product-upsell', upsellIds],
    queryFn: () => getProductsByIds({ ids: upsellIds }),
    enabled: hasUpsell, 
    staleTime: 1000 * 60 * 5,
  });

  // Query 2: Similar Biasa
  const similarQuery = useQuery({
    queryKey: ['product-similar', product.name],
    queryFn: () => getProductSimilar({ 
        name: product.name, 
        except: { productId: product.id } 
    }),
    enabled: !hasUpsell, 
    staleTime: 1000 * 60 * 5,
  });

  let products = [];
  let isLoading = false;

  // ==========================================
  // PERBAIKAN DI SINI
  // ==========================================
  if (hasUpsell) {
      // Salah: products = upsellQuery.data || [];
      // Benar: Ambil properti .products di dalamnya
      products = (upsellQuery.data as any)?.products || [];
      isLoading = upsellQuery.isLoading;
  } else {
      products = similarQuery.data?.products || []; 
      isLoading = similarQuery.isLoading;
  }

  if (!isLoading && products.length === 0) return null;

  return (
    <Skeleton
      isLoaded={!isLoading}
      rounded='lg'
      className='h-[350px]'
    >
      <ProductSlider products={products} productLayout='vertical' />
    </Skeleton>
  );
}

export default SimilarBottom;