import React, {
  FC,
  useState
} from "react"

import {
  formatClassList,
  removeUniqueValueFromArray
} from '../../utils'

import SelectCard from './select-card'

import './select-card.css'


type SelectCardsTypes = {
  className?: string,
  other?: unknown,
  multiple?: boolean,
  cardData: CardTypes[]
}

type CardTypes = {
  id: string,
  title: string,
  description: string,
  price: string
}

const CARDS: string = `
  p-4
  inline-block
`

const SelectCards:FC<SelectCardsTypes> = ({
  className,
  cardData,
  multiple,
  ...other
}: SelectCardsTypes) => {

  const cardsClassList = formatClassList(CARDS)

  const [selected, setSelected] = useState<number[]>([])

  const handleSelection = (select: boolean, index: number): void => {
    if (multiple) {
      if (select) {
        setSelected(selected => [...selected, index])
        return
      }

      if (selected.includes(index)) {
        setSelected(selected => removeUniqueValueFromArray(selected, index))
        return
      }

      return
    }

    if (select) {
      setSelected([index])
      return
    }

    setSelected([])
  }

  return (
    <>
      {
        cardData.map((card: CardTypes, index: number) => (
          <div className={cardsClassList} key={`card-${index}`} {...other}>
            <SelectCard
              cardData={card}
              selected={selected && selected.includes(index)}
              setSelected={(select: boolean) => handleSelection(select, index)}
            />
          </div>
        ))
      }
    </>
  )
}

export default SelectCards
