import React, { useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { Button, TextField } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { pspSubmitPos } from "../../services/psp-submit-pos";
import { DRAWER, LOADING_START } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";

export const PspCreatePos = ({ item, updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      reciver: "",
      terminal: "",
      serial: "",
      password: "",
    },
    validationSchema: Yup.object({
      reciver: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      terminal: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
      password: Yup.string()
        .matches(/^\d{4}$/, "پسورد باید یک عدد 4 رقمی باشد")
        .typeError("لطفا یک عدد 4 رقمی وارد کنید."),
      serial: Yup.string(),
    }),
  });

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

  return (
    <Grid gap={SPACING.SMALL} container xs={12}>
      <TextField
        id="reciver"
        label="شماره پذیرنده"
        variant="outlined"
        sx={{ width: "100%" }}
        value={formik.values.reciver}
        error={formik.touched.reciver ? Boolean(formik.errors.reciver) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.reciver && Boolean(formik.errors.reciver)
            ? formik.errors.reciver
            : null
        }
      />
      <TextField
        id="terminal"
        label="شماره ترمینال"
        variant="outlined"
        sx={{ width: "100%" }}
        value={formik.values.terminal}
        error={formik.touched.terminal ? Boolean(formik.errors.terminal) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.terminal && Boolean(formik.errors.terminal)
            ? formik.errors.terminal
            : null
        }
      />

      <TextField
        id="serial"
        name="serial"
        label="شماره سریال دستگاه"
        variant="outlined"
        value={formik.values.serial}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.serial && Boolean(formik.errors.serial)
            ? formik.errors.serial
            : null
        }
        error={formik.touched.serial && Boolean(formik.errors.serial)}
      />
      <TextField
        id="password"
        name="password"
        label="کلمه عبور مدیریتی"
        variant="outlined"
        value={formik.values.password}
        onChange={(e) => {
          const value = e.target.value.replace(/\D/g, "").slice(0, 4);
          formik.setFieldValue("password", value);
        }}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.password && Boolean(formik.errors.password)
            ? formik.errors.password
            : null
        }
        error={formik.touched.password && Boolean(formik.errors.password)}
        inputProps={{
          maxLength: 4,
        }}
      />

      <Button
        disabled={!formik.isValid}
        fullWidth
        variant="contained"
        onClick={() => {
          dispatch(LOADING_START());
          dispatch(
            pspSubmitPos({
              guild_key: item.key,
              receiver_number: formik.values.reciver,
              terminal_number: formik.values.terminal,
              password: formik.values.password,
              serial: formik.values.serial,
            })
          ).then((r) => {
            if (r.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی پیش آمده است!",
                severity: "error",
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              updateTable();
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
