import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import {
  AppBar,
  Toolbar,
  Typography,
  IconButton,
  Avatar,
  Menu,
  MenuItem,
  Badge,
  Box,
  Button,
  Chip,
} from '@mui/material';
import {
  Menu as MenuIcon,
  Notifications,
  AccountCircle,
  Logout,
  Settings,
  Wallet,
  TrendingUp,
} from '@mui/icons-material';
import { logout } from '../../store/slices/authSlice';
import { motion } from 'framer-motion';

const Navbar = ({ onSidebarToggle }) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { user } = useSelector((state) => state.auth);
  const [anchorEl, setAnchorEl] = useState(null);
  const [notificationAnchor, setNotificationAnchor] = useState(null);

  const handleProfileMenuOpen = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const handleNotificationOpen = (event) => {
    setNotificationAnchor(event.currentTarget);
  };

  const handleNotificationClose = () => {
    setNotificationAnchor(null);
  };

  const handleLogout = () => {
    dispatch(logout());
    navigate('/login');
    handleProfileMenuClose();
  };

  const formatBalance = (balance) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
    }).format(balance);
  };

  return (
    <AppBar 
      position="fixed" 
      className="glass"
      sx={{ 
        zIndex: (theme) => theme.zIndex.drawer + 1,
        background: 'linear-gradient(135deg, rgba(30, 41, 59, 0.95), rgba(51, 65, 85, 0.9))',
        backdropFilter: 'blur(20px)',
        borderBottom: '1px solid rgba(99, 102, 241, 0.2)',
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.37)',
      }}
    >
      <Toolbar className="px-4">
        {/* Menu Button */}
        <IconButton
          edge="start"
          color="inherit"
          aria-label="menu"
          onClick={onSidebarToggle}
          className="mr-4"
        >
          <MenuIcon />
        </IconButton>

        {/* Logo */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.5 }}
          className="flex items-center cursor-pointer"
          onClick={() => navigate('/')}
        >
          <TrendingUp className="mr-2 text-primary-400" />
          <Typography 
            variant="h6" 
            component="div" 
            className="font-serif font-bold bg-gradient-to-r from-primary-400 to-secondary-400 bg-clip-text text-transparent"
          >
            SellBits Plus
          </Typography>
        </motion.div>

        {/* Spacer */}
        <Box sx={{ flexGrow: 1 }} />

        {/* User Balance */}
        {user && (
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.5, delay: 0.2 }}
          >
            <Chip
              icon={<Wallet />}
              label={formatBalance(user.balance)}
              className="mr-4 glass-card"
              sx={{
                background: 'linear-gradient(135deg, rgba(16, 185, 129, 0.2), rgba(5, 150, 105, 0.1))',
                border: '1px solid rgba(16, 185, 129, 0.3)',
                color: '#10b981',
                '& .MuiChip-icon': {
                  color: '#10b981',
                },
              }}
            />
          </motion.div>
        )}

        {/* Notifications */}
        <IconButton
          color="inherit"
          onClick={handleNotificationOpen}
          className="mr-2"
        >
          <Badge badgeContent={3} color="error">
            <Notifications />
          </Badge>
        </IconButton>

        {/* Profile Menu */}
        <IconButton
          edge="end"
          aria-label="account of current user"
          aria-controls="primary-search-account-menu"
          aria-haspopup="true"
          onClick={handleProfileMenuOpen}
          color="inherit"
        >
          <Avatar
            sx={{
              background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
              width: 36,
              height: 36,
            }}
          >
            {user?.name?.charAt(0)?.toUpperCase()}
          </Avatar>
        </IconButton>
      </Toolbar>

      {/* Profile Menu */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleProfileMenuClose}
        onClick={handleProfileMenuClose}
        PaperProps={{
          className: 'glass-card',
          sx: {
            mt: 1.5,
            minWidth: 220,
            '& .MuiMenuItem-root': {
              borderRadius: '8px',
              margin: '4px 8px',
              '&:hover': {
                background: 'rgba(99, 102, 241, 0.1)',
              },
            },
          },
        }}
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
      >
        <Box className="px-4 py-2 border-b border-slate-700">
          <Typography variant="body2" className="text-slate-300">
            Signed in as
          </Typography>
          <Typography variant="body1" className="font-semibold">
            {user?.name}
          </Typography>
          <Typography variant="caption" className="text-slate-400">
            {user?.email}
          </Typography>
        </Box>
        
        <MenuItem onClick={() => navigate('/profile')}>
          <AccountCircle className="mr-3" />
          Profile
        </MenuItem>
        <MenuItem onClick={() => navigate('/settings')}>
          <Settings className="mr-3" />
          Settings
        </MenuItem>
        <MenuItem onClick={handleLogout} className="text-red-400">
          <Logout className="mr-3" />
          Sign Out
        </MenuItem>
      </Menu>

      {/* Notifications Menu */}
      <Menu
        anchorEl={notificationAnchor}
        open={Boolean(notificationAnchor)}
        onClose={handleNotificationClose}
        PaperProps={{
          className: 'glass-card',
          sx: {
            mt: 1.5,
            minWidth: 320,
            maxHeight: 400,
          },
        }}
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
      >
        <Box className="px-4 py-2 border-b border-slate-700">
          <Typography variant="h6" className="font-semibold">
            Notifications
          </Typography>
        </Box>
        
        <MenuItem>
          <Box>
            <Typography variant="body2" className="font-medium">
              🚀 DOGE is trending up 15%
            </Typography>
            <Typography variant="caption" className="text-slate-400">
              2 minutes ago
            </Typography>
          </Box>
        </MenuItem>
        
        <MenuItem>
          <Box>
            <Typography variant="body2" className="font-medium">
              💰 Trade executed: Bought 1000 PEPE
            </Typography>
            <Typography variant="caption" className="text-slate-400">
              5 minutes ago
            </Typography>
          </Box>
        </MenuItem>
        
        <MenuItem>
          <Box>
            <Typography variant="body2" className="font-medium">
              📊 New market analysis available
            </Typography>
            <Typography variant="caption" className="text-slate-400">
              1 hour ago
            </Typography>
          </Box>
        </MenuItem>
      </Menu>
    </AppBar>
  );
};

export default Navbar; 