import React, { useState, useEffect } from "react";
import {
  AppBar,
  Toolbar,
  Button,
  Container,
  Box,
  IconButton,
  Menu,
  MenuItem,
  useScrollTrigger,
  Divider,
} from '@mui/material';
import MenuIcon from '@mui/icons-material/Menu';
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
import Image from "next/image";
import Link from "next/link";
import sempreg from "../../assets/img/sempreg.png";

function ElevationScroll(props) {
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 0,
  });

  return React.cloneElement(props.children, {
    elevation: trigger ? 4 : 0,
  });
}

function CompMenuprincipal({ darkMode, onToggleDarkMode }) {
  const [anchorEl, setAnchorEl] = useState(null);
  const [isScrolled, setIsScrolled] = useState(false);
  // Evitar hidratación incorrecta
  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 50);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const handleMenu = (event) => setAnchorEl(event.currentTarget);
  const handleClose = () => setAnchorEl(null);

  const menuItems = [
    { text: 'Inicio', href: '/' },
    { text: 'Nosotros', href: '/nosotros' },
    { text: 'Herramientas', href: '/herramientas', tooltip: 'Generar Actas y Liquidaciones' },
    { text: 'Testimonios', href: '/testimonios'},
    { text: 'Contáctanos', href: '/contacto' },
    
  ];

  if (typeof window === "undefined") {
    return null;
  }

  return (
    <>
      <ElevationScroll>
        <AppBar
          position="fixed"
          sx={{
            backgroundColor: darkMode
              ? (isScrolled ? 'rgba(17, 25, 33, 0.6)' : 'rgba(17, 25, 33, 1)')
              : (isScrolled ? 'rgba(255, 255, 255, 0.7)' : 'rgba(255, 255, 255, 1)'),
            transition: 'all 0.3s ease-in-out',
            boxShadow: isScrolled ? 1 : 0,
            backdropFilter: 'blur(20px)',
            backgroundImage: 'none',
            borderBottom: isScrolled ? '1px solid rgba(255, 255, 255, 0.1)' : 'none',
          }}
        >
          <Container maxWidth="xl">
            <Toolbar disableGutters sx={{ py: 1 }}
              style={{ justifyContent: 'space-between' }}

            >
              {/* Logo */}
              <Link href="/" passHref legacyBehavior>
                <Box
                  component="a"
                  sx={{
                    flexGrow: { xs: 1, md: 0 },
                    mr: 2,
                    display: 'flex',
                    alignItems: 'center',
                    textDecoration: 'none'
                  }}
                >
                  <Image
                    src={sempreg}
                    width={160}
                    height={50}
                    alt="Sempreg Logo"
                    priority
                    style={{
                      height: 'auto',
                      filter: darkMode && !isScrolled ? 'brightness(0) invert(1)' : (darkMode && isScrolled ? 'brightness(0) invert(1)' : 'none')
                    }}
                  />
                </Box>
              </Link>

              {/* Menú desktop */}
              <Box sx={{
                flexGrow: 1,
                display: { xs: 'none', md: 'flex' },
                justifyContent: 'center',
                gap: 1
              }}>
                {menuItems.map((item) => (
                  <Button
                    key={item.text}
                    component={Link}
                    href={item.href}
                    sx={{
                      color: darkMode ? '#F9FAFB' : '#1F2937',
                      px: 2,
                      py: 1,
                      borderRadius: '6px',
                      transition: 'all 0.2s ease',
                      fontWeight: 500,
                      fontSize: '0.95rem',
                      '&:hover': {
                        backgroundColor: darkMode ? 'rgba(25, 118, 210, 0.15)' : 'rgba(25, 118, 210, 0.08)',
                        color: '#1976d2',
                        transform: 'translateY(-1px)'
                      },
                      textTransform: 'none',
                    }}
                    title={item.tooltip}
                  >
                    {item.text}
                  </Button>
                ))}
              </Box>

              {/* Controles derecho - Desktop */}
              <Box sx={{
                display: { xs: 'none', md: 'flex' },
                alignItems: 'center',
                gap: 2
              }}>
                {/* Toggle modo oscuro */}
                <IconButton
                  onClick={() => onToggleDarkMode && onToggleDarkMode(!darkMode)}
                  sx={{
                    color: darkMode ? '#F9FAFB' : '#1F2937',
                    '&:hover': {
                      backgroundColor: darkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
                    }
                  }}
                >
                  {darkMode ? <Brightness7Icon /> : <Brightness4Icon />}
                </IconButton>

                <Button
                  component={Link}
                  href="https://suite.sempreg.com/register"
                  variant="outlined"
                  sx={{
                    borderColor: '#1976d2',
                    color: '#1976d2',
                    borderRadius: '6px',
                    '&:hover': {
                      backgroundColor: '#1976d2',
                      color: 'white',
                      borderColor: '#1976d2',
                      transform: 'translateY(-1px)',
                      boxShadow: '0 4px 12px rgba(25, 118, 210, 0.3)'
                    },
                    textTransform: 'none',
                    px: 3,
                    fontWeight: 600
                  }}
                >
                  Regístrate
                </Button>
                <Button
                  component={Link}
                  href="https://suite.sempreg.com/login"
                  variant="contained"
                  sx={{
                    backgroundColor: '#1976d2',
                    borderRadius: '6px',
                    '&:hover': {
                      backgroundColor: '#1565c0',
                      transform: 'translateY(-1px)',
                      boxShadow: '0 6px 20px rgba(25, 118, 210, 0.4)'
                    },
                    textTransform: 'none',
                    px: 3,
                    fontWeight: 600
                  }}
                >
                  Ingresar
                </Button>
              </Box>

              {/* Menú móvil */}
              <Box sx={{
                display: { xs: 'flex', md: 'none' },
                alignItems: 'center',
                gap: 1
              }}>
                {/* Toggle modo oscuro móvil */}
                <IconButton
                  onClick={() => onToggleDarkMode && onToggleDarkMode(!darkMode)}
                  sx={{
                    color: darkMode ? '#F9FAFB' : '#1F2937',
                  }}
                >
                  {darkMode ? <Brightness7Icon /> : <Brightness4Icon />}
                </IconButton>

                <IconButton
                  size="large"
                  onClick={handleMenu}
                  sx={{
                    color: darkMode ? '#F9FAFB' : '#1F2937',
                  }}
                >
                  <MenuIcon />
                </IconButton>
                <Menu
                  anchorEl={anchorEl}
                  open={Boolean(anchorEl)}
                  onClose={handleClose}
                  PaperProps={{
                    elevation: 4,
                    sx: {
                      overflow: 'visible',
                      filter: 'drop-shadow(0px 4px 12px rgba(0,0,0,0.15))',
                      mt: 1.5,
                      minWidth: 200,
                      borderRadius: '12px',
                      backgroundColor: darkMode ? '#1F2937' : 'white',
                      '& .MuiMenuItem-root': {
                        padding: '12px 20px',
                        color: darkMode ? '#F9FAFB' : '#1F2937',
                        '&:hover': {
                          backgroundColor: darkMode ? 'rgba(25, 118, 210, 0.15)' : 'rgba(25, 118, 210, 0.08)',
                          color: '#1976d2'
                        }
                      },
                    },
                  }}
                  transformOrigin={{ horizontal: 'right', vertical: 'top' }}
                  anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
                >
                  {menuItems.map((item) => (
                    <MenuItem
                      key={item.text}
                      component={Link}
                      href={item.href}
                      onClick={handleClose}
                    >
                      {item.text}
                    </MenuItem>
                  ))}
                  <Divider sx={{ my: 1 }} />
                  <MenuItem
                    component={Link}
                    href="https://suite.sempreg.com//register"
                    onClick={handleClose}
                    sx={{
                      fontWeight: 600,
                      color: '#1976d2'
                    }}
                  >
                    Regístrate
                  </MenuItem>
                  <MenuItem
                    component={Link}
                    href="https://suite.sempreg.com/login"
                    onClick={handleClose}
                    sx={{
                      fontWeight: 600,
                      color: '#1976d2'
                    }}
                  >
                    Ingresar
                  </MenuItem>
                </Menu>
              </Box>
            </Toolbar>
          </Container>
        </AppBar>
      </ElevationScroll>
      <Toolbar /> {/* Espaciador para compensar el AppBar fijo */}
    </>
  );
}

export default CompMenuprincipal;