import { Button, InputAdornment } from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceEditUnpaidFeeService } from "../../services/province-edit-unpaid-fee";

export const ProvinceEditUnpaidFee = ({ item, updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [value, setValue] = useState(item?.provinceRequest?.totalAmount);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <Grid container gap={SPACING.TINY}>
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        label="مبلغ تعرفه "
        value={value}
        onChange={handleChange}
        InputProps={{
          endAdornment: <InputAdornment position="start">ریال</InputAdornment>,
        }}
      />
      <Button
        fullWidth
        variant="contained"
        onClick={() => {
          dispatch(
            provinceEditUnpaidFeeService({
              province_kill_request_key:
                item.provinceRequest.provinceKillRequestKey,
              total_amount: value,
              role: getRoleFromUrl(),
            })
          ).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",
              });
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
