import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  IconButton,
  Popover,
  Typography,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import CloseIcon from "@mui/icons-material/Close";
import { ProvinceFreeSaleEditRequest } from "../province-free-sale-edit-request/ProvinceFreeSaleEditRequest";
import { provinceOutRequestCancelRequest } from "../../services/provinceOutRequestCancelRequest";
import TuneIcon from "@mui/icons-material/Tune";
import ThumbDownOffAltIcon from "@mui/icons-material/ThumbDownOffAlt";
import { ProvinceFreeSalesRejectRequest } from "../province-free-sales-reject-request/ProvinceFreeSalesRejectRequest";
import { provinceCheckFreeSaleService } from "../../services/province-check-free-sale";
import CheckIcon from "@mui/icons-material/Check";
import { useDispatch } from "react-redux";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceFreeSalsesSendSmsService } from "../../services/province-free-sales-send-sms-again";
import SmsIcon from "@mui/icons-material/Sms";

export const ProvinceFreeSalesOperations = ({ item, fetchApiData }) => {
  const dispatch = useDispatch();

  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 role = getRoleFromUrl();

  const handleEdit = () => {
    dispatch(
      DRAWER({
        title: "ویرایش درخواست",
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        content: (
          <ProvinceFreeSaleEditRequest
            item={item}
            fetchApiData={fetchApiData}
          />
        ),
      })
    );
  };

  const handleApprove = () => {
    dispatch(
      OPEN_MODAL({
        title: "آیا از تایید درخواست مطمئن هستید؟",
        content: (
          <Grid>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  provinceCheckFreeSaleService({
                    poultry_request_key: item?.key,
                    // state: "accepted",
                    // message: "",
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(CLOSE_MODAL());
                    fetchApiData(1);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              بله
            </Button>
            <Button
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              خیر
            </Button>
          </Grid>
        ),
      })
    );
  };

  const handleResendSms = () => {
    dispatch(
      OPEN_MODAL({
        title: "پیامک مجددا ارسال شود؟",
        content: (
          <Grid>
            {item?.hasWage && (
              <Typography fullWidth variant="body2">
                پیامک پرداخت مجددا برای {item?.payerFullname} {"‌‌"} به شماره
                موبایل{" "}
                {item?.payerType === "buyer"
                  ? item?.outProvincePoultryRequestBuyer?.mobile
                  : item?.poultry?.user?.mobile}{" "}
                ارسال میشود.
              </Typography>
            )}
            <Grid xs={12} container justifyContent="center" mt={2}>
              <Button
                variant="contained"
                onClick={() => {
                  dispatch(provinceFreeSalsesSendSmsService(item?.key)).then(
                    (r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        dispatch(CLOSE_MODAL());
                        fetchApiData(1);
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    }
                  );
                }}
              >
                بله
              </Button>
              <Button
                onClick={() => {
                  dispatch(CLOSE_MODAL());
                }}
              >
                خیر
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

  const handleCancel = () => {
    dispatch(
      OPEN_MODAL({
        title: "آیا از لغو درخواست مطمئن هستید؟",
        content: (
          <Grid>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  provinceOutRequestCancelRequest({
                    role: getRoleFromUrl(),
                    poultry_request_key: item.key,
                  })
                ).then((r) => {
                  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",
                    });
                  }
                });
                dispatch(CLOSE_MODAL());
              }}
            >
              بله
            </Button>
            <Button
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              خیر
            </Button>
          </Grid>
        ),
      })
    );
  };

  const handleReject = () => {
    dispatch(
      OPEN_MODAL({
        title: "رد درخواست فروش خارج از استان",
        content: (
          <ProvinceFreeSalesRejectRequest
            item={item}
            fetchApiData={fetchApiData}
          />
        ),
      })
    );
  };

  const options = [
    {
      key: "edit",
      label: "ویرایش",
      color: "primary.main",
      icon: <EditIcon />,
      action: handleEdit,
    },
    role !== "CityOperator" && {
      key: "approve",
      label: "تایید درخواست",
      color: "success.main",
      icon: <CheckIcon />,
      action: handleApprove,
      disabled: item.provinceState !== "pending",
    },
    (role === "CityOperator" ||
      role === "ProvinceOperator" ||
      role === "SuperAdmin" ||
      role === "AdminX") && {
      key: "resendSms",
      label: "ارسال مجدد پیامک",
      color: "info.main",
      icon: <SmsIcon />,
      action: handleResendSms,
      disabled: item.outState !== "در انتظار پرداخت",
    },
    {
      key: "cancel",
      label: "لغو",
      color: "error.main",
      icon: <CloseIcon />,
      action: handleCancel,
      disabled:
        !item.provinceState === "pending" || !item.provinceState === "accepted",
    },
    role !== "CityOperator" && {
      key: "reject",
      label: "رد درخواست",
      color: "error.main",
      icon: <ThumbDownOffAltIcon />,
      action: handleReject,
      disabled:
        !item.provinceState === "pending" ||
        !item.provinceState === "accepted" ||
        item.outState === "در انتظار پرداخت",
    },
  ].filter(Boolean);

  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={{ width: 176, py: 0.5, px: 1 }}>
          {options.map((option) => (
            <ListItemButton
              key={option.key}
              onClick={() => {
                handleClose();
                option.action();
              }}
              disabled={Boolean(option.disabled)}
              sx={{
                borderRadius: 1,
                mb: 0.5,
                color: option.disabled ? "text.disabled" : option.color,
                "&:last-of-type": {
                  mb: 0,
                },
              }}
            >
              <ListItemIcon
                sx={{
                  color: option.disabled ? "text.disabled" : option.color,
                  minWidth: 32,
                }}
              >
                {React.cloneElement(option.icon, { fontSize: "small" })}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography
                    sx={{
                      color: option.disabled ? "text.disabled" : option.color,
                      fontWeight: 600,
                      fontSize: "0.85rem",
                    }}
                  >
                    {option.label}
                  </Typography>
                }
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </Grid>
  );
};
