import { HttpTypes } from "@medusajs/types"
import ProductRail from "./product-rail"
import { listCollections } from "@lib/data/collections"
import { LayoutComponentDefinition, LayoutContext } from "@vibentec/component-map"

export default async function VtFeaturedProducts(props: {
  collections?: HttpTypes.StoreCollection[]
  region?: HttpTypes.StoreRegion
  countryCode?: string
  nodes?: LayoutComponentDefinition
  context?: LayoutContext
}) {
  let { collections, region, countryCode } = props
  const { nodes, context } = props

  if (context) {
    if (!region) region = context.region
    if (!countryCode) countryCode = context.countryCode
  }

  if (!collections && region) {
    const result = await listCollections({
      fields: "id, handle, title",
    })
    collections = result.collections
  }

  if (!collections || !region || !countryCode) {
    return null
  }

  const configTitle = nodes?.config?.title
  const styles = nodes?.config?.styles

  let displayCollections = collections
  if (configTitle) {
    displayCollections = collections.filter(
      (c) => c.handle === configTitle || c.title === configTitle
    )
  }

  return displayCollections.map((collection) => (
    <li key={collection.id}>
      <ProductRail
        collection={collection}
        region={region}
        countryCode={countryCode}
        styles={styles}
      />
    </li>
  ))
}
