import React, { useState } from 'react'
import { Row, Spin } from 'antd'

import ShopifyCollectionItem from 'components/ShopifyCollectionItem'
import InfiniteScroll from 'react-infinite-scroll-component'

interface ShopifyCollectionListProps {
  list?: any[]
  onSelectColection?: (uuid: string) => void
  fetchMoreCollections?: () => void
  hasMore?: boolean
}

const ShopifyCollectionList = ({
  list,
  onSelectColection,
  fetchMoreCollections,
  hasMore = false
}: ShopifyCollectionListProps) => {
  const [selected, setSelected] = useState<string>('')

  const handleSelectItem = (uuid: string) => {
    setSelected(uuid)
    onSelectColection && onSelectColection(uuid)
  }

  if (fetchMoreCollections) {
    return (
      <InfiniteScroll
        dataLength={list?.length ?? 0}
        next={fetchMoreCollections}
        hasMore={hasMore}
        loader={
          <Row justify="center" align="middle">
            <Spin />
          </Row>
        }
        height={300}
      >
        {list?.map((item, i) => (
          <Row key={i} onClick={() => handleSelectItem(item.id)}>
            <ShopifyCollectionItem
              imgUrl={item.image?.src || ''}
              name={item.title}
              isSelected={item.id === selected}
            />
          </Row>
        ))}
      </InfiniteScroll>
    )
  }

  return (
    <>
      {list?.map((item, i) => (
        <Row key={i} onClick={() => handleSelectItem(item.id)}>
          <ShopifyCollectionItem
            imgUrl={item.image?.src || ''}
            name={item.title}
            isSelected={item.id === selected}
          />
        </Row>
      ))}
    </>
  )
}

export default ShopifyCollectionList
