import { Skeleton } from '@chakra-ui/react'
import { useQuery } from 'react-query'

import ProductCard from '~/modules/product-card'
// Import service
import { getProductSimilar, getProductsByIds } from '~/services/product'
// TAMBAHKAN 'IProduct' DISINI
import { IProduct, IProductDetail } from '~/types/product'

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

const SimilarSide = ({ product, relatedIds = [] }: Props) => {
  
  const hasRelated = relatedIds.length > 0;

  // 1. Fetch Related by ID
  const relatedQuery = useQuery({
    queryKey: ['product-related', relatedIds],
    queryFn: () => getProductsByIds({ ids: relatedIds }),
    enabled: hasRelated, 
    staleTime: 1000 * 60 * 5,
  });

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

  // ============================================================
  // PERBAIKAN: Definisikan tipe array secara eksplisit (IProduct[])
  // ============================================================
  let products: IProduct[] = []; 
  let isLoading = false;

  if (hasRelated) {
      // Cast ke any dulu jika tipe return service belum sempurna terdeteksi, lalu ambil products
      // Atau jika getProductsByIds me-return { products: IProduct[] }, ambil .products
      // Sesuai kode service terakhir, getProductsByIds me-return GetProductSimilarRes yg punya .products
      products = (relatedQuery.data as any)?.products || [];
      isLoading = relatedQuery.isLoading;
  } else {
      products = similarQuery.data?.products || [];
      isLoading = similarQuery.isLoading;
  }

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

  return (
    <Skeleton
      isLoaded={!isLoading}
      className="h-[500px] overflow-auto grid grid-cols-1 gap-y-4 divide-y divide-gray-300 border border-gray-300 rounded-lg p-2"
      rounded='lg'
    >
      {products.map((item) => (
        <div key={item.id} className="pt-2 first:pt-0">
            <ProductCard
              product={item}
              layout='horizontal'
            />
        </div>
      ))}
    </Skeleton>
  )
}

export default SimilarSide