import React, { useEffect, useState } from "react";
import {
  Box,
  IconButton,
  Menu,
  Typography,
  List,
  ListItem,
  ListItemText,
  Divider,
  ListItemIcon,
  Chip,
  Button,
  Autocomplete,
  TextField,
} from "@mui/material";
import WidgetsIcon from "@mui/icons-material/Widgets";
import useUserProfile from "../../features/authentication/hooks/useUserProfile";
import { getFaUserRole } from "../../utils/getFaUserRole";
import { getIconUserRole } from "../../utils/getRoleIcon";
import { getRoleItems } from "../../utils/getRolesItems";
import { useLocation, useNavigate } from "react-router-dom";
import { DRAWER, OPEN_MODAL } from "../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { motion } from "framer-motion";
import { sortRoles } from "../../utils/sortRoles";
import PorvinceGetReportOperations from "../../features/province/components/province-get-report-operations/PorvinceGetReportOperations";
import SummarizeIcon from "@mui/icons-material/Summarize";
import PushPinIcon from "@mui/icons-material/PushPin";
import PushPinOutlinedIcon from "@mui/icons-material/PushPinOutlined";
import { Grid } from "../../components/grid/Grid";
import { getLiveStockItems } from "../../utils/getLivestock";
import { getPoultryRoles } from "../../utils/getUserTypeOfActivity";

