// components/HeaderSection.tsx
import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import {
  AppBar,
  Box,
  Button,
  Toolbar,
  Typography,
  IconButton,
  Menu,
  MenuItem,
  Paper,
  Stack,
  Divider,
  Badge,
} from "@mui/material";
import ShoppingCartIcon from "@mui/icons-material/ShoppingCart";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";

interface Category {
  id: string;
  name: string;
  image: string;
  description: string;
  count: number;
}

const categories: Category[] = [
  {
    id: "chairs",
    name: "Premium Seating",
    image: "/images/chair-category.jpg",
    description: "Ergonomic masterpieces",
    count: 28,
  },
  {
    id: "luxury-chairs",
    name: "Luxury Chairs",
    image: "/images/luxury-chair.jpg",
    description: "Opulent designs",
    count: 15,
  },
  {
    id: "premium-beds",
    name: "Premium Beds",
    image: "/images/bed-category.jpg",
    description: "Sleep in comfort",
    count: 12,
  },
  {
    id: "designer-sofas",
    name: "Designer Sofas",
    image: "/images/sofa-category.jpg",
    description: "Statement pieces",
    count: 22,
  },
];

const HeaderSection: React.FC = () => {
  const location = useLocation();
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [headerBg, setHeaderBg] = useState("transparent");
  const [cartItems] = useState(3);

  // Dynamic background based on route
  useEffect(() => {
    const path = location.pathname;
    if (
      path === "http://localhost:3001" ||
      path === "/" ||
      path === "/home" ||
      path === "/cat"
    ) {
      setHeaderBg("transparent");
    } else if (
      path.startsWith("/categories/") ||
      path.startsWith("/product/")
    ) {
      setHeaderBg("black");
    } else {
      setHeaderBg("transparent");
    }
  }, [location.pathname]);

  // Menu handlers - simplified
  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);

  return (
    <AppBar
      position="static"
      sx={{
        background:
          headerBg === "rgba(0, 0, 0, 0)"
            ? "rgba(0, 0, 0, 0.5)"
            : "rgba(0, 0, 0, 0.9)",
        backdropFilter: "blur(10px)",
        transition: "background 0.3s ease",
      }}
    >
      <Toolbar
        sx={{ justifyContent: "space-between", px: { xs: 2, md: 4 }, py: 1 }}
      >
        {/* Logo */}
        <Typography variant="h4" sx={logoStyles}>
          PANTO
        </Typography>

        {/* Navigation */}
        <Box sx={{ display: { xs: "none", md: "flex" }, gap: 3, mx: 4 }}>
          <Button sx={navButtonStyles}>Home</Button>

          {/* Furniture Dropdown - Fixed */}
          <Box>
            <Button
              endIcon={<KeyboardArrowDownIcon />}
              onClick={handleMenuOpen}
              sx={{
                ...navButtonStyles,
                color: open ? "primary.main" : "white",
              }}
              aria-controls="furniture-menu"
              aria-haspopup="true"
              aria-expanded={open ? "true" : undefined}
            >
              Furniture
            </Button>
            <Menu
              id="furniture-menu"
              anchorEl={anchorEl}
              open={open}
              onClose={handleMenuClose}
              MenuListProps={{ sx: { p: 0 } }}
              PaperProps={{
                sx: menuPaperStyles,
              }}
              anchorOrigin={{
                vertical: "bottom",
                horizontal: "center",
              }}
              transformOrigin={{
                vertical: "top",
                horizontal: "center",
              }}
            >
              <Stack
                direction="row"
                spacing={4}
                divider={<Divider orientation="vertical" flexItem />}
              >
                <Box sx={{ width: "30%" }}>
                  <Typography variant="h6" sx={{ mb: 2, fontWeight: "bold" }}>
                    Shop By Category
                  </Typography>
                  <Stack spacing={1}>
                    {categories.map((category) => (
                      <MenuItem
                        key={category.id}
                        onClick={handleMenuClose}
                        sx={menuItemStyles}
                      >
                        <Box sx={categoryItemStyles}>
                          <Box
                            component="img"
                            src={category.image}
                            sx={categoryImageStyles}
                            alt={category.name}
                          />
                          <Box>
                            <Typography>{category.name}</Typography>
                            <Typography
                              variant="caption"
                              color="text.secondary"
                            >
                              {category.count} items
                            </Typography>
                          </Box>
                        </Box>
                      </MenuItem>
                    ))}
                  </Stack>
                </Box>
                {/* ... rest of the menu content ... */}
              </Stack>
            </Menu>
          </Box>

          <Button sx={navButtonStyles}>About Us</Button>
          <Button sx={navButtonStyles}>Contact</Button>
        </Box>

        {/* Shopping Cart */}
        <IconButton sx={{ color: "white" }}>
          <Badge badgeContent={cartItems} color="primary">
            <ShoppingCartIcon fontSize="medium" />
          </Badge>
        </IconButton>
      </Toolbar>
    </AppBar>
  );
};

// Styles extracted for better readability
const logoStyles = {
  fontWeight: "bold",
  color: "white",
  fontFamily: "'Playfair Display', serif",
  letterSpacing: "1px",
};

const navButtonStyles = {
  color: "white",
  fontSize: "1rem",
  textTransform: "none",
  "&:hover": { color: "primary.main" },
};

const menuPaperStyles = {
  width: "80vw",
  maxWidth: "1200px",
  overflow: "visible",
  mt: 2,
  p: 3,
  bgcolor: "background.paper",
  boxShadow: "0px 10px 30px rgba(0, 0, 0, 0.2)",
  "&:before": {
    content: '""',
    display: "block",
    position: "absolute",
    top: 0,
    left: "50%",
    width: 12,
    height: 12,
    bgcolor: "background.paper",
    transform: "translateY(-50%) rotate(45deg)",
    zIndex: 0,
  },
};

const menuItemStyles = {
  px: 0,
  py: 1,
  "&:hover": { color: "primary.main" },
};

const categoryItemStyles = {
  display: "flex",
  alignItems: "center",
};

const categoryImageStyles = {
  width: 40,
  height: 40,
  objectFit: "cover",
  borderRadius: 1,
  mr: 2,
};

export default HeaderSection;
