import {
  Button,
  IconButton,
  Popover,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { useContext, useState } from "react";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import EditIcon from "@mui/icons-material/Edit";
import SettingsSuggestIcon from "@mui/icons-material/SettingsSuggest";
import TuneIcon from "@mui/icons-material/Tune";
import { provincePriceEditService } from "../../services/province-price-edit";
import { ProvineSubmitPrice } from "../province-submit-price/ProvineSubmitPrice";

export const ProvincePriceEdit = ({ 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 role = getRoleFromUrl();

  const isToday = () => {
    if (!item?.date) return false;
    const today = new Date();
    const itemDate = new Date(item.date);
    return (
      itemDate.getFullYear() === today.getFullYear() &&
      itemDate.getMonth() === today.getMonth() &&
      itemDate.getDate() === today.getDate()
    );
  };

  const handleEdit = () => {
    handleClose();

    if (!isToday()) {
      openNotif({
        msg: "فقط قیمت‌های مربوط به تاریخ امروز قابل ویرایش هستند.",
        severity: "error",
        vertical: "top",
        horizontal: "center",
      });
      return;
    }

    dispatch(
      DRAWER({
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        content: (
          <ProvineSubmitPrice
            item={item}
            isEdit
            updateTable={updateTable}
            onSubmit={(prices) => {
              dispatch(
                provincePriceEditService({
                  id: item.id,
                  prices: {
                    kill_house_price: prices.killHousePrice,
                    wholesaler_price: prices.wholesalerPrice,
                    retailer_price: prices.retailerPrice,
                  },
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    msg: r.payload.error,
                    severity: "error",
                    vertical: "top",
                    horizontal: "center",
                  });
                } else {
                  updateTable();
                  openNotif({
                    msg: "قیمت‌ها با موفقیت ویرایش شدند",
                    severity: "success",
                    vertical: "top",
                    horizontal: "center",
                  });
                }
              });
            }}
          />
        ),
        title: "ویرایش قیمت‌های کارمزد",
      })
    );
  };

  const handleApproval = (state) => {
    dispatch(
      provincePriceEditService({
        id: item.id,
        prices: {
          kill_house_check: true,
          state,
        },
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          msg: r.payload.error,
          severity: "error",
          vertical: "top",
          horizontal: "center",
        });
      } else {
        updateTable();
        dispatch(CLOSE_MODAL());
        openNotif({
          msg: "وضعیت با موفقیت به روز رسانی شد",
          severity: "success",
          vertical: "top",
          horizontal: "center",
        });
      }
    });
  };

  const renderActions = () => {
    if (role !== "KillHouse") {
      return (
        <Tooltip title="ویرایش قیمت‌ها">
          <Button
            size="small"
            startIcon={<EditIcon fontSize="small" />}
            sx={{
              "&.Mui-disabled": {
                backgroundColor: "transparent",
                color: "text.disabled",
              },
            }}
            onClick={handleEdit}
          >
            <Typography variant="body2" fontWeight={600}>
              ویرایش قیمت‌ها
            </Typography>
          </Button>
        </Tooltip>
      );
    } else {
      return (
        <Tooltip title="تایید/رد">
          <Button
            size="small"
            startIcon={<SettingsSuggestIcon fontSize="small" />}
            onClick={() => {
              handleClose();
              dispatch(
                OPEN_MODAL({
                  title: "تایید/ رد",
                  content: (
                    <Grid container spacing={2} justifyContent="center">
                      <Grid item xs={12}>
                        <Typography variant="body2" color="error">
                          توجه: در صورت تایید حجم قطعه اعلام شده، حجم مورد نظر
                          از سالن مرغدار کسر شده و با میانگین وزن کشتار مرغدار
                          به انبار شما اضافه می‌گردد.
                        </Typography>
                      </Grid>
                      <Grid item>
                        <Button
                          color="success"
                          variant="contained"
                          onClick={() => handleApproval("accepted")}
                        >
                          تایید
                        </Button>
                      </Grid>
                      <Grid item>
                        <Button
                          color="error"
                          variant="contained"
                          onClick={() => handleApproval("rejected")}
                        >
                          رد
                        </Button>
                      </Grid>
                    </Grid>
                  ),
                })
              );
            }}
            sx={{
              "&.Mui-disabled": {
                backgroundColor: "transparent",
                color: "text.disabled",
              },
            }}
          >
            <Typography variant="body2" fontWeight={600}>
              تایید / رد
            </Typography>
          </Button>
        </Tooltip>
      );
    }
  };

  return (
    <div>
      <IconButton
        aria-describedby={id}
        color="primary"
        onClick={handleClick}
        disabled={!isToday()}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "left" }}
      >
        <div style={{ padding: "10px" }}>
          <Grid
            container
            direction="column"
            gap={1}
            alignItems="flex-start"
            style={{ width: 150 }}
          >
            {renderActions()}
          </Grid>
        </div>
      </Popover>
    </div>
  );
};
