import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { RiFileExcel2Fill } from "react-icons/ri";
import { Box, IconButton, Popover, Tooltip, Typography } from "@mui/material";
import axios from "axios";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { VetFarmCancelBar } from "../vet-farm-cancel-bar/VetFarmCancelBar";
import { SuperAdminSubmitBarStatus } from "../../../super-admin/components/super-admin-submit-bar-status/SuperAdminSubmitBarStatus";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import TuneIcon from "@mui/icons-material/Tune";
import ImageSearchIcon from "@mui/icons-material/ImageSearch";
import CancelIcon from "@mui/icons-material/Delete";
import { SlaughterEnterBarWeight } from "../../../file/components/slaughter-enter-bar-weight/SlaughterEnterBarWeight";
import EditIcon from "@mui/icons-material/Edit";
import DeleteForeverIcon from "@mui/icons-material/DeleteForever";
import { VetFarmDeleteBar } from "../vet-farm-delete-bar/VetFarmDeleteBar";
import LibraryAddIcon from "@mui/icons-material/LibraryAdd";
import { VetFarmSavePrice } from "../vet-farm-save-price/VetFarmSavePrice";
import { alpha, useTheme } from "@mui/material/styles";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
export const VetFarmOperationOptions = ({ item, updateTable, isComplete }) => {
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [anchorEl, setAnchorEl] = useState(null);
  const theme = useTheme();
  const role = getRoleFromUrl();
  const isSuperAdmin = role === "SuperAdmin";
  const isSupporter = role === "Supporter";
  const isProvinceOperator = role === "ProvinceOperator";
  const isCityVet = role === "CityVet";
  const isVetFarm = role === "VetFarm";
  const isAdminX = role === "AdminX";

  const canSubmitStatus = isSuperAdmin || isSupporter;
  const canDeleteBar = isAdminX || isSuperAdmin || isSupporter;
  const showCancelAction =
    item.assignmentStateArchive === "pending" &&
    item.trash !== true &&
    !isVetFarm;
  const cancelDisabled =
    isSuperAdmin || isSupporter || isProvinceOperator || isCityVet;
  const showPriceAction = !isVetFarm;
  const showEnterBarInfoAction = isComplete;
  const showDeleteBarAction = !isComplete && canDeleteBar;
  const showExcelAction = !isComplete;

  const ExcelIcon = () => (
    <Box component="span" sx={{ display: "flex", alignItems: "center" }}>
      <RiFileExcel2Fill size={20} color={theme.palette.success.main} />
    </Box>
  );

  const renderAction = ({
    title,
    IconComponent,
    colorKey,
    onClick,
    disabled = false,
    hidden = false,
    componentProps,
    placement = "left",
  }) => {
    if (hidden) {
      return null;
    }

    const paletteMain =
      theme.palette[colorKey]?.main ?? theme.palette.primary.main;
    const hoverBackground = alpha(paletteMain, 0.1);

    const handleActivation = () => {
      if (disabled) {
        return;
      }
      onClick?.();
    };

    const handleKeyDown = (event) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleActivation();
      }
    };

    return (
      <Grid item>
        <Tooltip title={title} placement={placement}>
          <span style={{ width: "100%", display: "block" }}>
            <Box
              role="button"
              tabIndex={0}
              onClick={handleActivation}
              onKeyDown={handleKeyDown}
              {...componentProps}
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1.5,
                px: 1.5,
                py: 1,
                borderRadius: 1,
                cursor: disabled ? "not-allowed" : "pointer",
                opacity: disabled ? 0.4 : 1,
                transition: "background-color 0.2s ease",
                textDecoration: "none",
                "&:hover": {
                  backgroundColor: disabled ? "transparent" : hoverBackground,
                },
              }}
            >
              <IconComponent sx={{ color: paletteMain }} />
              <Typography
                variant="body2"
                sx={{ color: paletteMain, fontWeight: 500 }}
              >
                {title}
              </Typography>
            </Box>
          </span>
        </Tooltip>
      </Grid>
    );
  };

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

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

  const open = Boolean(anchorEl);
  const id = open ? "popover" : undefined;

  return (
    <Grid container>
      <IconButton
        aria-describedby={id}
        variant="contained"
        color="primary"
        onClick={handleClick}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
      >
        <Grid style={{ padding: "10px 6px" }}>
          <Grid container direction="column" spacing={1}>
            {renderAction({
              title: "ثبت وضعیت سند",
              IconComponent: ImageSearchIcon,
              colorKey: "primary",
              hidden: !canSubmitStatus,
              disabled: item.assignmentInfo?.assignmentState === false,
              onClick: () => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: "ثبت وضعیت سند",
                    content: (
                      <SuperAdminSubmitBarStatus
                        item={item}
                        updateTable={updateTable}
                      />
                    ),
                  })
                );
              },
            })}

            {renderAction({
              title: "ورود اطلاعات بار",
              IconComponent: EditIcon,
              colorKey: "primary",
              hidden: !showEnterBarInfoAction,
              placement: "right",
              onClick: () => {
                handleClose();
                dispatch(
                  DRAWER({
                    title: "انجام عملیات تخصیص",
                    top: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: (
                      <SlaughterEnterBarWeight
                        updateTable={updateTable}
                        item={item}
                      />
                    ),
                  })
                );
              },
            })}

            {renderAction({
              title: "لغو بار",
              IconComponent: CancelIcon,
              colorKey: "error",
              hidden: !showCancelAction,
              disabled: cancelDisabled,
              onClick: () => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: "لغو بار",
                    content: (
                      <VetFarmCancelBar
                        updateTable={updateTable}
                        killHouseRequestKey={item.key}
                      />
                    ),
                  })
                );
              },
            })}

            {renderAction({
              title: "حذف کامل بار",
              IconComponent: DeleteForeverIcon,
              colorKey: "error",
              hidden: !showDeleteBarAction,
              disabled: item?.trash,
              onClick: () => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: "آیا از حذف بار اطمینان دارید؟",
                    content: (
                      <VetFarmDeleteBar updateTable={updateTable} item={item} />
                    ),
                  })
                );
              },
            })}

            {renderAction({
              title: "خروجی اکسل",
              IconComponent: ExcelIcon,
              colorKey: "success",
              hidden: !showExcelAction,
              placement: "left",
              onClick: () => handleClose(),
              componentProps: {
                component: "a",
                href: `${
                  axios.defaults.baseURL
                }bar_for_each_persion_excel/?code=${item.barCode}${
                  checkPathStartsWith("slaughter")
                    ? `&role_key=${selectedSubUser?.key}`
                    : ""
                }`,
                rel: "noreferrer",
                target: "_blank",
              },
            })}

            {renderAction({
              title: item?.priceRegisterDate
                ? "ویرایش گزارش قیمت"
                : "ثبت گزارش قیمت",
              IconComponent: LibraryAddIcon,
              colorKey: "primary",
              hidden: !showPriceAction,
              placement: "left-start",
              onClick: () => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: item?.priceRegisterDate
                      ? "ویرایش گزارش قیمت"
                      : "ثبت گزارش قیمت",
                    content: (
                      <VetFarmSavePrice updateTable={updateTable} item={item} />
                    ),
                  })
                );
              },
            })}
          </Grid>
        </Grid>
      </Popover>
    </Grid>
  );
};
