//React
import React, { FC, useEffect } from 'react'
import { 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 shopItemActionCreators } from '../../../store/reducers/ShopItem'

// Reactstrap
import { Container } from 'reactstrap'

// Components
import { FeatherIcon } from '../../../components/FeatherIcons'
import { RelatedProducts } from '../RelatedProducts'

const ShopItem : FC = () => {
  const params = useParams()
  const dispatch = useDispatch()

  const { content, shopItem } = useSelector((state: ApplicationState) => state)

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

  const {
    productSection = {
      availableQuantity: "",
      addToCart: ""
    }
  } = content?.shopItem ? content.shopItem : {}

  useEffect(() => {
    if(params?.slug)
      dispatch(shopItemActionCreators.requestShopItem({
        searchParams: {
          slug:  params.slug
        }
      }))
  }, [])

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




  return <>
    <section className="py-5">
      <Container fluid className="px-4 px-lg-5 my-5">
        <div className="row gx-4 gx-lg-5 align-items-center">
          <div className="col-md-6"><img className="card-img-top mb-5 mb-md-0" {...shopItem?.image} /></div>
          <div className="col-md-6">
            <div className="small mb-1">{`SKU: ${shopItem?.sku}`}</div>
            <h1 className="display-5 fw-bolder">{shopItem?.title}</h1>
            <div className="fs-5 mb-5">
              {shopItem?.newPrice
                ? <><span className="text-muted text-decoration-line-through">{currencySymbol}{shopItem.price.toFixed(2)}</span> <span>{currencySymbol}{shopItem.newPrice.toFixed(2)}</span></>
                : <span>{currencySymbol}{shopItem?.price.toFixed(2)}</span>}
            </div>

            <section dangerouslySetInnerHTML={{ __html: shopItem?.text ? shopItem.text : '' }}></section>
            
            <div className="d-flex pb-1">{productSection.availableQuantity} {shopItem?.quantity ? shopItem.quantity : 0}</div>

            <div className="d-flex">
              <input className="form-control text-center me-3" id="inputQuantity" type="num" value="1" style={{maxWidth: "3rem"}} />

              <button className="btn btn-outline-dark flex-shrink-0" type="button">
                <FeatherIcon icon='shopping-cart' className="me-1"/> {productSection.addToCart}</button>
            </div>
          </div>
        </div>
      </Container>
    </section>

    <RelatedProducts />
  </>
}

export {
  ShopItem
}