import React, { useState, useEffect } from "react";
import { useNavigate, Link, Routes, Route, Outlet } from "react-router-dom";
import {
  Box,
  Divider,
  Drawer,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Collapse,
  useTheme,
  styled,
  Menu,
  MenuItem,
  Avatar,
  Typography,
  Tooltip
} from '@mui/material';
import {
  ChevronLeft,
  ChevronRight,
  ExpandMore,
  ExpandLess,
  Description as DescriptionIcon,
  Error as ErrorIcon,
  Storage as StorageIcon,
  SwapHoriz as SwapHorizIcon,
  Home as HomeIcon,
  Settings as SettingsIcon,
  GridView as GridViewIcon,
  BarChart as BarChartIcon,
  Apps as AppsIcon,
  Person as PersonIcon,
  Language as LanguageIcon,
  LockReset as LockResetIcon,
  Logout as LogoutIcon,
  Info as InfoIcon,
  Menu as MenuIcon
} from '@mui/icons-material';
import UserMaintanceComponent from "./UserMaintance";
import UserGroupMaintanceComponent from "./UserGroupMaintance/UserGroupMaintance";
import MenuMaintanceComponent from "./MenuMaintance/MenuMaintance";
import MenuAccessControlComponent from "./MenuAccessControl/MenuAccessControl";
import SystemParametersComponent from "./SystemParameters/SystemParameters";
import AccessTypeComponent from "./AccessType/AccessType";
import ApiRegistery from "./ApiRegistery/ApiRegistery";
import TokenRegistery from "./TokenRegistery/TokenRegistery";
import HomePage from "./HomePage";
import Setup from "./Setup";
// import Report from "./reports/Report";
import SequenceGenerator from "./document sequence/sequencegenerator";
import About from "./dropdown/about";
import Profile from "./dropdown/profile";
import DashboardRunnerAll from "./../dashboardnew/dashboardrunner/dashboardrunnerall";
import DashboardNewAll from "../dashboardnew/dashboardbuildernewall";
import DashboardNewAdd from "../dashboardnew/dashboardadd/dashboardbuilderadd";
import DashboardNewEdit from "../dashboardnew/editdashboard/editformdashboard"; 
import EditNewDash from "../dashboardnew/editdashboard/editdashboard";
import DashboardRunner from "../dashboardnew/dashboardrunner/dashboardrunner";
import SubMenuMaintenance from "./sub menu/submenumaintanence"; 
import ReportRunnerAll from "./reports/reportrunnerall";
import Report from "./reports/Report";
import ReportBuilderSQL from "./reports/reportbuildersql";

