import React from "react";
import { Grid } from "../../components/grid/Grid";
import { Typography } from "@mui/material";
import { getFaUserRole } from "../../utils/getFaUserRole";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";
import { getRoleItems } from "../../utils/getRolesItems";
import { useLocation, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { getLiveStockItems } from "../../utils/getLivestock";
import arrow from "../../assets/images/arrow.png";

export const SiteMap = () => {
  const { pathname } = useLocation();
  const navigate = useNavigate();

  const { subMenuText, mediatorText } = useSelector((state) => state.userSlice);

  const showSecondPath =
    !getRoleItems(getRoleFromUrl())?.find(
      (element) => element.route === pathname
    ) &&
    !getLiveStockItems(getRoleFromUrl())?.find(
      (element) => element.route === pathname
    );

  const pathFound =
    getRoleItems(getRoleFromUrl())?.find(
      (element) => element.route === mediatorText
    )?.text ||
    getLiveStockItems(getRoleFromUrl())?.find(
      (element) => element.route === mediatorText
    )?.text;

  return (
    <Grid
      container
      xs={12}
      sx={{
        justifyContent: { xs: "start", sm: "center" },
      }}
      px={2}
      mt={1}
    >
      <Grid
        container
        xs={10}
        justifyContent="start"
        alignItems="center"
        style={{ color: "gray", userSelect: "none" }}
      >
        <Grid
          container
          justifyContent="start"
          alignItems="center"
          gap={1}
          style={{
            color: "gray",
            userSelect: "none",
            background: "#E4E4E4",
            paddingInline: "10px",
            borderRadius: "5px",
          }}
        >
          <Typography
            variant="caption"
            onClick={() => navigate("/")}
            sx={{ cursor: "pointer" }}
          >
            {getFaUserRole(getRoleFromUrl())}
          </Typography>
          <img alt="arrow" src={arrow} style={{ width: "20px" }} />

          {showSecondPath && pathFound && (
            <>
              <Typography
                variant="caption"
                onClick={() => navigate(-1)}
                style={{ cursor: "pointer" }}
              >
                {pathFound}
              </Typography>

              <img alt="arrow" src={arrow} style={{ width: "20px" }} />
            </>
          )}

          <Typography variant="caption">
            {!/\d/.test(pathname)
              ? getRoleItems(getRoleFromUrl())?.find(
                  (element) => element.route === pathname
                )?.text ||
                getLiveStockItems(getRoleFromUrl())?.find(
                  (element) => element.route === pathname
                )?.text ||
                subMenuText
              : "نمایش"}
          </Typography>
        </Grid>
      </Grid>
    </Grid>
  );
};
