import { AppBar, Box, IconButton, Typography } from "@mui/material";
import React from "react";
import logo from "../../assets/images/logo.png";
import iranView from "../../assets/images/IranOutlined.png";
import HomeIcon from "@mui/icons-material/Home";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../components/grid/Grid";
import { HeaderOperations } from "../header-operations/HeaderOperations";
import { getRoleItems } from "../../utils/getRolesItems";
import { useLocation, useNavigate } from "react-router-dom";
import { sortRoles } from "../../utils/sortRoles";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";
import { useSystemName } from "../../utils/getSystemName";
import CloudSyncIcon from "@mui/icons-material/CloudSync";
import { tokenVerifiction } from "../../features/authentication/services/token-verifiction";
import { LOADING_END, LOADING_START } from "../../lib/redux/slices/appSlice";
import { loginWithPassword } from "../../features/authentication/services/login";
import { SET_ADMIN_TOKEN } from "../../lib/redux/slices/userSlice";
import {
  getLiveStockRoles,
  getUserTypeOfActivity,
} from "../../utils/getUserTypeOfActivity";
import { getLiveStockItems } from "../../utils/getLivestock";
import { AppMenu } from "../menu/Menu";

export const Header = () => {
  const role = useSelector((state) => state.userSlice.role);
  const navigate = useNavigate();
  const { pathname } = useLocation();
  // const authToken = useSelector((state) => state.userSlice.authToken);
  const systemName = useSystemName();
  const adminToken = useSelector((state) => state.userSlice.adminToken);
  const dispatch = useDispatch();
  const { typeActivitySelected } = useSelector((state) => state.userSlice);

  const userType = getUserTypeOfActivity([getRoleFromUrl()]);

  return (
    <AppBar position="relative" size="small">
      <Grid
        m={1}
        container
        alignItems="center"
        justifyContent="space-between"
        alignSelf="center"
        xs={12}
        sm={10}
        sx={{ position: "relative" }}
      >
        {/* <Menu */}
        <Box
          sx={{ display: { xs: "flex", sm: "flex", md: "flex", xl: "none" } }}
        >
          <AppMenu color="white" />
        </Box>
        <Grid sx={{ xs: "none", sm: "none", md: "none", lg: "flex" }}></Grid>
        {/* <Grid item>
          <Box
            sx={{
              flexGrow: 1,
              display: { xs: authToken ? "flex" : "none" },
              zIndex: 100,
            }}
          ></Box>
        </Grid> */}

        <Grid item container alignItems="center" gap={1}>
          <Box
            sx={{
              position: "absolute",
              top: 0,
              left: 0,
              width: "100%",
              height: "100%",
              backgroundImage: `url(${iranView})`,
              backgroundSize: "contain",
              backgroundRepeat: "repeat",
              backgroundPosition: "center",
              opacity: 0.1,
              zIndex: 0,
              pointerEvents: "none",
            }}
          />

          <Box
            sx={{
              position: "absolute",
              left: "50%",
              top: "50%",
              transform: "translate(-50%, -50%)",
              zIndex: 1,
              display: "flex",
              alignItems: "center",
              height: "100%",
            }}
          >
            {/* <AppMenu /> */}
            <Box
              component="img"
              sx={{
                width: 50,
                display: { xs: "none", md: "flex" },
                mr: 1,
              }}
              alt="logo"
              src={logo}
            />
            <Typography
              display={{ xs: "none", lg: "flex" }}
              variant="h6"
              noWrap
              component="a"
              onClick={() => {
                navigate("/");
              }}
              sx={{
                fontSize: 18,
                fontWeight: 700,
                color: "inherit",
                textDecoration: "none",
                mr: 2,
                cursor: "pointer",
              }}
            >
              {`رصـــد یـــار (سامانه رصد و پایش زنجیره تامین، تولید و توزیع کالای اساسی ) ${
                role.length === 1 && role[0] === "ParentCompany"
                  ? "شرکت مادر"
                  : systemName
              }`}
            </Typography>
            <Typography
              display={{ xs: "flex", lg: "none" }}
              variant="h6"
              noWrap
              component="a"
              onClick={() => {
                navigate("/");
              }}
              sx={{
                fontSize: 18,
                fontWeight: 700,
                color: "inherit",
                textDecoration: "none",
                mr: 2,
                cursor: "pointer",
              }}
            >
              {"سامانه رصدیار"}
            </Typography>
          </Box>
        </Grid>

        <Grid container item>
          <HeaderOperations />
          {adminToken && (
            <IconButton
              sx={{ color: "white" }}
              onClick={() => {
                dispatch(LOADING_START());
                dispatch(tokenVerifiction({ token: adminToken })).then((r) => {
                  dispatch(SET_ADMIN_TOKEN(null));
                  dispatch(
                    loginWithPassword({
                      mobile: r.payload.data?.username,
                      password: r.payload.data?.password,
                    })
                  ).then(() => {
                    dispatch(LOADING_END());
                    dispatch(SET_ADMIN_TOKEN(null));
                    navigate("/");
                  });
                });
              }}
            >
              <CloudSyncIcon />
            </IconButton>
          )}
        </Grid>
      </Grid>
      <Grid
        style={{
          backgroundColor: "#f9f9f9",
        }}
        container
        justifyContent="center"
      >
        <Grid
          container
          alignItems="center"
          display={{ xs: "none", sm: "none", md: "none", lg: "flex" }}
          style={{
            height: "40px",
          }}
          justifyContent="space-between"
          alignSelf="center"
          xs={12}
          sm={10}
        >
          <Box
            sx={{ display: { xs: "none", sm: "none", md: "none", xl: "flex" } }}
          >
            <AppMenu />
          </Box>
          <Box
            sx={{
              display: { xs: "none", lg: "inline", xl: "none" },
            }}
          ></Box>

          <Grid container justifyContent="center" alignItems="center">
            <Grid
              mx={{ xs: 0, sm: 0, md: 0.5, nlg: 1 }}
              container
              justifyContent="center"
              alignItems="center"
              gap={1}
              sx={{
                height: "100%",
                p: "3px",
                color: (theme) => theme.palette.primary.main,
                borderRadius: "8px",
                backgroundColor: (theme) =>
                  pathname === "/"
                    ? theme.palette.primary.light
                    : "transparent",
                cursor: "pointer",
                "&:hover": {
                  backgroundColor: "#EFEFEF",
                },
              }}
              onClick={() => {
                navigate("/");
              }}
            >
              {pathname === "/" && <HomeIcon />}

              <Typography
                className="header-menu"
                sx={{
                  fontWeight: "500",
                  fontSize: {
                    xs: "12px",
                    sm: "12px",
                    xl: "14px",
                  },
                }}
              >
                خانه
              </Typography>
            </Grid>

            {(userType
              ? (!!getRoleItems(getRoleFromUrl()).length &&
                  getRoleItems(getRoleFromUrl())) ||
                getLiveStockItems(getRoleFromUrl())
              : typeActivitySelected === "Livestock"
              ? getLiveStockItems(getLiveStockRoles(role)[0])
              : getRoleItems(sortRoles(role)[0])
            )
              .slice(0, 10)
              .map((item, i) => (
                <Grid
                  mx={{ xs: 0, sm: 0, md: 0.6, nlg: 1 }}
                  className="header-menu"
                  container
                  key={i}
                  justifyContent="center"
                  alignItems="center"
                  gap={1}
                  sx={{
                    height: "100%",
                    p: "3px",
                    borderRadius: "8px",
                    color: (theme) => theme.palette.primary.main,
                    backgroundColor: (theme) =>
                      pathname === item?.route
                        ? theme.palette.primary.light
                        : "transparent",
                    "&:hover": {
                      backgroundColor: "#EFEFEF",
                    },
                    cursor: "pointer",
                  }}
                  onClick={() => {
                    navigate(item?.route);
                  }}
                >
                  {pathname === item?.route && item?.icon}
                  <Typography
                    className="header-menu"
                    sx={{
                      fontWeight: "500",
                      fontSize: {
                        lg: "12px",
                        xl: "14px",
                      },
                    }}
                  >
                    {item?.text}
                  </Typography>
                </Grid>
              ))}
          </Grid>
          <Grid></Grid>
        </Grid>
      </Grid>
    </AppBar>
  );
};
