import React, { useContext } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import { provinceTradePanelEnterMarketCodeService } from "../../services/province-trade-panel-enter-market-code-service";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

const validationSchema = yup.object({
  marketCode: yup
    .string()
    .required("کد احراز الزامی است")
    .matches(/^[0-9]+$/, "کد احراز باید فقط شامل اعداد باشد"),
});

export const ProvinceTradePanelEnterMarketCode = ({ item, updateAll }) => {
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      marketCode: item?.inputMarketCode || "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        provinceTradePanelEnterMarketCodeService({
          key: item?.key,
          input_market_code: values.marketCode,
        })
      ).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());
          updateAll();
        }
      });
    },
  });

  return (
    <Grid container xs={12} justifyContent="center" gap={2} direction="column">
      <TextField
        size="small"
        fullWidth
        label="کد احراز"
        name="marketCode"
        value={formik.values.marketCode}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={formik.touched.marketCode && Boolean(formik.errors.marketCode)}
        helperText={formik.touched.marketCode && formik.errors.marketCode}
      />

      <Button
        onClick={formik.handleSubmit}
        type="submit"
        variant="contained"
        color="primary"
        fullWidth
        disabled={!formik.isValid}
      >
        ثبت
      </Button>
    </Grid>
  );
};
