import React, { useEffect } from 'react'
import { Box, Typography } from '@mui/material';
import { useParams } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import Grid from '@mui/material/Grid2';
import logoSrc from "../../assets/svg/logo.svg";
import ImageView from '../../components/ImageView/ImageView';
import ProductDetails from '../../components/ProductDetails';
import ProductSuggestion from '../../components/ProductSuggestion';
import ProductHistoryList from '../../components/ProductHistoryList';
import SocialMedia from '../../components/SocialMedia'
import Feature from '../../components/Feature'
import { fetchProduct } from '../../redux/slices/productSlice';

const Product = () => {

  let { pid } = useParams();
  const product = useSelector((state) => state.products.product.data)
  const dispatch = useDispatch();

  useEffect(() => {

    window.scrollTo({
      top: 0,
    });

    dispatch(fetchProduct(pid))

    if (localStorage.getItem('amber-product-history')) {

      let productHistory = JSON.parse(localStorage.getItem('amber-product-history'))

      if (productHistory.includes(pid)) return

      productHistory = [pid, ...productHistory]
      productHistory = productHistory.slice(0, 6)
      productHistory = JSON.stringify(productHistory)

      localStorage.setItem('amber-product-history', productHistory)

    } else {

      let productHistory = [pid]
      productHistory = JSON.stringify(productHistory)
      localStorage.setItem('amber-product-history', productHistory)

    }

  }, [])

  return (

    <Box sx={{
      px: {
        xs: 2,
        md: 5,
        lg: 5
      },
      mb: {
        xs: 0,
        md: 5,
        lg: 10
      }
    }}>
      <Grid container spacing={0} sx={{ mt: 10, mb: 5 }}>

        <Grid size={{ xs: 12, md: 6 }}>
          <Box sx={{ paddingRight: 1 }}>
            <Box>
              <ImageView />
            </Box>
          </Box>
        </Grid>

        <Grid size={{ xs: 12, md: 6 }}>
          <Box>
            <Box>
              <ProductDetails />
            </Box>
          </Box>
        </Grid>
      </Grid>

      <Box sx={{
        width: "100%",
        borderTop: "1px solid rgba(0,0,0,0.2)",
        py: 4,
        textAlign: "center"
      }}>
        <Typography variant='body1' sx={{ fontWeight: "400", mb: 4 }}>
          YOU MAY ALSO LIKE
        </Typography>

        <ProductSuggestion />

      </Box>

      <Box sx={{
        width: "100%",
        borderTop: "1px solid rgba(0,0,0,0.2)",
        py: 4,
        textAlign: "center"
      }}>
        <Typography variant='body1' sx={{ fontWeight: "400", mb: 4 }}>
          RECENTLY VIEWED
        </Typography>

        <ProductHistoryList />

      </Box>


      <SocialMedia />
      <Box sx={{
        display: {
          xs: "none",
          sm: "none",
          md: "block"
        }
      }}>
        <Feature />
      </Box>

    </Box>

  )
}

export default Product