import React, { useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { provincePaidFeesEditDescription } from "../../services/province-paid-fees-edit-description";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceKillHousePaidFeeEditDescription = ({
  fetchApiData,
  item,
}) => {
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      description: item?.description ? item?.description : "",
    },
    validationSchema: Yup.object({
      description: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را پر کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid xs={12} container direction="column" gap={2}>
      <TextField
        id="description"
        label="توضیحات"
        multiline
        rows={5}
        variant="outlined"
        sx={{ width: "100%", height: "100%" }}
        value={formik.values.description}
        error={
          formik.touched.description ? Boolean(formik.errors.description) : null
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.description && Boolean(formik.errors.description)
            ? formik.errors.description
            : null
        }
      />

      <Grid>
        <Button
          fullWidth
          variant="contained"
          disabled={!formik.isValid}
          onClick={() => {
            dispatch(
              provincePaidFeesEditDescription({
                transaction_key: item?.key,
                description: formik.values.description,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
                dispatch(CLOSE_MODAL());
                fetchApiData(1);
              }
            });
          }}
        >
          ویرایش توضیحات
        </Button>
      </Grid>
    </Grid>
  );
};
