import {
  FormControlLabel,
  IconButton,
  Popover,
  Switch,
  Tooltip,
  Button,
  Typography,
} from "@mui/material";
import { useContext, useState } from "react";
import TuneIcon from "@mui/icons-material/Tune";
import EditIcon from "@mui/icons-material/Edit";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import {
  DRAWER,
  OPEN_MODAL,
  CLOSE_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { ProvicneJahadSubmitHerd } from "../province-jahad-submit-herd/ProvicneJahadSubmitHerd";
import { AppContext } from "../../../../contexts/AppContext";
import UnarchiveIcon from "@mui/icons-material/Unarchive";
import ArchiveIcon from "@mui/icons-material/Archive";
import {
  provinceJahadEditHerdService,
  provinceJahadDeleteHerdService,
} from "../../services/province-jahad-submit-herd";

export const ProvinceJahadHerdsOperations = ({
  item,
  // fileUrl,
  updateTable,
  getDashboardData,
  dataType,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

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

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

  const handleArchive = () => {
    dispatch(
      provinceJahadDeleteHerdService({
        live_stock_key: item?.key,
      })
    ).then((r) => {
      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());
      }
    });
    handleClose();
  };

  const handleUnarchive = () => {
    dispatch(
      provinceJahadEditHerdService({
        live_stock_key: item?.key,
        return_from_archive: true,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        updateTable();
        dispatch(CLOSE_MODAL());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
    handleClose();
  };

  const showConfirmationModal = (action) => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container spacing={2}>
            <Grid
              item
              xs={12}
              container
              justifyContent="center"
              alignItems="center"
            >
              <Typography variant="body2">
                {action === "archive"
                  ? "آیا می‌خواهید این گله را به بایگانی منتقل کنید؟"
                  : "آیا می‌خواهید این گله را از بایگانی خارج کنید؟"}
              </Typography>
            </Grid>
            <Grid item xs={6}>
              <Button
                fullWidth
                variant="contained"
                color="primary"
                onClick={() => {
                  if (action === "archive") {
                    handleArchive();
                  } else {
                    handleUnarchive();
                  }
                }}
              >
                بله
              </Button>
            </Grid>
            <Grid item xs={6}>
              <Button
                fullWidth
                variant="outlined"
                onClick={() => dispatch(CLOSE_MODAL())}
              >
                خیر
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

  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}
      >
        <div
          style={{ padding: "20px", display: "flex", flexDirection: "column" }}
        >
          <Tooltip title={"ویرایش"} placement="left-start">
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                handleClose();
                dispatch(
                  DRAWER({
                    title: "ویرایش اطلاعات",
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: (
                      <ProvicneJahadSubmitHerd
                        updateTable={updateTable}
                        getDashboardData={getDashboardData}
                        item={item}
                      />
                    ),
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Tooltip>

          <FormControlLabel
            control={
              <Switch
                size="small"
                checked={item?.active}
                onChange={() => {
                  dispatch(
                    provinceJahadEditHerdService({
                      live_stock_key: item?.key,
                      active: !item?.active,
                    })
                  ).then((r) => {
                    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",
                      });
                    }
                  });
                }}
                color="primary"
              />
            }
            label={item?.active ? "فعال" : "غیرفعال"}
            style={{
              justifyContent: "center",
              alignItems: "center",
              display: "flex",
            }}
          />
          {dataType === "archive" ? (
            <Tooltip title="برگشت از بایگانی" placement="left-start">
              <IconButton
                variant="outlined"
                color="primary"
                onClick={() => showConfirmationModal("unarchive")}
                style={{ marginTop: "10px" }}
              >
                <UnarchiveIcon />
              </IconButton>
            </Tooltip>
          ) : (
            <Tooltip title="انتقال به بایگانی" placement="left-start">
              <IconButton
                variant="outlined"
                color="error"
                onClick={() => showConfirmationModal("archive")}
                style={{ marginTop: "10px" }}
              >
                <ArchiveIcon />
              </IconButton>
            </Tooltip>
          )}
        </div>
      </Popover>
    </Grid>
  );
};
