import React, { useContext, useState } from "react";
import {
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { slaughterDeleteOutOfProvinceSell } from "../../services/slaughter-delete-out-province-sell";
import { SlaughterSubmitOutProvinceSell } from "../slaughter-submit-out-province-sell/SlaughterSubmitOutProvinceSell";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";
import { slaughterResendOutProvinceRegistrationCodeService } from "../../services/slaughter-resend-out-province-registration-code";
import TuneIcon from "@mui/icons-material/Tune";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import SendIcon from "@mui/icons-material/Send";

export const SlaughterOutProvinceSalesOperations = ({
  item,
  updateTable,
  fetchApiData,
  page,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [anchorEl, setAnchorEl] = useState(null);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const openPopover = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const handleEdit = () => {
    closePopover();
    dispatch(
      DRAWER({
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        title: "ویرایش فروش خارج از استان",
        content: (
          <SlaughterSubmitOutProvinceSell
            fetchItems={updateTable}
            isEdit={true}
            item={item}
          />
        ),
      })
    );
  };

  const handleDelete = () => {
    closePopover();
    dispatch(slaughterDeleteOutOfProvinceSell(item?.key)).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.data.result,
          severity: "error",
        });
      } else {
        updateTable();
        dispatch(
          fetchSlaughterBroadcastAndProducts({
            role_key: selectedSubUser?.key || "",
          })
        );
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.data.result,
          severity: "success",
        });
      }
    });
  };

  const handleResend = () => {
    closePopover();
    dispatch(
      slaughterResendOutProvinceRegistrationCodeService({
        key: item?.key,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "کد با موفقیت ارسال شد.",
          severity: "success",
        });
        fetchApiData(page);
      }
    });
  };

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

  return (
    <div>
      <IconButton
        aria-describedby={id}
        variant="contained"
        color="primary"
        onClick={openPopover}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={closePopover}
      >
        <List sx={{ py: 1, minWidth: 130 }}>
          <Tooltip title="ویرایش" placement="left-start">
            <ListItem disablePadding>
              <ListItemButton onClick={handleEdit}>
                <ListItemIcon sx={{ minWidth: 36 }}>
                  <EditIcon color="primary" />
                </ListItemIcon>
                <ListItemText
                  primary={
                    <Typography variant="body2" color="primary">
                      ویرایش
                    </Typography>
                  }
                />
              </ListItemButton>
            </ListItem>
          </Tooltip>

          <Tooltip title="حذف" placement="left-start">
            <ListItem disablePadding>
              <ListItemButton onClick={handleDelete}>
                <ListItemIcon sx={{ minWidth: 36 }}>
                  <DeleteIcon color="error" />
                </ListItemIcon>
                <ListItemText
                  primary={
                    <Typography variant="body2" color="error">
                      حذف
                    </Typography>
                  }
                />
              </ListItemButton>
            </ListItem>
          </Tooltip>

          {item?.systemRegistrationCode &&
            item?.registrationCode &&
            !item?.loggedRegistrationCode && (
              <Tooltip title="ارسال مجدد کد" placement="left-start">
                <ListItem disablePadding>
                  <ListItemButton onClick={handleResend}>
                    <ListItemIcon sx={{ minWidth: 36 }}>
                      <SendIcon color="success" />
                    </ListItemIcon>
                    <ListItemText
                      primary={
                        <Typography variant="body2" color="success">
                          ارسال مجدد کد
                        </Typography>
                      }
                    />
                  </ListItemButton>
                </ListItem>
              </Tooltip>
            )}
        </List>
      </Popover>
    </div>
  );
};
