import { useState, useEffect, useRef } from "react";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import Box from "@mui/material/Box";
import Header from "../Header";
import SearchIcon from "@mui/icons-material/Search";
import LocalMallIcon from '@mui/icons-material/LocalMall';
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import logoSrc from "../../assets/images/amberlogo.png";
import { styled } from '@mui/material/styles';
import { MenuItem, Select, FormControl, Badge, Typography } from '@mui/material';
import MobileNav from "./components/MobileNav";
import SideCart from "../SideCart/SideCart";
import MenuIcon from "@mui/icons-material/Menu";
import SearchProduct from "../SearchProduct"
import CategoryIcon from '@mui/icons-material/Category';
import HomeIcon from '@mui/icons-material/Home';
import BrushIcon from '@mui/icons-material/Brush';
import LoyaltyIcon from '@mui/icons-material/Loyalty';
import Grid from '@mui/material/Grid2';
import { useSelector, useDispatch } from 'react-redux';
import { fetchProducts } from "../../redux/slices/productSlice";
import ProductService from "../../services/ProductService";

import { Swiper, SwiperSlide } from 'swiper/react';
import { Scrollbar, A11y, Navigation } from 'swiper/modules';

import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';

function calculateTotalQuantity(cartItems) {
  return cartItems.reduce((total, item) => total + item.quantity, 0);
}

const LanguageSelect = styled(Select)(({ theme }) => ({
  backgroundColor: 'black',
  color: 'white',
  border: '1px solid black',
  fontSize: 12,
  '& .MuiSelect-icon': {
    color: 'white',
  },
  '&:hover': {
    backgroundColor: 'white',
    color: 'black',
  },
  '& .MuiMenuItem-root': {
    backgroundColor: 'black',
    color: 'white',
  },
  '& .MuiMenuItem-root:hover': {
    backgroundColor: 'white',
    color: 'black',
  },
}));

const LanguageSelectItem = styled(MenuItem)(() => ({
  backgroundColor: 'black',
  color: 'white',
  '&:hover': {
    backgroundColor: 'white',
    color: 'black',
  },
}));

function mapProductTypesWithCollections(products) {
  // Create a Map to group collections by productType
  const productTypeMap = new Map();

  products.forEach(product => {
    const { productType, collections } = product;

    // If productType already exists, merge its collections
    if (productTypeMap.has(productType)) {
      const existingCollections = productTypeMap.get(productType);
      const newCollections = collections.map(collection => collection);
      productTypeMap.set(productType, [...new Set([...existingCollections, ...newCollections])]);
    } else {
      // Add a new productType with its collections
      productTypeMap.set(productType, collections.map(collection => collection));
    }
  });

  // Convert the Map into the desired array structure
  return Array.from(productTypeMap, ([productType, collection]) => ({ productType, collection }));
}

function getUniqueCollections(data) {
  return data.map(item => {
    // Use a Map to store unique collection titles with their corresponding image
    const uniqueCollectionsMap = new Map();
    item.collection.forEach(({ title, image, updatedAt }) => {
      if (!uniqueCollectionsMap.has(title)) {
        uniqueCollectionsMap.set(title, { title, image, updatedAt });
      }
    });

    // Convert the Map back to an array
    return {
      productType: item.productType,
      collection: Array.from(uniqueCollectionsMap.values())
    };
  });
}

