// React
import React, { FC, useEffect } from "react"

// Reduc
import { useDispatch, useSelector } from "react-redux"
import { ApplicationState } from "../../../store"
import { actionCreators as loaderActionCreators } from '../../../store/reducers/Loader'

// Reactstrap
import { Card, CardBody, CardFooter, CardImg, Col, Container, Row } from "reactstrap"

// Components
import { FeatherRating } from "../../../components/FeatherRating"

const RelatedProducts: FC = () => {
  const dispatch = useDispatch()

  const { content, shopRelated } = useSelector((state: ApplicationState) => state)
  
  const {
    currencySymbol = ""
  } = content?.localization ? content.localization : {}

  const {
    relatedProductsSection = {
      title: "",
      addToCart: ""
    }
  } = content?.shopItem ? content?.shopItem : {}

  const {
    items = []
  } = shopRelated ? shopRelated : {}

  useEffect(() => {
    content?.isLoading || shopRelated?.isLoading
      ? dispatch(loaderActionCreators.show())
      : setTimeout(() => {
        dispatch(loaderActionCreators.hide())
      }, 1000)
  }, [content?.isLoading, shopRelated?.isLoading])

  return <section className="py-5 bg-light">
    <Container fluid className="px-4 px-lg-5">
      <h2 className="fw-bolder mb-4">{relatedProductsSection.title}</h2>

      <Row className="gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center">
        {items.map((item, index) => <Col key={index} className="mb-5">
          <Card className="h-100">
            <div className="position-absolute" style={{top: "0.5rem", right: "0.5rem"}}>
              {(item?.badges ? item.badges : []).map((badge, index) => <div key={index} className="badge bg-dark text-white" style={{marginLeft: "0.5rem"}}>{badge}</div>) }
            </div>
            <CardImg className="card-img-top" {...item.image} />
            <CardBody className="p-4">
              <div className="text-center">
                  
                <h5 className="fw-bolder">{item.title}</h5>
                <FeatherRating {...{
                  value: item?.rating ? item.rating : 0
                }} />

                {item.newPrice
                  ? <><span className="text-muted text-decoration-line-through">{currencySymbol}{item.price.toFixed(2)}</span> <span>{currencySymbol}{item.newPrice.toFixed(2)}</span></>
                  : <span>{currencySymbol}{item.price.toFixed(2)}</span>}
              </div>
            </CardBody>
            <CardFooter className="p-4 pt-0 border-top-0 bg-transparent">
              <div className="text-center"><a className="btn btn-outline-dark mt-auto" href="#">{relatedProductsSection.addToCart}</a></div>
            </CardFooter>
          </Card>
        </Col>)}
      </Row>
    </Container>
  </section>
}

export {
  RelatedProducts
}