'use client';

import React, { useState } from 'react';
import { 
  AppBar, Toolbar, Typography, Button, Box, Container, 
  Avatar, IconButton, Drawer, List, ListItem, 
  ListItemButton, ListItemIcon, ListItemText, Divider 
} from '@mui/material';
import MenuIcon from '@mui/icons-material/Menu';
import LibraryBooksIcon from '@mui/icons-material/LibraryBooks';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CloudSyncIcon from '@mui/icons-material/CloudSync'; // Great icon for Bulk/Restore
import DashboardIcon from '@mui/icons-material/Dashboard';
import SettingsIcon from '@mui/icons-material/Settings';
import Link from 'next/link';
import { signIn, signOut } from "next-auth/react";

// Updated Interface to include Role and Bootstrap status
interface NavbarProps {
  user?: {
    name?: string | null;
    email?: string | null;
    image?: string | null;
    role?: string;        // Added
    isBootstrap?: boolean; // Added
  };
}

export default function Navbar({ user }: NavbarProps) {
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const isLoggedIn = !!user;

  // Logic: Is this user an Admin?
  const isAdmin = user?.role === 'ADMIN' || user?.isBootstrap === true;

  const toggleDrawer = (open: boolean) => (event: React.KeyboardEvent | React.MouseEvent) => {
    if (event.type === 'keydown' && ((event as React.KeyboardEvent).key === 'Tab' || (event as React.KeyboardEvent).key === 'Shift')) {
      return;
    }
    setIsDrawerOpen(open);
  };

  // Build the list dynamically based on permissions
  const navItems = [
    { text: 'Dashboard', icon: <DashboardIcon />, href: '/dashboard' },
    { text: 'Library', icon: <LibraryBooksIcon />, href: '/library' },
    { text: 'Upload File', icon: <CloudUploadIcon />, href: '/upload' },
    { text: 'Bulk Upload / Restore', icon: <CloudSyncIcon />, href: '/upload/bulk' },
  ];

  // Only push Settings if the user has Admin rights
  if (isAdmin) {
    navItems.push({ text: 'Settings', icon: <SettingsIcon />, href: '/settings' });
  }

  return (
    <>
      <AppBar position="sticky" elevation={0} sx={{ backgroundColor: 'white', color: 'text.primary', borderBottom: '1px solid #e0e0e0' }}>
        <Container maxWidth="lg">
          <Toolbar disableGutters>
            <IconButton 
              edge="start" 
              color="inherit" 
              aria-label="menu" 
              sx={{ mr: 2 }}
              onClick={toggleDrawer(true)}
            >
              <MenuIcon />
            </IconButton>

            <Typography
              variant="h6"
              component={Link}
              href="/"
              sx={{ fontWeight: 700, color: 'primary.main', textDecoration: 'none', flexGrow: 1 }}
            >
              WebCalibre 2
            </Typography>

            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              {isLoggedIn ? (
                <>
                  <Box sx={{ textAlign: 'right', display: { xs: 'none', sm: 'block' } }}>
                    <Typography variant="body2" fontWeight={600} sx={{ lineHeight: 1.2 }}>{user.name}</Typography>
                    <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>
                        {user.email} {isAdmin && "(Admin)"}
                    </Typography>
                  </Box>
                  <Avatar src={user.image || ""} sx={{ width: 38, height: 38, border: '1px solid #eee' }}>
                    {user.name?.charAt(0)}
                  </Avatar>
                  <Button variant="outlined" color="inherit" size="small" onClick={() => signOut({ callbackUrl: '/' })} sx={{ textTransform: 'none' }}>
                    Logout
                  </Button>
                </>
              ) : (
                <Button variant="contained" disableElevation onClick={() => signIn("microsoft-entra-id", { callbackUrl: "/dashboard" })} sx={{ textTransform: 'none', px: 3 }}>
                  Login
                </Button>
              )}
            </Box>
          </Toolbar>
        </Container>
      </AppBar>

      {/* The Drawer (Sidebar) */}
      <Drawer anchor="left" open={isDrawerOpen} onClose={toggleDrawer(false)}>
        <Box sx={{ width: 250 }} role="presentation" onClick={toggleDrawer(false)} onKeyDown={toggleDrawer(false)}>
          <Box sx={{ p: 2, display: 'flex', alignItems: 'center', gap: 2, bgcolor: 'primary.main', color: 'white' }}>
             <LibraryBooksIcon />
             <Typography variant="h6" fontWeight={700}>Navigation</Typography>
          </Box>
          <Divider />
          <List>
            {navItems.map((item) => (
              <ListItem key={item.text} disablePadding>
                <ListItemButton component={Link} href={item.href}>
                  <ListItemIcon>{item.icon}</ListItemIcon>
                  <ListItemText primary={item.text} />
                </ListItemButton>
              </ListItem>
            ))}
          </List>
          {/* Visual indicator for non-admins if you want it greyed out instead of hidden */}
          {!isAdmin && isLoggedIn && (
             <>
                <Divider />
                <List>
                    <ListItem sx={{ opacity: 0.5 }}>
                        <ListItemIcon><SettingsIcon /></ListItemIcon>
                        <ListItemText primary="Settings" secondary="Admin Only" />
                    </ListItem>
                </List>
             </>
          )}
        </Box>
      </Drawer>
    </>
  );
}