// React
import React, { FC, useEffect } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'

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

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

// Models (interfaces)
import { ShopItemModel } from '../../../models'
import { TitleSectionModel } from '../../../models/pageSections'

// Custom components
import { FeatherRating } from '../../../components/FeatherRating'
import { Pagination } from '../../../components/Pagination'

// Functions
import { findRoutes } from '../../../functions'

const TitleSection: FC<TitleSectionModel> = ({
  title = "",
  text = ""
}) => <header className="bg-dark py-5">
  <Container fluid className="px-4 px-lg-5 my-5">
    <div className="text-center text-white">
      <h1 className="display-4 fw-bolder">{title}</h1>
      <p className="lead fw-normal text-white-50 mb-0">{text}</p>
    </div>
  </Container>
</header>


interface ShopItems {
  currencySymbol: string,
  addToCart: string,
  path: string
  totalPages?: number,
  currentPage?: number,
  items?: ShopItemModel []
}

const ShopItemsSection: FC<ShopItems> = ({
  currencySymbol = "",
  addToCart = "",
  path = "",
  totalPages = 1,
  currentPage = 1,
  items = []
}) => {

  const dispatch = useDispatch()
  const navigate = useNavigate()

  return <section className="py-5">
    <Container fluid className="px-4 px-lg-5 mt-5">
      <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>

            <Link to={`${path}/${currentPage}/${item.slug}`}>
              <CardImg top {...item.image} />
            </Link>
          
            <CardBody>
              <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="#">{addToCart}</a></div>
            </CardFooter>
          </Card>
        </Col>)}
      </Row>

      <Pagination {...{
        totalPages: totalPages,
        currentPage: currentPage,
        onClick: (nextPage) => {
          dispatch(shopCatalogActionCreators.requestShopCatalog({
            searchParams: {
              currentPage: nextPage + ""
            }
          }))

          navigate(`${path}/${nextPage}`)
        }
      }} />
    </Container>
  </section>
}


const ShopCatalog = () => {
  const params = useParams()
  const dispatch = useDispatch()

  const { content, shopCatalog } = useSelector((state: ApplicationState) => state)
  const page = content?.shopCatalog
  const path = findRoutes(content?.routes, 'ShopCatalog')[0]?.targets[0]

  const {
    currencySymbol = ""
  } = content?.localization ? content.localization : {}

  useEffect(() => {
    dispatch(shopCatalogActionCreators.requestShopCatalog({
      searchParams: {
        currentPage: params?.page ? params.page : "1"
      }
    }))
  }, [])

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

  const {
    shopItemsSection = {
      addToCart: ""
    }
  } = content?.shopCatalog ? content?.shopCatalog : {}

  const shopItems: ShopItems = {
    currencySymbol,
    path,
    ...shopItemsSection,
    ...shopCatalog
  }

  return <>
    <TitleSection {...page?.titleSection} />
    <ShopItemsSection {...shopItems} />
  </>
}

export {
  ShopCatalog
}