import { Button, IconButton, Popover } from "@mui/material";
import { useState } from "react";
import TuneIcon from "@mui/icons-material/Tune";
import { useDispatch, useSelector } from "react-redux";
import { SlaughterAllocateToGuild } from "../../../slaughter-house/components/slaughter-allocate-to-guild/SlaughterAllocateToGuild";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import { StewardNorEnterdBarChangeState } from "../../../guild/components/StewardNorEnterdBarChangeState";
import { slaughterDeleteAllocatedService } from "../../../slaughter-house/services/salughter-delete-allocated";
import { fetchSlaughterBroadcastAndProducts } from "../../../slaughter-house/services/handle-fetch-slaughter-products";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const StewardShowAllocationsOperations = ({
  item,
  type,
  handleUpdate,
  priceInfo,
  remainWeight,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const openPopover = (event) => {
    setPopoverOpen(true);
    setAnchorEl(event.currentTarget);
  };

  const closePopover = () => {
    setPopoverOpen(false);
    setAnchorEl(null);
  };

  const handleDistributeToGuild = () => {
    closePopover();
    const handleEditSuccess = () => {
      if (updateTable) updateTable(1);
      if (handleUpdate) handleUpdate();
    };
    dispatch(
      OPEN_MODAL({
        title: "ویرایش توزیع و فروش محصول",
        content: (
          <SlaughterAllocateToGuild
            updateTable={handleEditSuccess}
            fetchApiData={handleEditSuccess}
            sellerType="KillHouse"
            sellType="exclusive"
            priceInfo={priceInfo}
            remainWeight={remainWeight}
            editData={item}
            item={item}
          />
        ),
      })
    );
  };

  return (
    <Grid>
      <IconButton
        variant="contained"
        color="primary"
        onClick={openPopover}
        disabled={!type && item?.registrationCode}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        open={popoverOpen}
        anchorEl={anchorEl}
        onClose={closePopover}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <div style={{ padding: 10 }}>
          <Grid
            container
            direction="column"
            alignItems="center"
            justifyContent="center"
            gap={1}
          >
            {type && (
              <Button
                size="small"
                color="primary"
                variant="outlined"
                onClick={() => {
                  closePopover();
                  dispatch(
                    OPEN_MODAL({
                      title: "ویرایش اطلاعات بار",
                      content: (
                        <StewardNorEnterdBarChangeState
                          updateTable={updateTable}
                          handleUpdate={handleUpdate}
                          item={item}
                        />
                      ),
                    })
                  );
                }}
              >
                تایید / رد
              </Button>
            )}

            {!type && (
              <Button
                size="small"
                color="primary"
                variant="outlined"
                onClick={handleDistributeToGuild}
              >
                ویرایش
              </Button>
            )}

            {!type && (
              <Button
                size="small"
                disabled={item?.registrationCode}
                variant="outlined"
                color="error"
                onClick={() => {
                  closePopover();
                  dispatch(
                    slaughterDeleteAllocatedService({
                      steward_allocation_key: item.key,
                      role_key: checkPathStartsWith("steward")
                        ? selectedSubUser?.key
                        : "",
                    })
                  ).then(() => {
                    dispatch(
                      fetchSlaughterBroadcastAndProducts({
                        role_key: checkPathStartsWith("steward")
                          ? selectedSubUser?.key
                          : "",
                      })
                    );
                    if (updateTable) updateTable(1);
                    if (handleUpdate) handleUpdate();
                  });
                }}
              >
                حذف
              </Button>
            )}
          </Grid>
        </div>
      </Popover>
    </Grid>
  );
};
