import {
  Button,
  IconButton,
  Popover,
  Tooltip,
  Typography,
} from "@mui/material";
import { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { provinceCloseAllocationService } from "../../services/province-close-allocation";
import { provinceGetAllRequests } from "../../services/province-get-all-requests";
import ArchiveIcon from "@mui/icons-material/Archive";
import ConstructionIcon from "@mui/icons-material/Construction";
import { ProvinceAllocation } from "../../../file/components/province-allocation/ProvinceAllocation";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import TuneIcon from "@mui/icons-material/Tune";
import { ProvincePoultryRequestEnterConfirmationCode } from "../province-poultry-request-enter-confirmation-code/ProvincePoultryRequestEnterConfirmationCode";

export const ProvinceAllocateOperations = ({
  item,
  remainQuantity,
  getItemFreeSaleInProvince,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const [openNotif, , selectedDate1] = useContext(AppContext);

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

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

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

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

  return (
    <Grid>
      <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}
      >
        <div
          style={{ padding: "20px", display: "flex", flexDirection: "column" }}
        >
          <Tooltip title="تخصیص" placement="right">
            <IconButton
              color="primary"
              onClick={() => {
                handleClose();
                if (
                  item?.poultryRequest?.priceConfirmation === true &&
                  !item?.poultryRequest?.inputPriceConfirmationCode
                ) {
                  dispatch(
                    OPEN_MODAL({
                      title: "ورود کد احراز",
                      content: (
                        <ProvincePoultryRequestEnterConfirmationCode
                          updateTable={updateTable}
                          item={item?.poultryRequest}
                        />
                      ),
                    })
                  );
                } else if (item?.provinceState === "pending") {
                  dispatch(
                    OPEN_MODAL({
                      title: "اطلاعیه سیستم",
                      content: (
                        <Grid>
                          <Typography variant="body1" color="secondary">
                            درخواست ابتدا باید توسط استان تایید شود!
                          </Typography>
                          <Grid container justifyContent="center">
                            <Grid
                              item
                              container
                              xs={12}
                              justifyContent="center"
                              mt={2}
                            >
                              <Button
                                size="small"
                                color="success"
                                variant="contained"
                                onClick={() => dispatch(CLOSE_MODAL())}
                              >
                                متوجه شدم
                              </Button>
                            </Grid>
                          </Grid>
                        </Grid>
                      ),
                    })
                  );
                } else {
                  dispatch(
                    DRAWER({
                      title: "انجام عملیات تخصیص",
                      // right: !(window.innerWidth <= 600),
                      top: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      size: 1000,
                      content: (
                        <ProvinceAllocation
                          remainQuantity={remainQuantity}
                          item={item}
                          id={
                            item?.poultryRequest?.process?.poultry
                              ?.poultryRequestId
                          }
                          orginalQuantity={
                            item?.poultryRequest?.process?.poultry
                              ?.poultryQuantity
                          }
                          file={item?.poultryRequest?.process}
                          getItemFreeSaleInProvince={getItemFreeSaleInProvince}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }
              }}
            >
              <ConstructionIcon />
            </IconButton>
          </Tooltip>
          <Tooltip title="اتمام" placement="right">
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: "آیا مطمئن هستید؟",
                    content: (
                      <Grid container>
                        <Button
                          variant="contained"
                          onClick={() => {
                            dispatch(
                              provinceCloseAllocationService({
                                allocated_number:
                                  item?.quantity?.allocatedNumber,
                                final_state: "archive",
                                key: item?.poultryRequest?.key,
                              })
                            ).then((r) => {
                              dispatch(provinceGetAllRequests(selectedDate1));
                              if (r.payload.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: r.payload.error,
                                  severity: "error",
                                });
                              } else {
                                dispatch(CLOSE_MODAL());

                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                              }
                            });
                          }}
                        >
                          تایید
                        </Button>
                        <Button
                          onClick={() => {
                            dispatch(CLOSE_MODAL());
                          }}
                        >
                          لغو
                        </Button>
                      </Grid>
                    ),
                  })
                );
              }}
            >
              <ArchiveIcon />
            </IconButton>
          </Tooltip>
          {/* <Tooltip title="مشاهده" placement="right">
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                handleClose();
                navigate(
                  ROUTE_PROVINCE_FILE +
                    item?.poultryRequest?.process?.poultry?.poultryRequestId
                );
              }}
            >
              <PlagiarismIcon />
            </IconButton>
          </Tooltip> */}
        </div>
      </Popover>
    </Grid>
  );
};
