import { Button, InputAdornment, TextField, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { getPolicyProvinceFeeService } from "../../services/get-policy-province-fee";
import { policyChangeProvinceFeeService } from "../../services/policy-change-province-fee";

export const ProvincePolicyProvinceFee = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [textValue, setTextValue] = useState();

  const handleChange = (e) => {
    setTextValue(e.target.value);
  };

  useEffect(() => {
    dispatch(getPolicyProvinceFeeService()).then((r) => {
      setTextValue(r.payload.data.provinceUnion);
    });
  }, []);

  return (
    <Grid container alignItems="center" gap={SPACING.SMALL}>
      <Grid>
        <Typography>مبلغ تعرفه استان:</Typography>
      </Grid>
      <Grid>
        <TextField
          InputLabelProps={{
            shrink: true,
          }}
          size="small"
          label="مبلغ تعرفه "
          type="number"
          value={textValue}
          onChange={handleChange}
          style={{ width: "160px" }}
          InputProps={{
            endAdornment: <InputAdornment position="end">﷼</InputAdornment>,
          }}
        />
      </Grid>
      <Grid>
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              policyChangeProvinceFeeService({
                province_union: Number(textValue),
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.error,
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