export const AppMenu = ({ color }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const [pinned, setPinned] = useState(false);
  const open = Boolean(anchorEl);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const [selectedRole, setSelectedRole] = useState(null);
  const [hoveredRole, setHoveredRole] = useState(null);
  const [role] = useUserProfile();

  // Active role is either hovered or selected
  const activeRole = hoveredRole || selectedRole;

  const autocompleteItems = [];
  if (role) {
    for (let i = 0; i < role.length; i++) {
      const items = getRoleItems(role[i]);
      items.forEach((item) => {
        autocompleteItems.push({ ...item, role: role[i] });
      });

      const liveStockItems = getLiveStockItems(role[i]);
      liveStockItems.forEach((item) => {
        autocompleteItems.push({ ...item, role: role[i] });
      });
    }
  }

  useEffect(() => {
    if (role?.length === 1) {
      setSelectedRole(role[0]);
    } else if (role?.length > 1) {
      // Auto-select first role for multi-role users
      setSelectedRole(sortRoles(role)[0]);
    }
  }, [role]);

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

  const handleMenuClose = () => {
    if (!pinned) {
      setAnchorEl(null);
    }
  };

  const handlePinToggle = () => {
    setPinned((prev) => !prev);
  };

  const handleAutocompleteChange = (event, value) => {
    if (value?.route) {
      navigate(value.route);
      setSelectedRole(value.role);
      if (!pinned) {
        setAnchorEl(null);
      }
    }
  };

  const renderSearch = (
    <Grid
      container
      justifyContent="space-between"
      alignItems="center"
      mr="10px"
    >
      <Grid item xs={2}>
        <IconButton color="primary" onClick={handlePinToggle} size="small">
          {pinned ? <PushPinIcon /> : <PushPinOutlinedIcon />}
        </IconButton>
      </Grid>
      <Grid item xs={10}>
        <Autocomplete
          fullWidth
          size="small"
          options={autocompleteItems.map((item, index) => ({
            label: item.text,
            route: item.route,
            role: item.role,
            disabled: item.disabled || false,
            index,
          }))}
          groupBy={(option) =>
            role?.length !== 1 ? getFaUserRole(option.role) : false
          }
          getOptionDisabled={(option) => option.disabled}
          getOptionLabel={(option) => option.label || ""}
          onChange={handleAutocompleteChange}
          renderInput={(params) => (
            <TextField {...params} placeholder="جستجو ..." />
          )}
          renderOption={(props, option) => (
            <Typography
              color="primary"
              {...props}
              sx={{
                fontSize: 14,
                fontWeight: "700",
              }}
            >
              {option.label}
            </Typography>
          )}
        />
      </Grid>
    </Grid>
  );

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: { xs: "flex-start", sm: "center" },
        padding: { xs: "0 16px", sm: "0" },
      }}
    >
      <Button
        startIcon={<WidgetsIcon />}
        sx={{
          color: color === "white" ? "white" : "primary.main",
          "& .MuiButton-startIcon": {
            color: color === "white" ? "white" : "primary.main",
          },
        }}
        aria-controls={open ? "app-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleMenuToggle}
      >
        منو
      </Button>
      <Menu
        disableScrollLock={true}
        id="app-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleMenuClose}
        PaperProps={{
          sx: {
            width: { xs: "90%", sm: role?.length === 1 ? "350px" : "500px" },
            maxHeight: { xs: "70vh", sm: "80vh" },
            padding: 0,
            borderRadius: 2,
            boxShadow: 3,
            overflow: "hidden",
          },
        }}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "center",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "center",
        }}
      >
        <Box sx={{ p: 2, pb: 1 }}>{renderSearch}</Box>
        <Divider />

        {/* Two Column Layout */}
        <Box
          sx={{
            display: "flex",
            height: { xs: "calc(70vh - 80px)", sm: "auto" },
            maxHeight: { xs: "calc(70vh - 80px)", sm: "calc(80vh - 80px)" },
          }}
        >
          {/* Left Column - Roles List (only show if multiple roles) */}
          {role?.length > 1 && (
            <>
              <Box
                sx={{
                  width: "200px",
                  borderLeft: "1px solid",
                  borderColor: "divider",
                  overflowY: "auto",
                  bgcolor: "grey.50",
                }}
              >
                <List dense sx={{ p: 0 }}>
                  {sortRoles(role).map((item, index) => (
                    <ListItem
                      button
                      key={index}
                      selected={selectedRole === item}
                      onClick={() => setSelectedRole(item)}
                      onMouseEnter={() => setHoveredRole(item)}
                      sx={{
                        p: 1.5,
                        borderBottom: "1px solid",
                        borderColor: "divider",
                        bgcolor:
                          selectedRole === item
                            ? "primary.light"
                            : hoveredRole === item
                            ? "action.hover"
                            : "transparent",
                        transition: "all 0.2s",
                      }}
                    >
                      <ListItemIcon
                        sx={{
                          color:
                            selectedRole === item ? "primary.main" : "#6D214F",
                          minWidth: 40,
                        }}
                      >
                        {getIconUserRole(item)}
                      </ListItemIcon>
                      <ListItemText
                        sx={{
                          color:
                            selectedRole === item ? "primary.main" : "#6D214F",
                        }}
                        primary={getFaUserRole(item)}
                        primaryTypographyProps={{
                          fontSize: "0.85rem",
                          fontWeight: selectedRole === item ? 700 : 500,
                        }}
                      />
                    </ListItem>
                  ))}
                </List>
              </Box>
            </>
          )}

          {/* Right Column - Menu Items */}
          <Box
            sx={{
              flex: 1,
              overflowY: "auto",
              p: 1,
            }}
          >
            {activeRole && (
              <>
                {role?.length === 1 && (
                  <Box sx={{ px: 1, py: 0.5, mb: 1 }}>
                    <Chip
                      label={getFaUserRole(activeRole)}
                      size="small"
                      color="primary"
                      variant="outlined"
                    />
                  </Box>
                )}

                <List dense>
                  <motion.div
                    key={activeRole}
                    initial={{ opacity: 0, x: 20 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: -20 }}
                    transition={{ duration: 0.3, ease: "easeOut" }}
                  >
                    {(() => {
                      const menuItems = getPoultryRoles([activeRole]).length
                        ? getRoleItems(activeRole)
                        : getLiveStockItems(activeRole);

                      if (!menuItems || menuItems.length === 0) {
                        return (
                          <Box
                            sx={{
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                              p: 4,
                              textAlign: "center",
                            }}
                          >
                            <Typography
                              variant="body2"
                              color="text.secondary"
                              sx={{ fontWeight: 500 }}
                            >
                              آیتم منویی برای نمایش وجود ندارد
                            </Typography>
                          </Box>
                        );
                      }

                      return menuItems.map((item, index) => (
                        <ListItem
                          disabled={item?.disabled}
                          selected={pathname?.includes(item?.route)}
                          button
                          key={index}
                          onClick={() => {
                            setSelectedRole(activeRole);
                            handleMenuClose();
                            dispatch(
                              DRAWER({
                                right: false,
                                bottom: false,
                                content: null,
                              })
                            );
                            navigate(item?.route);
                          }}
                          sx={{
                            p: 1,
                            borderRadius: 1,
                            mb: 0.5,
                            "&:hover": {
                              bgcolor: "action.hover",
                            },
                          }}
                        >
                          <ListItemIcon sx={{ color: "#30336b", minWidth: 36 }}>
                            {item?.icon}
                          </ListItemIcon>
                          <ListItemText
                            sx={{ color: "#30336b" }}
                            primary={item?.text}
                            primaryTypographyProps={{ fontSize: "0.85rem" }}
                          />
                        </ListItem>
                      ));
                    })()}

                    {(activeRole === "ProvinceOperator" ||
                      activeRole === "SuperAdmin" ||
                      activeRole === "Commerce" ||
                      activeRole === "ProvinceSupervisor" ||
                      activeRole === "AdminX") && (
                      <ListItem
                        button
                        onClick={() => {
                          setSelectedRole(activeRole);
                          handleMenuClose();
                          dispatch(
                            DRAWER({
                              right: false,
                              bottom: false,
                              content: null,
                            })
                          );
                          dispatch(
                            OPEN_MODAL({
                              title: "اطلاعات گزارش",
                              content: <PorvinceGetReportOperations />,
                            })
                          );
                        }}
                        sx={{
                          p: 1,
                          borderRadius: 1,
                          mb: 0.5,
                          "&:hover": {
                            bgcolor: "action.hover",
                          },
                        }}
                      >
                        <ListItemIcon sx={{ color: "#30336b", minWidth: 36 }}>
                          <SummarizeIcon />
                        </ListItemIcon>
                        <ListItemText
                          sx={{ color: "#30336b" }}
                          primary={"گزارش روزانه"}
                          primaryTypographyProps={{ fontSize: "0.85rem" }}
                        />
                      </ListItem>
                    )}
                  </motion.div>
                </List>
              </>
            )}
          </Box>
        </Box>
      </Menu>
    </Box>
  );
};