const Dashboard = () => {
  const navigate = useNavigate();
  const theme = useTheme();
  const [menus, setMenus] = useState([]);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(true);
  const [openTransaction, setOpenTransaction] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);
  const [submenuAnchorEl, setSubmenuAnchorEl] = useState(null);
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);

  const drawerWidth = 220;
  const collapsedWidth = 60;

  useEffect(() => {
    const user = JSON.parse(localStorage.getItem("user"));
    setCurrentUser(user);

    const fetchMenusData = async () => {
      const token = localStorage.getItem("token");

      const apiUrl = `${process.env.REACT_APP_API_BASE_URL}/fndMenu/menuloadbyuser`;
      console.log("Fetching menus from API:", apiUrl);

      try {
        const response = await fetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const menuData = await response.json();
          setMenus(menuData);
        } else {
          const errorText = await response.text();
          console.error(
            "Failed to fetch menus. Status:",
            response.status,
            "Response:",
            errorText
          );
        }
      } catch (error) {
        console.error("Error during menu fetch:", error);
      }
    };

    fetchMenusData();
  }, [navigate]);

  const handleHomeClick = () => {
    navigate('/dashboard');
  };

  const handleSetupClick = () => {
    navigate('/dashboard/setup');
  };

  const handleReportClick = () => {
    navigate('/dashboard/reports');
  };

  const handleMenuItemClick = (menu) => {
    const routeMap = {
      "User Maintance": "/dashboard/setup/user-maintenance",
      "User Group Maintance": "/dashboard/setup/user-group-maintenance",
      "Menu Maintance": "/dashboard/setup/menu-maintenance",
      "Menu Access Control": "/dashboard/setup/menu-access-control",
      "System Parameters": "/dashboard/setup/system-parameters",
      "Access Type": "/dashboard/setup/access-type",
      "Api Registery": "/dashboard/setup/api-registry",
      "Token Registery": "/dashboard/setup/token-registry",
      "sequence generator": "/dashboard/setup/document-sequence",
    };
    
    if (routeMap[menu.menuItemDesc]) {
      navigate(routeMap[menu.menuItemDesc]);
    }
  };

  const handleSidebarToggle = () => {
    setSidebarCollapsed(!sidebarCollapsed);
  };

  const handleTransactionToggle = () => {
    setOpenTransaction(!openTransaction);
  };

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

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

  const handleSubmenuOpen = (event) => {
    setSubmenuAnchorEl(event.currentTarget);
  };

  const handleSubmenuClose = () => {
    setSubmenuAnchorEl(null);
  };

  const handleLogout = () => {
    localStorage.removeItem("authToken");
    localStorage.removeItem("user");
    navigate("/");
    handleMenuClose();
  };

  const handleLanguageSelect = (lang) => {
    localStorage.setItem("appLanguage", lang);
    handleSubmenuClose();
    handleMenuClose();
    window.location.reload();
  };

  const toggleMobileSidebar = () => {
    setMobileSidebarOpen(!mobileSidebarOpen);
  };

  const DrawerHeader = styled('div')(({ theme }) => ({
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: theme.spacing(0, 1),
    ...theme.mixins.toolbar,
  }));

  return (
    <div className="flex flex-col h-screen">
      {/* Navbar - fixed at the top */}
      <div className="h-16 flex-shrink-0 bg-gray-800 text-white p-4 z-10">
        <div className="flex justify-between items-center h-full">
          <div className="flex items-center">
            <IconButton 
              color="inherit" 
              onClick={toggleMobileSidebar}
              sx={{ display: { xs: 'block', lg: 'none' }, mr: 2 }}
            >
              <MenuIcon />
            </IconButton>
            <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
              Dashboard
            </Typography>
          </div>

          {/* Desktop Navigation Icons */}
          <Box sx={{ display: { xs: 'none', lg: 'flex' }, gap: 2 }}>
            <Tooltip title="Home">
              <IconButton color="inherit" onClick={handleHomeClick}>
                <HomeIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Settings">
              <IconButton color="inherit" onClick={handleSetupClick}>
                <SettingsIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Dashboard">
              <IconButton color="inherit" onClick={() => navigate('/dashboard/dashboard-runner-all')}>
                <GridViewIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Reports">
              <IconButton color="inherit" onClick={handleReportClick}>
                <BarChartIcon />
              </IconButton>
            </Tooltip>
          </Box>

          {/* User Dropdown */}
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <Tooltip title="Account settings">
              <IconButton
                onClick={handleMenuOpen}
                size="small"
                sx={{ ml: 2 }}
                aria-controls={anchorEl ? 'account-menu' : undefined}
                aria-haspopup="true"
                aria-expanded={anchorEl ? 'true' : undefined}
              >
                <Avatar sx={{ width: 32, height: 32, bgcolor: 'primary.main' }}>
                  <PersonIcon fontSize="small" />
                </Avatar>
                <Typography variant="body1" sx={{ ml: 1, color: 'white', display: { xs: 'none', lg: 'block' } }}>
                  {currentUser ? currentUser.fullname || currentUser.username || currentUser.email : "Guest"}
                </Typography>
              </IconButton>
            </Tooltip>
          </Box>

          {/* User Menu */}
          <Menu
            anchorEl={anchorEl}
            id="account-menu"
            open={Boolean(anchorEl)}
            onClose={handleMenuClose}
            onClick={handleMenuClose}
            PaperProps={{
              elevation: 0,
              sx: {
                overflow: 'visible',
                filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))',
                mt: 1.5,
                '& .MuiAvatar-root': {
                  width: 32,
                  height: 32,
                  ml: -0.5,
                  mr: 1,
                },
                '&:before': {
                  content: '""',
                  display: 'block',
                  position: 'absolute',
                  top: 0,
                  right: 14,
                  width: 10,
                  height: 10,
                  bgcolor: 'background.paper',
                  transform: 'translateY(-50%) rotate(45deg)',
                  zIndex: 0,
                },
              },
            }}
            transformOrigin={{ horizontal: 'right', vertical: 'top' }}
            anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
          >
            <MenuItem onClick={() => navigate('/dashboard/about')}>
              <ListItemIcon>
                <InfoIcon fontSize="small" />
              </ListItemIcon>
              About
            </MenuItem>
            <MenuItem onClick={() => navigate('/dashboard/profile')}>
              <ListItemIcon>
                <PersonIcon fontSize="small" />
              </ListItemIcon>
              My Profile
            </MenuItem>
            <MenuItem onClick={() => navigate('/dashboard/dashboard-runner-all')}>
              <ListItemIcon>
                <GridViewIcon fontSize="small" />
              </ListItemIcon>
              Activity
            </MenuItem>
            <MenuItem 
              onClick={handleSubmenuOpen}
              onMouseEnter={handleSubmenuOpen}
            >
              <ListItemIcon>
                <LanguageIcon fontSize="small" />
              </ListItemIcon>
              Choose Language
              {Boolean(submenuAnchorEl) ? <ExpandLess sx={{ ml: 1 }} /> : <ExpandMore sx={{ ml: 1 }} />}
            </MenuItem>
            <MenuItem onClick={() => navigate('/admin/resetpassword')}>
              <ListItemIcon>
                <LockResetIcon fontSize="small" />
              </ListItemIcon>
              Reset Password
            </MenuItem>
            <Divider />
            <MenuItem onClick={handleLogout}>
              <ListItemIcon>
                <LogoutIcon fontSize="small" />
              </ListItemIcon>
              Logout
            </MenuItem>
          </Menu>

          {/* Language Submenu */}
          <Menu
            anchorEl={submenuAnchorEl}
            open={Boolean(submenuAnchorEl)}
            onClose={handleSubmenuClose}
            MenuListProps={{
              onMouseLeave: handleSubmenuClose,
              'aria-labelledby': 'language-button',
            }}
            anchorOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
            transformOrigin={{
              vertical: 'top',
              horizontal: 'left',
            }}
          >
            <MenuItem onClick={() => handleLanguageSelect("en")}>English</MenuItem>
            <MenuItem onClick={() => handleLanguageSelect("hi")}>Hindi</MenuItem>
            <MenuItem onClick={() => handleLanguageSelect("ta")}>Tamil</MenuItem>
            <MenuItem onClick={() => handleLanguageSelect("te")}>Telugu</MenuItem>
          </Menu>
        </div>
      </div>

      {/* Mobile Sidebar */}
      <Drawer
        variant="temporary"
        open={mobileSidebarOpen}
        onClose={toggleMobileSidebar}
        ModalProps={{
          keepMounted: true,
        }}
        sx={{
          display: { xs: 'block', lg: 'none' },
          '& .MuiDrawer-paper': { boxSizing: 'border-box', width: 240 },
        }}
      >
        <Box sx={{ p: 2 }}>
          <List>
            <ListItemButton onClick={() => { handleHomeClick(); toggleMobileSidebar(); }}>
              <ListItemIcon><HomeIcon /></ListItemIcon>
              <ListItemText primary="Home" />
            </ListItemButton>
            <ListItemButton onClick={() => { handleSetupClick(); toggleMobileSidebar(); }}>
              <ListItemIcon><SettingsIcon /></ListItemIcon>
              <ListItemText primary="Settings" />
            </ListItemButton>
            <ListItemButton onClick={() => { navigate('/dashboard/dashboard-runner-all'); toggleMobileSidebar(); }}>
              <ListItemIcon><GridViewIcon /></ListItemIcon>
              <ListItemText primary="Dashboard" />
            </ListItemButton>
            <ListItemButton onClick={() => { handleReportClick(); toggleMobileSidebar(); }}>
              <ListItemIcon><BarChartIcon /></ListItemIcon>
              <ListItemText primary="Reports" />
            </ListItemButton>
           
          </List>
        </Box>
      </Drawer>

      {/* Main content area below navbar */}
      <div className="flex flex-1 overflow-hidden">
        {/* Integrated Sidebar */}
        <Drawer
          variant="permanent"
          sx={{
            display: { xs: 'none', lg: 'block' },
            width: sidebarCollapsed ? collapsedWidth : drawerWidth,
            flexShrink: 0,
            '& .MuiDrawer-paper': {
              width: sidebarCollapsed ? collapsedWidth : drawerWidth,
              boxSizing: 'border-box',
              backgroundColor: theme.palette.grey[200],
              borderRight: '1px solid rgba(0, 0, 0, 0.12)',
              transition: theme.transitions.create('width', {
                easing: theme.transitions.easing.sharp,
                duration: theme.transitions.duration.enteringScreen,
              }),
              overflowX: 'hidden',
              height: 'calc(100vh - 64px)',
              position: 'relative',
            },
          }}
        >
          <DrawerHeader>
            <IconButton onClick={handleSidebarToggle} size="small">
              {sidebarCollapsed ? <ChevronRight /> : <ChevronLeft />}
            </IconButton>
          </DrawerHeader>
          <Divider />
          <List>
            {/* Transaction with submenus */}
            <ListItem disablePadding>
              <ListItemButton
                onClick={handleTransactionToggle}
                sx={{
                  minHeight: 48,
                  justifyContent: sidebarCollapsed ? 'center' : 'initial',
                  px: 2.5,
                  '&:hover': {
                    backgroundColor: 'rgba(0, 0, 0, 0.04)'
                  }
                }}
              >
                <ListItemIcon
                  sx={{
                    minWidth: 0,
                    mr: sidebarCollapsed ? 'auto' : 3,
                    justifyContent: 'center',
                    color: 'inherit'
                  }}
                >
                  <SwapHorizIcon />
                </ListItemIcon>
                {!sidebarCollapsed && (
                  <>
                    <ListItemText primary="Transaction" />
                    {openTransaction ? <ExpandLess /> : <ExpandMore />}
                  </>
                )}
              </ListItemButton>
            </ListItem>
            
            {!sidebarCollapsed && (
              <Collapse in={openTransaction} timeout="auto" unmountOnExit>
                <List component="div" disablePadding sx={{ backgroundColor: 'rgba(0, 0, 0, 0.02)' }}>
                  <ListItemButton
                    sx={{ pl: 4 }}
                    onClick={() => navigate('/admin/regform')}
                  >
                    <ListItemIcon sx={{ minWidth: 0, mr: 3, justifyContent: 'center' }}>
                      <DescriptionIcon />
                    </ListItemIcon>
                    <ListItemText primary="Regform" />
                  </ListItemButton>
                  <ListItemButton
                    sx={{ pl: 4 }}
                    onClick={() => navigate('/admin/error404')}
                  >
                    <ListItemIcon sx={{ minWidth: 0, mr: 3, justifyContent: 'center' }}>
                      <ErrorIcon />
                    </ListItemIcon>
                    <ListItemText primary="Additional container" />
                  </ListItemButton>
                </List>
              </Collapse>
            )}

            {/* Masters (single item) */}
            <ListItem disablePadding>
              <ListItemButton
                onClick={() => navigate('/admin/masters')}
                sx={{
                  minHeight: 48,
                  justifyContent: sidebarCollapsed ? 'center' : 'initial',
                  px: 2.5,
                  '&:hover': {
                    backgroundColor: 'rgba(0, 0, 0, 0.04)'
                  }
                }}
              >
                <ListItemIcon
                  sx={{
                    minWidth: 0,
                    mr: sidebarCollapsed ? 'auto' : 3,
                    justifyContent: 'center',
                    color: 'inherit'
                  }}
                >
                  <StorageIcon />
                </ListItemIcon>
                {!sidebarCollapsed && (
                  <ListItemText primary="Masters" />
                )}
              </ListItemButton>
            </ListItem>

            {/* Dynamic menu items from API */}
            {menus.map((menu) => (
              <ListItem key={menu.menuItemId} disablePadding>
                <ListItemButton
                  onClick={() => handleMenuItemClick(menu)}
                  sx={{
                    minHeight: 48,
                    justifyContent: sidebarCollapsed ? 'center' : 'initial',
                    px: 2.5,
                    '&:hover': {
                      backgroundColor: 'rgba(0, 0, 0, 0.04)'
                    }
                  }}
                >
                  <ListItemIcon
                    sx={{
                      minWidth: 0,
                      mr: sidebarCollapsed ? 'auto' : 3,
                      justifyContent: 'center',
                      color: 'inherit'
                    }}
                  >
                    <StorageIcon />
                  </ListItemIcon>
                  {!sidebarCollapsed && (
                    <ListItemText primary={menu.menuItemDesc} />
                  )}
                </ListItemButton>
              </ListItem>
            ))}
          </List>
        </Drawer>

        {/* Content area */}
        <Box
          component="main"
          sx={{
            flexGrow: 1,
            p: 3,
            width: { 
              xs: '100%',
              lg: `calc(100% - ${sidebarCollapsed ? collapsedWidth : drawerWidth}px)`
            },
            marginLeft: {
              xs: 0,
              lg: `${sidebarCollapsed ? collapsedWidth : drawerWidth}px`
            },
            transition: theme.transitions.create(['width', 'margin'], {
              easing: theme.transitions.easing.sharp,
              duration: theme.transitions.duration.leavingScreen,
            }),
            height: 'calc(100vh - 64px)',
            overflow: 'auto'
          }}
        >
          <Routes>
            <Route index element={<HomePage />} />
            <Route path="setup" element={<Setup />}>
              <Route index element={<div>Select a setup option from the menu</div>} />
              <Route path="user-maintenance" element={<UserMaintanceComponent />} />
              <Route path="user-group-maintenance" element={<UserGroupMaintanceComponent />} />
              <Route path="menu-maintenance" element={<MenuMaintanceComponent />} />
              <Route path="menu-access-control" element={<MenuAccessControlComponent />} />
              <Route path="system-parameters" element={<SystemParametersComponent />} />
              <Route path="access-type" element={<AccessTypeComponent />} />
              <Route path="api-registry" element={<ApiRegistery />} />
              <Route path="token-registry" element={<TokenRegistery />} />
              <Route path="document-sequence" element={<SequenceGenerator />} />
            <Route path="sub-menu-maintenance/:menuItemId" element={<SubMenuMaintenance/>} />
            </Route>
            <Route path="reports" element={<Report/>} />
            <Route path="user-report" element={<ReportBuilderSQL/>} />
            <Route path="about" element={<About/>} />
            <Route path="profile" element={<Profile/>} />
            <Route path="dashboard-runner-all" element={<DashboardRunnerAll/>}/>
            <Route path="dashboard-new-all" element={<DashboardNewAll/>}/>
            <Route path="dashboard-new-add" element={<DashboardNewAdd/>}/>
            <Route path="dashboard-new-edit/:id" element={<DashboardNewEdit/>}/> 
            <Route path="edit-new-dash/:id" element={<EditNewDash/>}/>
            <Route path="dashrunner/:id" element={  <DashboardRunner/>}/>
            
            <Route path="*" element={<div>Page Not Found</div>} />
          </Routes>
        </Box>
      </div>
    </div>
  );
};

export default Dashboard;