import React, { useState, useEffect } from "react";
import { Grid } from "../../components/grid/Grid";
import {
  Typography,
  Select,
  MenuItem,
  FormControl,
  Box,
  IconButton,
  Button,
  InputLabel,
  CircularProgress,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import { getFaUserRole } from "../../utils/getFaUserRole";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";
import { getRoleItems } from "../../utils/getRolesItems";
import { useLocation, useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { getLiveStockItems } from "../../utils/getLivestock";
import arrow from "../../assets/images/arrow.png";
import { SET_SELECTED_SUB_USER } from "../../lib/redux/slices/userSlice";
import { OPEN_MODAL, CLOSE_MODAL } from "../../lib/redux/slices/appSlice";
import { getUserRoleInfo } from "../../features/authentication/services/getUserRoleInfo";

// Edit Modal Content Component
const EditModalContent = ({
  initialRole,
  initialSubUser,
  subUsers: initialSubUsers,
  onSubmit,
  onCancel,
  userKey,
}) => {
  const dispatch = useDispatch();
  const [selectedSubUserInModal, setSelectedSubUserInModal] =
    useState(initialSubUser);
  const [subUsers, setSubUsers] = useState(initialSubUsers || []);
  const [loadingSubUsers, setLoadingSubUsers] = useState(false);

  const rolesNeedingSubUsers = [
    "Steward",
    "ColdHouseSteward",
    "KillHouse",
    "Guilds",
  ];

  const getRoleLabel = (role) => {
    switch (role) {
      case "KillHouse":
        return "نام کشتارگاه";
      case "ColdHouseSteward":
      case "Steward":
        return "نام مباشر";
      case "Guilds":
        return "نام صنف";
      default:
        return "انتخاب واحد";
    }
  };

  const fetchSubUsers = React.useCallback(
    (role) => {
      if (role && rolesNeedingSubUsers.includes(role) && userKey) {
        setLoadingSubUsers(true);
        dispatch(getUserRoleInfo({ userKey, role }))
          .unwrap()
          .then((result) => {
            if (result?.data && Array.isArray(result.data)) {
              setSubUsers(result.data);
            } else {
              setSubUsers([]);
            }
            setLoadingSubUsers(false);
          })
          .catch((error) => {
            console.error("Error fetching subUsers:", error);
            setSubUsers([]);
            setLoadingSubUsers(false);
          });
      } else {
        setSubUsers([]);
        setLoadingSubUsers(false);
      }
    },
    [userKey, dispatch, rolesNeedingSubUsers]
  );

  useEffect(() => {
    if (initialRole) {
      if (initialSubUsers && initialSubUsers.length > 0) {
        return;
      }
      fetchSubUsers(initialRole);
    }
  }, [initialRole]);

  return (
    <Grid container spacing={2} direction="column" sx={{ width: "100%" }}>
      {rolesNeedingSubUsers.includes(initialRole) && (
        <Grid item xs={12}>
          <FormControl fullWidth>
            <InputLabel id="subuser-select-label">
              {getRoleLabel(initialRole)}
            </InputLabel>
            {loadingSubUsers ? (
              <Box
                sx={{
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  padding: 2,
                }}
              >
                <CircularProgress size={24} />
              </Box>
            ) : (
              <Select
                labelId="subuser-select-label"
                value={selectedSubUserInModal || ""}
                onChange={(e) => setSelectedSubUserInModal(e.target.value)}
                label={getRoleLabel(initialRole)}
                disabled={loadingSubUsers || subUsers.length === 0}
              >
                {subUsers.map((user) => (
                  <MenuItem key={user.key} value={user.key}>
                    {user.unit}
                  </MenuItem>
                ))}
              </Select>
            )}
          </FormControl>
        </Grid>
      )}
      <Grid item xs={12} container spacing={2} mt={1} pb={2}>
        <Grid item xs={6}>
          <Button fullWidth variant="outlined" onClick={onCancel}>
            انصراف
          </Button>
        </Grid>
        <Grid item xs={6}>
          <Button
            fullWidth
            variant="contained"
            onClick={() => onSubmit(selectedSubUserInModal)}
            disabled={!selectedSubUserInModal}
          >
            ثبت
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};

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

  const { subMenuText, mediatorText } = useSelector((state) => state.userSlice);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const subUsers = useSelector((state) => state.userSlice.subUsers);
  const userProfile = useSelector((state) => state.userSlice.userProfile);
  const loginUserProfile = useSelector(
    (state) => state.userSlice.loginUserProfile
  );
  const userKey = userProfile?.key || loginUserProfile?.key;

  // Check if current route is slaughter, senf, or steward
  const isAllowedRoute =
    pathname.startsWith("/slaughter") ||
    pathname.startsWith("/senf") ||
    pathname.startsWith("/steward");

  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;

  const getRoleLabel = (role) => {
    switch (role) {
      case "KillHouse":
        return "کشتارگاه";
      case "Steward":
        return "مباشر";
      case "Guilds":
        return "صنف";
      default:
        return "کشتارگاه"; // Default fallback
    }
  };

  const currentRole = getRoleFromUrl();
  const roleLabel = getRoleLabel(currentRole);
  const subUserName = selectedSubUser?.unit;

  const handleOpenEditModal = () => {
    const initialRole = getRoleFromUrl() || "";
    const initialSubUser = selectedSubUser?.key || "";

    dispatch(
      OPEN_MODAL({
        title: "تغییر واحد",
        content: (
          <EditModalContent
            initialRole={initialRole}
            initialSubUser={initialSubUser}
            subUsers={subUsers}
            onSubmit={handleSubmit}
            onCancel={() => dispatch(CLOSE_MODAL())}
            userKey={userKey}
          />
        ),
        size: 400,
      })
    );
  };

  const handleSubmit = (selectedSubUserInModal) => {
    dispatch(CLOSE_MODAL());
    dispatch(
      OPEN_MODAL({
        title: "تأیید تغییرات",
        content: (
          <Grid container spacing={2} direction="column" sx={{ width: "100%" }}>
            <Grid item xs={12}>
              <Typography variant="body2">
                آیا از تغییر واحد مطمئن هستید؟
              </Typography>
            </Grid>
            <Grid item xs={12} container spacing={2} mt={1}>
              <Grid item xs={6}>
                <Button
                  fullWidth
                  variant="outlined"
                  onClick={() => dispatch(CLOSE_MODAL())}
                >
                  خیر
                </Button>
              </Grid>
              <Grid item xs={6}>
                <Button
                  fullWidth
                  variant="contained"
                  onClick={() => handleConfirmSubmit(selectedSubUserInModal)}
                >
                  بله
                </Button>
              </Grid>
            </Grid>
          </Grid>
        ),
        size: 300,
      })
    );
  };

  const handleConfirmSubmit = (selectedSubUserInModal) => {
    if (selectedSubUserInModal) {
      const subUser = subUsers.find((u) => u.key === selectedSubUserInModal);
      if (subUser) {
        dispatch(SET_SELECTED_SUB_USER(subUser));
      }
    }
    dispatch(CLOSE_MODAL());
  };

  return (
    <Grid
      container
      xs={12}
      sx={{
        justifyContent: { xs: "start", sm: "center" },
      }}
      px={2}
      mt={1}
    >
      <Box
        sx={{
          width: { xs: "100%", sm: "83.33%" },
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 2,
        }}
      >
        <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>

        {isAllowedRoute && subUsers && subUsers.length > 1 && (
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 1,
            }}
          >
            <Typography
              variant="body2"
              component="span"
              sx={{
                fontSize: "12px",
                color: "primary.main",
                fontWeight: 500,
              }}
            >
              نام {roleLabel} :{" "}
              <Typography
                component="span"
                sx={{
                  fontSize: "14px",
                  color: "primary.main",
                  fontWeight: 600,
                }}
              >
                {subUserName}
              </Typography>
            </Typography>
            <IconButton
              size="small"
              onClick={handleOpenEditModal}
              sx={{
                padding: "4px",
                color: "primary.main",
                "&:hover": {
                  backgroundColor: "primary.light",
                  color: "primary.dark",
                },
              }}
            >
              <EditIcon fontSize="small" sx={{ fontSize: "16px" }} />
            </IconButton>
          </Box>
        )}
      </Box>
    </Grid>
  );
};
