import * as React from "react";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import SwipeableDrawer from "@mui/material/SwipeableDrawer";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
import Avatar from "@mui/material/Avatar";
import Container from "@mui/material/Container";
import Button from "@mui/material/Button";
import Tooltip from "@mui/material/Tooltip";
import MenuItem from "@mui/material/MenuItem";
import Menu from "@mui/material/Menu";
import MenuIcon from "@mui/icons-material/Menu";
import CloseIcon from "@mui/icons-material/Close";   // <-- Added
import Divider from "@mui/material/Divider";
import AdbIcon from "@mui/icons-material/Adb";
import ListItemIcon from "@mui/material/ListItemIcon";
import { InboxIcon, MailIcon } from "lucide-react";
import LazyImage from "./LazyImage";
import Logo from "../../assets/images/logo.png"
import { Navigate, useNavigate } from "react-router-dom";
const pages = ["Matches", "Search", "Help"];
const settings = ["Profile", "Account", "Dashboard", "Logout"];


import { useState, useRef, useEffect } from 'react';
import { Home, Search, Heart, MessageCircle, User, Settings } from 'lucide-react';
const NAV_LINKS = [
  { label: "Home", path: "/", icon: <Home /> },
  { label: "Matches", path: "/matches", icon: <InboxIcon /> },
  { label: "Search", path: "/search", icon: <Search /> },
  { label: "Chat", path: "/chat", icon: <MessageCircle /> }
]

// Sparkle Navbar Component
const SparkleNavbar = ({ items, color = "#0fec1eff", onItemClick }) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [indicatorStyle, setIndicatorStyle] = useState({});
  const [isAnimating, setIsAnimating] = useState(false);
  const navRef = useRef(null);
  const buttonRefs = useRef([]);

  useEffect(() => {
    updateIndicator(activeIndex);
  }, []);

  const updateIndicator = (index) => {
    const button = buttonRefs.current[index];
    if (button && navRef.current) {
      const navRect = navRef.current.getBoundingClientRect();
      const btnRect = button.getBoundingClientRect();
      setIndicatorStyle({
        left: btnRect.left - navRect.left + btnRect.width / 2 - 18,
        opacity: 1
      });
    }
  };

  const handleClick = (index) => {
    if (index === activeIndex || isAnimating) return;
    setIsAnimating(true);
    const newButton = buttonRefs.current[index];
    
    if (newButton && navRef.current) {
      const navRect = navRef.current.getBoundingClientRect();
      const newRect = newButton.getBoundingClientRect();
      
      setIndicatorStyle(prev => ({
        ...prev,
        left: newRect.left - navRect.left + newRect.width / 2 - 18,
      }));
      
      setTimeout(() => {
        setActiveIndex(index);
        setIsAnimating(false);
        if (onItemClick) onItemClick(items[index], index);
      }, 300);
    }
  };

  return (
    <nav ref={navRef} className="relative flex items-center gap-8 px-6 py-4">
      {items.map((item, index) => (
        <button
          key={item}
          ref={el => buttonRefs.current[index] = el}
          onClick={() => handleClick(index)}
          className={`cursor-pointer relative uppercase text-sm font-medium transition-all duration-300 pb-2 ${
            activeIndex === index ? 'text-black' : 'text-gray-900 hover:text-gray-600'
          }`}
          style={{
            textShadow: activeIndex === index 
              ? `0 0 10px ${color}, 0 0 20px ${color}, 0 0 30px ${color}` 
              : 'none'
          }}
        >
          {item}
        </button>
      ))}
      
      {/* Underline only - no dots */}
      <div
        className="absolute bottom-3 h-[3px] w-9 rounded-full transition-all duration-300 ease-out"
        style={{
          left: indicatorStyle.left,
          opacity: indicatorStyle.opacity,
          backgroundColor: color,
          boxShadow: `0 0 10px ${color}, 0 0 20px ${color}, 0 0 30px ${color}, 0 0 40px ${color}`,
        }}
      />
    </nav>
  );
};