const Navbar = () => {

  const swiperRef = useRef(null); // Create a ref for the Swiper instance
  const [showHeader, setShowHeader] = useState(true);
  const [showSearch, setShowSearch] = useState(false);
  const [isAtTop, setIsAtTop] = useState(false);
  const [isProductPage, setIsProductPage] = useState(false);
  const [lastScrollPos, setLastScrollPos] = useState(0);
  const [language, setLanguage] = useState('English');
  const dispatch = useDispatch();

  const cart = useSelector((state) => state.cart.cart)
  const products = useSelector((state) => state.products.products.data)
  const [cartAmount, setCartAmount] = useState(0);

  const [openSideMenu, setOpenSideMenu] = useState(false);
  const [openSideCart, setOpenSideCart] = useState(false);
  const [navItem, setNavItem] = useState([]);

  const [displayCollection, setDisplayCollection] = useState({
    productType: null,
    list: []
  })

  useEffect(() => {

    dispatch(fetchProducts())
    if (window.location.pathname === "/") setIsAtTop(true);

    const handleScroll = () => {
      if (window.location.pathname === "/") setIsAtTop(window.scrollY < 20);
    };

    window.addEventListener("scroll", handleScroll);

    // Cleanup on component unmount
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };

  }, [])

  useEffect(() => {

    if (!cart?.lines?.nodes) return // don't need to do anything if we have no cart data

    setCartAmount(calculateTotalQuantity(cart?.lines?.nodes))

  }, [cart])

  useEffect(() => {

    //Navbar item are based on products type, thus get all the item and then we should be good
    if (products.length > 0) {

      let navItemData = mapProductTypesWithCollections(products)
      navItemData = getUniqueCollections(navItemData)
      setNavItem(navItemData)

    }

  }, [products])

  const handleChange = (event) => {
    setLanguage(event.target.value);
  };

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollPos = window.scrollY;

      if (currentScrollPos > lastScrollPos && currentScrollPos > 50) setShowHeader(false)
      else setShowHeader(true)

      setLastScrollPos(currentScrollPos);
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, [lastScrollPos]);

  const renderCollectionDisplay = (colletion) => {

    return (
      <SwiperSlide>
        <Box
          className="animate__animated animate__fadeIn animate__fast"
          sx={{
            backgroundImage: `url(${colletion?.image?.url})`,
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
            backgroundPosition: "center center",
            height: "100%",
            paddingTop: "85%",
            position: "relative",
            cursor: "pointer",
            transition: "transform 0.3s ease",
          }}
          onClick={() => {
            sessionStorage.setItem('amber-select-collection', JSON.stringify(colletion))
            sessionStorage.setItem('amber-select-product-type', displayCollection.productType)
            window.location.href = `/products`;
          }}
        ></Box>
        <Typography
          variant="body1"
          sx={{
            mt:1,
            color: "black",
            fontWeight: "100",
            fontSize: {
              xs: "0.73rem",
              sm: "0.73rem",
              md: "0.875rem",
            },
          }}
        >
          {colletion?.title?.toUpperCase()}
        </Typography>
      </SwiperSlide>
    )

  }

  const swipeToLeft = () => {
    if (swiperRef.current) {
      swiperRef.current.slidePrev(); // Move to the previous slide
    }
  };

  const swipeToRight = () => {
    if (swiperRef.current) {
      swiperRef.current.slideNext(); // Move to the previous slide
    }
  };

  const displayCollectionList = (collection = [], productType) => {

    
    collection = collection.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt) )

    setDisplayCollection([])
    setTimeout(() => {
      setDisplayCollection({
        productType,
        list: collection
      })
    }, 100);
  }

  const hideCollectionList = () => {
    setDisplayCollection([])
  }

  return (
    <>
      <AppBar position="fixed"
        sx={{
          zIndex: 998,
          backgroundColor: (isAtTop) ? "rgba(0, 0, 0, 0)" : "rgba(255, 255, 255, 0.3)",
          backdropFilter: (isAtTop) ? "none" : "blur(10px)",
          boxShadow: 0,
          transition: "all 0.2s ease-in-out",
          ":hover": {
            backgroundColor: "rgba(255,255,255,1) !important",
            backdropFilter: "none !important",
            '& .navItem': {
              color: "black !important"
            },
            '& .navItem:hover': {
              color: "#95AAC5 !important"
            },
          }
        }}
        onMouseLeave={() => {
          hideCollectionList()
        }}
      >

        {/* Conditionally render the Header */}
        {showHeader && <Header />}

        <Toolbar sx={{
          px: {
            xs: 2,
            md: 6,
            lg: 6
          },
          py: 0.5
        }} disableGutters>

          <Box sx={{ display: "flex", alignItems: "center", width: "100%", position: "relative", justifyContent: "space-between" }}>
            {/* SIDEBAR BUTTON */}
            <Box sx={{
              display: {
                xs: "block",
                md: "block",
                lg: "none"
              }
            }}>

              <IconButton
                onClick={() => setOpenSideMenu(true)}
                className="navItem"
                sx={{
                  backgroundColor: "transparent",
                  color: (isAtTop) ? "white" : "black",
                  "&:hover": {
                    backgroundColor: "rgba(0, 0, 0, 0.1)",
                  },
                }}
              >
                <MenuIcon fontSize="large" />
              </IconButton>

            </Box>

            {/* Left Section: Logo */}
            <Box
              sx={{
                mr: {
                  xs: 0,
                  sm: 0,
                  md: 10,
                  lg: 10,
                  xl: 10
                },
                display: {
                  xs: (isProductPage) ? "flex" : "none",
                  md: (isProductPage) ? "flex" : "none",
                  lg: "flex"
                },
              }}
            >
              <a href="/">
                <img src={logoSrc} alt="Logo"
                  style={{
                    width: 130,
                    height: 20,
                  }} />
              </a>
            </Box>

            {/* Center Section: Nav Items */}
            <Box
              sx={{
                flexGrow: 1,
                display: {
                  xs: "none",
                  md: "none",
                  lg: "flex"
                },
                gap: 2
              }}
            >

              {navItem.map(({ productType, collection }) => (<Button
                sx={{
                  position: "relative",
                  ':hover': {
                    backgroundColor: "rgba(0,0,0,0)",
                  }
                }}
                color="inherit"
                onClick={() => {
                  sessionStorage.setItem('amber-select-product-type', productType)
                  sessionStorage.removeItem('amber-select-collection')
                  window.location.href = `/products`;
                }}
                onMouseEnter={() => {
                  displayCollectionList(collection, productType)
                }}
              >
                <Typography variant="body2"
                  className="navItem"
                  sx={{
                    fontSize: {
                      xs: "0.73rem",
                      sm: "0.73rem",
                      md: "0.875rem",
                    },
                    color: (isAtTop) ? "white" : "black",
                    transition: "all 0.3s ease-in-out",
                    ":hover": {
                      color: "#95AAC5 !important"
                    },
                    "&::after": {
                      content: '""',
                      position: "absolute",
                      left: "50%",
                      transform: "translateX(-50%)",
                      bottom: 2,
                      width: "0%",
                      height: "2px", // Thickness of the underline
                      backgroundColor: "#95AAC5",
                      transition: "width 0.3s ease-in-out",
                    },
                    ":hover::after": {
                      width: "50%", // Expands on hover
                    },
                  }}>{productType}</Typography>
              </Button>))}

            </Box>

            {/* Right Section: Search and Profile */}
            <Box sx={{ display: "flex", alignItems: "center", gap: 1.2 }}>

              {/* <FormControl
                sx={{
                  display: {
                    xs: "none",
                    lg: "block"
                  }
                }}
              >
                <LanguageSelect
                  value={language}
                  onChange={handleChange}
                  label=""
                  MenuProps={{
                    PaperProps: {
                      style: {
                        backgroundColor: 'black',
                        color: 'white'
                      },
                    },
                  }}
                >
                  <LanguageSelectItem value="English">English</LanguageSelectItem>
                  <LanguageSelectItem value="Malay">Malay</LanguageSelectItem>
                  <LanguageSelectItem value="Chinese">Chinese</LanguageSelectItem>
                </LanguageSelect>
              </FormControl> */}

              <IconButton onClick={() => { setShowSearch(true) }}>
                <SearchIcon className="navItem" style={{
                  transition: "all 0.3s ease-in-out",
                  color: (isAtTop) ? "white" : "black",
                }} />
              </IconButton>

              <Badge
                sx={{ cursor: "pointer" }}
                onClick={() => { setOpenSideCart(true) }}
                badgeContent={cartAmount} color="primary">
                <LocalMallIcon className="navItem" style={{
                  transition: "all 0.3s ease-in-out",
                  color: (isAtTop) ? "white" : "black",
                }} />
              </Badge>
              {/* <IconButton color="inherit">
                <AccountCircleIcon sx={{ color: "white" }} />
              </IconButton> */}
            </Box>
          </Box>
        </Toolbar>

        {/* On Hover Collection */}
        <Box className="animate__animated animate__fadeIn" sx={{ backgroundColor: "white", position: "relative", py: 5, display: (displayCollection?.list?.length > 0) ? "block" : "none" }}>
          <ChevronLeftIcon
            style={{
              cursor: "pointer",
              color: "black",
              position: "absolute",
              top: "50%",
              fontSize: 50,
              left: 40,
              transform: "translateY(-50%)",
            }}
            onClick={swipeToLeft}
          />

          <Box sx={{ px: 20 }}>
            <Swiper
              modules={[Navigation, Scrollbar, A11y]}
              spaceBetween={20}
              slidesPerView={4}
              pagination={{ clickable: true }}
              scrollbar={{ draggable: true }}
              onSwiper={(swiper) => (swiperRef.current = swiper)}
            >
              {displayCollection?.list?.map((colletion) => {
                return renderCollectionDisplay(colletion)
              })}

            </Swiper>
          </Box>

          <KeyboardArrowRightIcon
            style={{
              cursor: "pointer",
              color: "black",
              fontSize: 50,
              position: "absolute",
              top: "50%",
              right: 40,
              transform: "translateY(-50%)",
            }}
            onClick={swipeToRight}
          />
        </Box>

      </AppBar>
      {showSearch && <SearchProduct onClose={() => { setShowSearch(false) }} />}

      <MobileNav open={openSideMenu} menu={navItem} onClose={() => { setOpenSideMenu(false) }} />
      <SideCart open={openSideCart} onClose={() => { setOpenSideCart(false) }} />

    </>
  );
};

export default Navbar;
