import {
  Button,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Tooltip,
} from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { avicultureHatchingRequestsService } from "../../../aviculture/services/aviculture-hatching-requests";
import { archiveAvicaltureRequestService } from "../../../city/services/archive-avicalture-request";
import ArchiveIcon from "@mui/icons-material/Archive";
import DeleteIcon from "@mui/icons-material/Delete";
import { removeAvicaltureRequestService } from "../../../city/services/remove-avicalture-request";
import TuneIcon from "@mui/icons-material/Tune";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
import { useNavigate } from "react-router-dom";
import EditIcon from "@mui/icons-material/Edit";
import { CityUpdateKillRequest } from "../../../city/components/city-update-kill-request/CityUpdateKillRequest";
import { ProvincePoultryRequestEnterConfirmationCode } from "../province-poultry-request-enter-confirmation-code/ProvincePoultryRequestEnterConfirmationCode";
import VpnKeyIcon from "@mui/icons-material/VpnKey";

export const ProvinceManagePoultryRequestOperations = ({
  item,
  fileUrl,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [openNotif] = useContext(AppContext);

  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const [anchorEl, setAnchorEl] = useState(null);

  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}
      >
        <List dense sx={{ minWidth: 220, py: 0 }}>
          {item.hatching.fileState === "confirmation_code_pending" && (
            <Tooltip title={"ورود کد احراز"} placement="left-start">
              <ListItem disablePadding>
                <ListItemButton
                  onClick={() => {
                    handleClose();
                    dispatch(
                      OPEN_MODAL({
                        title: "ورود کد احراز",
                        content: (
                          <ProvincePoultryRequestEnterConfirmationCode
                            updateTable={updateTable}
                            item={item}
                          />
                        ),
                      })
                    );
                  }}
                >
                  <ListItemIcon>
                    <VpnKeyIcon color="primary" />
                  </ListItemIcon>
                  <ListItemText primary="ورود کد احراز" />
                </ListItemButton>
              </ListItem>
            </Tooltip>
          )}
          <Tooltip title={"ویرایش تعداد کشتار"} placement="left-start">
            <ListItem disablePadding>
              <ListItemButton
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "ویرایش تعداد کشتار",
                      content: (
                        <CityUpdateKillRequest
                          updateTable={updateTable}
                          item={item}
                        />
                      ),
                    })
                  );
                }}
              >
                <ListItemIcon>
                  <EditIcon color="primary" />
                </ListItemIcon>
                <ListItemText primary="ویرایش تعداد کشتار" />
              </ListItemButton>
            </ListItem>
          </Tooltip>
          <Tooltip title={"اتمام پرونده"} placement="left-start">
            <ListItem disablePadding>
              <ListItemButton
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "آیا مطمئن هستید؟",
                      content: (
                        <Grid
                          display="flex"
                          justifyContent="space-between"
                          gap={SPACING.SMALL}
                        >
                          <Button
                            variant="contained"
                            onClick={() => {
                              dispatch(
                                archiveAvicaltureRequestService({
                                  allocated_number:
                                    item.quantity - item?.remainQuantity,
                                  final_state: "archive",
                                  key: item?.key,
                                })
                              ).then((r) => {
                                updateTable();
                                dispatch(
                                  avicultureHatchingRequestsService({
                                    selectedDate1,
                                    selectedDate2,
                                  })
                                );
                                if (r.payload.error) {
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: r.payload.error,
                                    severity: "error",
                                  });
                                } else {
                                  updateTable();
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: "عملیات با موفقیت انجام شد.",
                                    severity: "success",
                                  });
                                  dispatch(CLOSE_MODAL());
                                }
                              });
                            }}
                          >
                            بله
                          </Button>
                          <Button
                            variant="contained"
                            color="error"
                            onClick={() => {
                              dispatch(CLOSE_MODAL());
                            }}
                          >
                            خیر
                          </Button>
                        </Grid>
                      ),
                    })
                  );
                }}
              >
                <ListItemIcon>
                  <ArchiveIcon color="primary" />
                </ListItemIcon>
                <ListItemText primary="اتمام پرونده" />
              </ListItemButton>
            </ListItem>
          </Tooltip>
          <Tooltip title={"مشاهده پرونده"} placement="left-start">
            <ListItem disablePadding>
              <ListItemButton
                onClick={() => {
                  handleClose();
                  navigate(fileUrl + item?.id);
                }}
              >
                <ListItemIcon>
                  <PlagiarismIcon color="primary" />
                </ListItemIcon>
                <ListItemText primary="مشاهده پرونده" />
              </ListItemButton>
            </ListItem>
          </Tooltip>
          <Tooltip title={"حذف درخواست کشتار"} placement="left-start">
            <ListItem disablePadding>
              <ListItemButton
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "آیا مطمئن هستید؟",
                      content: (
                        <Grid
                          display="flex"
                          justifyContent="space-between"
                          gap={SPACING.SMALL}
                        >
                          <Button
                            variant="contained"
                            onClick={() => {
                              dispatch(
                                removeAvicaltureRequestService(item?.id)
                              ).then((r) => {
                                if (r.payload.error) {
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: r.payload.error,
                                    severity: "error",
                                  });
                                } else {
                                  updateTable();
                                  dispatch(
                                    avicultureHatchingRequestsService({
                                      selectedDate1,
                                      selectedDate2,
                                    })
                                  );
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: "عملیات با موفقیت انجام شد.",
                                    severity: "success",
                                  });
                                  dispatch(CLOSE_MODAL());
                                }
                              });
                            }}
                          >
                            بله
                          </Button>
                          <Button
                            variant="contained"
                            color="error"
                            onClick={() => {
                              dispatch(CLOSE_MODAL());
                            }}
                          >
                            خیر
                          </Button>
                        </Grid>
                      ),
                    })
                  );
                }}
              >
                <ListItemIcon>
                  <DeleteIcon color="error" />
                </ListItemIcon>
                <ListItemText
                  primary="حذف درخواست کشتار"
                  primaryTypographyProps={{ color: "error" }}
                />
              </ListItemButton>
            </ListItem>
          </Tooltip>
        </List>
      </Popover>
    </Grid>
  );
};