const LandingHeader = () => {
  const navigate = useNavigate();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [anchorElUser, setAnchorElUser] = React.useState(null);
 const [selectedItem, setSelectedItem] = useState('Home');
  const toggleDrawer = (open) => () => {
    setDrawerOpen(open);
  };

  const handleOpenUserMenu = (event) => {
    setAnchorElUser(event.currentTarget);
  };
  const handleCloseUserMenu = () => {
    setAnchorElUser(null);
  };

  const DrawerList = (
    <Box
      sx={{ width: 250 }}
      role="presentation"
      onKeyDown={toggleDrawer(false)}
    >
      {/* Drawer Header + Close Button */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          px: 2,
          py: 1.5,
        }}
      >
        <Typography variant="h6">Menu</Typography>

        {/* Close Button */}
        <IconButton onClick={toggleDrawer(false)}>
          <CloseIcon />
        </IconButton>
      </Box>

      <Divider />

      <List>
       {NAV_LINKS.map(({ label, path, icon }) => (
          <ListItem key={label} disablePadding>
            <ListItemButton onClick={() => {
              navigate(path);
              toggleDrawer(false)();
            }}>
              <ListItemIcon>{icon}</ListItemIcon>
              <ListItemText primary={label} />
            </ListItemButton>
          </ListItem>
        ))}
      </List>

      {/* <Divider />

      <List>
        {["All mail", "Trash", "Spam"].map((text, index) => (
          <ListItem key={text} disablePadding>
            <ListItemButton>
              <ListItemIcon>
                {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
              </ListItemIcon>
              <ListItemText primary={text} />
            </ListItemButton>
          </ListItem>
        ))}
      </List> */}
    </Box>
  );

  return (
    <>
      <AppBar position="sticky" sx={{ backgroundColor: "#fff" }}>
        <Container maxWidth="xl">
          <Toolbar disableGutters>
            {/* Desktop Logo */}
            {/* <Typography
              variant="h6"
              noWrap
              component="a"
              href="#"
              sx={{
                mr: 2,
                display: { xs: "none", md: "flex" },
                fontFamily: "monospace",
                fontWeight: 700,
                letterSpacing: ".3rem",
                color: "#000000",
                textDecoration: "none",
                position:"sticky",
                zIndex:"99"
              }}
            >
              LOGO
            </Typography> */}
<Box sx={{ display: { xs: "none", md: "flex" }, mr: 1 }}>

            <LazyImage
                    src={Logo}
                    className="w-full h-[50px] rounded-lg object-cover "
                  />
</Box>
            {/* Mobile Drawer Button */}
            <Box sx={{ flexGrow: 1, display: { xs: "flex", md: "none" } }}>
              <IconButton size="large" color="#000000" onClick={toggleDrawer(true)}>
                <MenuIcon />
              </IconButton>
            </Box>

            {/* Mobile Logo */}
            <Box sx={{ display: { xs: "flex", md: "none" }, mr: 1 ,flexGrow: 1,}}>
             <LazyImage
                    src={Logo}
                    className="w-full h-[50px] rounded-lg object-cover "
                    onClick={()=> navigate("/")}
                  />
</Box>
            {/* <Typography
              variant="h5"
              noWrap
              component="a"
              href="#"
              sx={{
                mr: 2,
                display: { xs: "flex", md: "none" },
                flexGrow: 1,
                fontFamily: "monospace",
                fontWeight: 700,
                letterSpacing: ".3rem",
                color: "#000000",
                textDecoration: "none",
              }}
            >
              LOGO
            </Typography> */}

            {/* Desktop Menu */}
            <Box sx={{ flexGrow: 1, display: { xs: "none", md: "flex", marginLeft:"20px" } }}>
              {/* {pages.map((page) => (
                <Button key={page} sx={{ my: 2, color: "#000000", display: "block" }}>
                  {page}
                </Button>
              ))} */}

               <SparkleNavbar 
           items={NAV_LINKS.map(link => link.label)}
            color="#034E08"
           onItemClick={(label) => {
    setSelectedItem(label);
    const link = NAV_LINKS.find(l => l.label === label);
    if (link) navigate(link.path);
  }}
          />
            </Box>

            {/* Avatar Menu */}
            <Box sx={{ flexGrow: 0 }}>
              <Tooltip title="Open settings">
                <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
                  <Avatar alt="User" src="/static/images/avatar/2.jpg" />
                </IconButton>
              </Tooltip>
              <Menu
                sx={{ mt: "45px" }}
                anchorEl={anchorElUser}
                open={Boolean(anchorElUser)}
                onClose={handleCloseUserMenu}
                anchorOrigin={{ vertical: "top", horizontal: "right" }}
                transformOrigin={{ vertical: "top", horizontal: "right" }}
              >
                {settings.map((setting) => (
                  <MenuItem key={setting} onClick={handleCloseUserMenu}>
                    <Typography textAlign="center">{setting}</Typography>
                  </MenuItem>
                ))}
              </Menu>
            </Box>
          </Toolbar>
        </Container>
      </AppBar>

      {/* Drawer */}
      <SwipeableDrawer
        anchor="left"
        open={drawerOpen}
        onClose={toggleDrawer(false)}
        onOpen={toggleDrawer(true)}
      >
        {DrawerList}
      </SwipeableDrawer>
    </>
  );
};

export default LandingHeader;
