import React, { useContext, useState } from "react";
import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Typography,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import EditIcon from "@mui/icons-material/Edit";
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
import DeleteIcon from "@mui/icons-material/Delete";
import { Grid } from "../../../../components/grid/Grid";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { slaughterInventoryFinalSubmitService } from "../../services/slaughter-inventory-final-submit";
import { slaughterDeleteAllocatedService } from "../../services/salughter-delete-allocated";
import { SlaughterAllocateToGuild } from "../slaughter-allocate-to-guild/SlaughterAllocateToGuild";
import { SlaughterAllocateForFreezing } from "../slaughter-allocate-for-freezing/SlaughterAllocateForFreezing";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";

export const SlaughterManageInventoryAllocationOperations = ({
  fetchApiData,
  item,
  priceInfo,
  remainWeight,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);

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

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

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

  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

  const handleEdit = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "ویرایش تخصیص",
        content:
          item?.allocationType === "ColdHouse" ? (
            <SlaughterAllocateForFreezing
              fetchApiData={fetchApiData}
              editData={item}
              priceInfo={priceInfo}
              remainWeight={remainWeight}
            />
          ) : (
            <SlaughterAllocateToGuild
              fetchApiData={fetchApiData}
              editData={item}
              priceInfo={priceInfo}
              remainWeight={remainWeight}
            />
          ),
      })
    );
  };

  const handleFinalSubmit = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "ثبت نهایی",
        content: (
          <Grid container gap={SPACING.SMALL}>
            <Typography>
              در صورت ثبت نهایی انجام هیچگونه عملیاتی مانند حذف و ویرایش امکان
              پذیر نمی باشد.
            </Typography>
            <Grid container direction="column" gap={SPACING.TINY} width="100%">
              <Button
                fullWidth
                variant="contained"
                onClick={() => {
                  dispatch(
                    slaughterInventoryFinalSubmitService({
                      steward_allocation_list: [item?.key],
                    })
                  ).then((r) => {
                    dispatch(CLOSE_MODAL());
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      fetchApiData(1);
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              >
                تایید
              </Button>
              <Button
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  dispatch(CLOSE_MODAL());
                }}
              >
                لغو
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

  const handleDelete = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container spacing={2}>
            <Grid item>
              <Button
                variant="contained"
                color="error"
                onClick={() => {
                  dispatch(
                    slaughterDeleteAllocatedService({
                      steward_allocation_key: item.key,
                    })
                  ).then(() => {
                    dispatch(CLOSE_MODAL());
                    dispatch(fetchSlaughterBroadcastAndProducts());
                    fetchApiData(1);
                  });
                }}
              >
                تایید
              </Button>
            </Grid>
            <Grid item>
              <Button
                onClick={() => {
                  dispatch(CLOSE_MODAL());
                }}
              >
                لغو
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

  const options = [
    {
      key: "edit",
      label: "ویرایش",
      icon: EditIcon,
      color: "primary.main",
      action: handleEdit,
    },
  ];

  if (!item?.registrationCode) {
    options.push({
      key: "finalSubmit",
      label: "تایید نهایی",
      icon: CheckCircleOutlineIcon,
      color: "info.main",
      action: handleFinalSubmit,
    });
  }

  if (!item?.registrationCode) {
    options.push({
      key: "delete",
      label: "حذف",
      icon: DeleteIcon,
      color: "error.main",
      action: handleDelete,
    });
  }

  return (
    <Grid container>
      <IconButton
        size="small"
        disabled={item?.registrationCode}
        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}
      >
        <List sx={{ minWidth: 160, p: 0.5 }}>
          {options.map((option) => {
            const IconComponent = option.icon;
            return (
              <ListItemButton
                key={option.key}
                onClick={option.action}
                sx={{
                  borderRadius: 1,
                  mb: 0.25,
                  py: 0.5,
                  "&:last-of-type": { mb: 0 },
                }}
              >
                <ListItemIcon sx={{ minWidth: 32, color: option.color }}>
                  <IconComponent fontSize="small" />
                </ListItemIcon>
                <ListItemText
                  primary={option.label}
                  primaryTypographyProps={{
                    sx: {
                      color: option.color,
                      fontSize: "0.82rem",
                      fontWeight: 600,
                    },
                  }}
                />
              </ListItemButton>
            );
          })}
        </List>
      </Popover>
    </Grid>
  );
};
