import { useEffect, useState } from 'react';
import { Box, Typography, Button, FormControl, Select, MenuItem, InputBase } from '@mui/material';
import Grid from '@mui/material/Grid2';
import { styled } from "@mui/material";
//REDUX
import { useSelector, useDispatch } from 'react-redux';
import { fetchProducts, fetchProductsByCollection } from '../../redux/slices/productSlice';

//UTIL FUNCTION
function getAllTags(data) {
  const products = data || [];
  const allTags = products.flatMap(product => product.tags);
  const uniqueTags = [...new Set(allTags)];
  return uniqueTags;
}

const BootstrapInput = styled(InputBase)(({ theme }) => ({
  'label + &': {
    marginTop: theme.spacing(3),
  },
  '& .MuiInputBase-input': {
    position: 'relative',
    backgroundColor: "#2E2E2E",
    border: '1px solid #ced4da',
    color: "#FFF",
    fontSize: 13,
    padding: '5px 0',
    paddingRight: '50px !important',
    paddingLeft: "10px",
    transition: theme.transitions.create(['border-color', 'box-shadow']),
    '&:focus': {
      borderRadius: 4,
      borderColor: '#80bdff',
      boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
    },
  },
  '& .MuiSvgIcon-root': {
    color: "#FFF !important"
  },
}));

const ProductList = ({ size = 99999 }) => {

  const products = useSelector((state) => state.products.products.data) // only used as referenced
  const [filteredProducts, setFilteredProducts] = useState([]) // this one is the actual data to be rendered
  const [categoryFilterOption, setCategoryFilterOption] = useState([])
  const dispatch = useDispatch();

  //filter
  const [category, setCategory] = useState('all');
  const [sort, setSort] = useState('all')

  useEffect(() => {

    // if user come from select collection
    if (sessionStorage.getItem('amber-select-collection')) {

      let { id } = JSON.parse(sessionStorage.getItem('amber-select-collection'))
      dispatch(fetchProductsByCollection({ collectionId: id }))

    } else if (sessionStorage.getItem('amber-select-category')) {

    }

  }, [])

  useEffect(() => {

    let productType = sessionStorage.getItem('amber-select-product-type')
    let newFilteredProducts = products.filter(
      (product) => product.productType === productType
    );

    const categoryList = getAllTags(newFilteredProducts) // yes we use tags as category, while I was coding this, this is the only way to implement category

    setFilteredProducts(newFilteredProducts)
    setCategoryFilterOption(categoryList)

  }, [products])


  useEffect(() => {

    if (products?.length > 0) {

      let productType = sessionStorage.getItem('amber-select-product-type')

      let newFilteredProducts = products.filter(
        (product) => {

          if(category == 'all'){
            return product.productType === productType
          } else {
            return product.productType === productType && product.tags.includes(category)
          }

        }
      );

      setFilteredProducts(newFilteredProducts)

    }

  }, [category])



  useEffect(() => {
    if (products) console.log(products)
  }, [products])




  const handleChange = (event) => {
    //setInput({ ...input, [event.target.name]: event.target.value });
  };

  const renderProduct = (id, img_url, title, collection, price, currency, extra_desc) => {

    return (
      <Grid item size={{ xs: 6, sm: 6, md: 3 }}>
        <Box
          onClick={() => { window.location.href = `/products/${id}` }}
          sx={{
            overflow: 'hidden',
            position: 'relative',
            cursor: 'pointer'
          }}

        >
          <img
            src={img_url}
            alt={title}
            style={{
              width: '100%',
              aspectRatio: '3 / 4',
              objectFit: 'cover',
              objectPosition: 'top center'
            }}
          />

          {/* <Button sx={{ position: "absolute", top: 20, left: 20, boxShadow: 0 }} variant="contained">
            NEW
          </Button> */}

          <Box sx={{ py: 5 }}>
            <Typography variant="body2" >
              {collection}
            </Typography>
            <Typography variant="h5" sx={{ fontWeight: "bolder" }}>
              {title}
            </Typography>
            <Typography variant="body" >
              {`${currency} ${parseFloat(price).toFixed(2)}`}
            </Typography>
            <Typography variant="body2" sx={{ mt: 2 }}>
              {extra_desc}
            </Typography>
          </Box>
        </Box>
      </Grid>
    )

  }

  return (
    <>
      {/* FILTER */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          backgroundColor: "background.black",
          color: "white",
          px: 2, // Add padding around the box
          my: 4
        }}
      >
        {/* Left Side: Page Title */}
        <Typography variant="body2">
          {`${filteredProducts.length} Item`}
        </Typography>

        {/* Right Side: Option Inputs */}
        <Box sx={{ display: "flex", gap: 2 }}>

          <FormControl sx={{ m: 1, display: "flex", flexDirection: "row" }} variant="standard">
            <Typography variant="body2" sx={{ mr: 1, my: "auto" }}>Filter By Category</Typography>
            <Select
              value={category}
              onChange={(event) => {
                setCategory(event.target.value);
              }}
              input={<BootstrapInput />}
              name="type"
            >
              <MenuItem value={'all'}>All</MenuItem>
              {categoryFilterOption?.map((data) => (<MenuItem value={data}>{data}</MenuItem>))}
            </Select>
          </FormControl>

          <FormControl sx={{ m: 1, display: { xs: "none", sm: "none", md: "flex" }, flexDirection: "row" }} variant="standard">
            <Typography variant="body2" sx={{ mr: 1, my: "auto" }}>Sort By</Typography>
            <Select
              value={sort}
              onChange={handleChange}
              input={<BootstrapInput />}
              name="sort"
            >
              <MenuItem defaultValue value={''}>All</MenuItem>
              <MenuItem defaultValue value={'all'}>Newest</MenuItem>

            </Select>
          </FormControl>

        </Box>
      </Box>

      {/* LIST */}
      <Box sx={{ mb: 5 }}>
        <Grid container spacing={1} columns={12}>
          {filteredProducts.map((product, index) => {

            let { id, title, compareAtPriceRange, images, collections } = product
            let price = compareAtPriceRange.maxVariantPrice.amount
            let currency = compareAtPriceRange.maxVariantPrice.currencyCode
            let img_url = images.nodes[0].url
            let collection_name = collections.nodes[0]?.title

            // ID
            const parts = id.split('/');
            let prodID = parts[parts.length - 1];


            if (index < size) {
              return renderProduct(prodID, img_url, title, collection_name, price, currency, "")
            }

          })}
        </Grid>
      </Box>
    </>
  );
};

export default ProductList;
