import React, { useContext } from "react";
import {
  Button,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  FormHelperText,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { provinceKillhousesPaidFeesChangePaymentTypeService } from "../../services/province-killhouses-paid-fee-change-payment-type-service";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

const validationSchema = Yup.object({
  paymentType: Yup.string().required("نوع پرداخت را وارد کنید!"),
});

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

  const formik = useFormik({
    initialValues: {
      paymentType: item?.transactionType ? item?.transactionType : "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        provinceKillhousesPaidFeesChangePaymentTypeService({
          transaction_key: item?.key,
          transaction_type: values.paymentType,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          fetchApiData(1);
          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  return (
    <Grid xs={12} container>
      <FormControl
        fullWidth
        margin="normal"
        error={formik.touched.paymentType && Boolean(formik.errors.paymentType)}
      >
        <InputLabel id="payment-type-label">نوع پرداخت</InputLabel>
        <Select
          fullWidth
          labelId="payment-type-label"
          id="paymentType"
          name="paymentType"
          value={formik.values.paymentType}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          label="نوع پرداخت"
        >
          <MenuItem value="wage-gateway-auto">آنلاین</MenuItem>
          <MenuItem value="wage-gateway-manual">دستی</MenuItem>
          <MenuItem value="correspondence">مکاتبات</MenuItem>
        </Select>
        {formik.touched.paymentType && formik.errors.paymentType ? (
          <FormHelperText>{formik.errors.paymentType}</FormHelperText>
        ) : null}
      </FormControl>
      <Button
        color="primary"
        variant="contained"
        fullWidth
        type="submit"
        onClick={formik.handleSubmit}
      >
        ثبت
      </Button>
    </Grid>
  );
};

export default ProvinceKillhousePaidFeeChangePaymentType;
