import {
  Button,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useState, useContext } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import TuneIcon from "@mui/icons-material/Tune";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import SettingsSuggestIcon from "@mui/icons-material/SettingsSuggest";
import { ProvinceSubmitBarDifference } from "../province-submit-bar-difference/ProvinceSubmitBarDifference";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import {
  provinceDeleteBarDifferenceService,
  provinceEditBarDifferenceService,
} from "../../services/province-bar-differences-services";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { resizeImage } from "../../../../utils/resizeImage";

export const ProvinceBarDifferencesOperations = ({ item, updateTable }) => {
  const dispatch = useDispatch();
  const [anchorEl, setAnchorEl] = useState(null);
  const [openNotif] = useContext(AppContext);

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

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

  const handleDelete = () => {
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container spacing={2}>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(provinceDeleteBarDifferenceService(item?.key)).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: r.payload.data.result,
                        severity: "success",
                      });
                    }
                  }
                );
              }}
            >
              تایید
            </Button>
            <Button onClick={() => dispatch(CLOSE_MODAL())}>لغو</Button>
          </Grid>
        ),
      })
    );
    handleClose();
  };

  const openAcceptRejectModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "تایید/ رد",
        content: (
          <AcceptRejectModal
            item={item}
            updateTable={updateTable}
            openNotif={openNotif}
          />
        ),
      })
    );
    handleClose();
  };

  return (
    <div>
      <IconButton aria-describedby={id} color="primary" onClick={handleClick}>
        <TuneIcon />
      </IconButton>

      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "left" }}
      >
        <List dense sx={{ py: 0, minWidth: 200 }}>
          {getRoleFromUrl() !== "KillHouse" ? (
            <>
              <Tooltip title="ویرایش" placement="left-start">
                <ListItem disablePadding>
                  <ListItemButton
                    sx={{ py: 0.5 }}
                    onClick={() => {
                      handleClose();
                      dispatch(
                        DRAWER({
                          right: !(window.innerWidth <= 600),
                          bottom: window.innerWidth <= 600,
                          content: (
                            <ProvinceSubmitBarDifference
                              item={item}
                              isEdit
                              updateTable={updateTable}
                            />
                          ),
                          title: "ویرایش اختلاف کشتار",
                        })
                      );
                    }}
                  >
                    <ListItemIcon sx={{ minWidth: 40 }}>
                      <EditIcon color="primary" fontSize="small" />
                    </ListItemIcon>
                    <ListItemText
                      primary="ویرایش اختلاف کشتار"
                      primaryTypographyProps={{
                        color: "primary",
                        variant: "body2",
                      }}
                    />
                  </ListItemButton>
                </ListItem>
              </Tooltip>

              <Tooltip title="حذف" placement="left-start">
                <ListItem disablePadding>
                  <ListItemButton
                    sx={{ py: 0.5 }}
                    onClick={() => {
                      handleClose();
                      handleDelete();
                    }}
                  >
                    <ListItemIcon sx={{ minWidth: 40 }}>
                      <DeleteIcon color="error" fontSize="small" />
                    </ListItemIcon>
                    <ListItemText
                      primary="حذف اختلاف کشتار"
                      primaryTypographyProps={{
                        color: "error",
                        variant: "body2",
                      }}
                    />
                  </ListItemButton>
                </ListItem>
              </Tooltip>
            </>
          ) : (
            <Tooltip title="تایید/ رد" placement="left-start">
              <ListItem disablePadding>
                <ListItemButton
                  sx={{ py: 0.5 }}
                  onClick={() => {
                    handleClose();
                    openAcceptRejectModal();
                  }}
                >
                  <ListItemIcon sx={{ minWidth: 40 }}>
                    <SettingsSuggestIcon color="primary" fontSize="small" />
                  </ListItemIcon>
                  <ListItemText
                    primary="تایید/ رد اختلاف"
                    primaryTypographyProps={{
                      color: "primary",
                      variant: "body2",
                    }}
                  />
                </ListItemButton>
              </ListItem>
            </Tooltip>
          )}
        </List>
      </Popover>
    </div>
  );
};

const AcceptRejectModal = ({ item, updateTable, openNotif }) => {
  const dispatch = useDispatch();
  const [acceptorMessage, setAcceptorMessage] = useState("");
  const [profileImages, setProfileImages] = useState([]);
  const [acceptorImages, setAcceptorImages] = useState([]);

  const handleEditOrAccept = (newState) => {
    dispatch(
      provinceEditBarDifferenceService({
        bar_key: item?.key,
        kill_house_check: true,
        acceptor_message: acceptorMessage,
        acceptor_images: acceptorImages,
        state: newState,
      })
    ).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: r.payload.data.result,
          severity: "success",
        });
      }
    });
  };

  const handleImageChange = (imageList) => {
    if (imageList.length === 0) {
      setProfileImages([]);
      setAcceptorImages([]);
      return;
    }

    Promise.all(
      imageList.map(
        (image) =>
          new Promise((resolve) =>
            resizeImage(image.file, (resized) => resolve(fixBase64(resized)))
          )
      )
    ).then((resizedImages) => {
      setProfileImages(imageList);
      setAcceptorImages(resizedImages);
    });
  };

  return (
    <Grid container spacing={2} justifyContent="center">
      <Grid item xs={12} justifyContent="center">
        <Typography variant="body2" color="error">
          توجه: در صورت تایید حجم قطعه اعلام شده، حجم مورد نظر از سالن مرغدار
          کسر شده و با میانگین وزن کشتار مرغدار به انبار شما اضافه می‌گردد.
        </Typography>
      </Grid>
      <Grid item xs={12} justifyContent="center">
        <ImageUpload
          onChange={handleImageChange}
          images={profileImages}
          maxNumber={1}
          title="سند"
        />
      </Grid>
      <Grid item xs={12} justifyContent="center">
        <TextField
          label="توضیحات"
          value={acceptorMessage}
          onChange={(e) => setAcceptorMessage(e.target.value)}
          fullWidth
        />
      </Grid>

      <Grid item>
        <Button
          variant="contained"
          color="success"
          onClick={() => handleEditOrAccept("accepted")}
        >
          تایید
        </Button>
      </Grid>
      <Grid item>
        <Button
          variant="contained"
          color="error"
          onClick={() => handleEditOrAccept("rejected")}
        >
          رد
        </Button>
      </Grid>
    </Grid>
  );
};
