import { useContext, useEffect, useState } from "react";
import { verificationDirectBuyingCode } from "../../services/edit-verification-direct-buying-code";
import EditIcon from "@mui/icons-material/Edit";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import {
  Grid,
  IconButton,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";

import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";

function EditVerificationDirectBuy({
  inputDirectBuyingCode,
  kill_request_key,
  updateTable,
}) {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [isEditMode, setIsEditMode] = useState(false);

  const formik = useFormik({
    initialValues: {
      input_direct_buying_code: inputDirectBuyingCode,
    },
    validationSchema: Yup.object({
      input_direct_buying_code: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!")
        .matches(/^[0-9]+$/, "فقط عدد وارد کنید"),
      // .min(5, "کد باید حداقل ۵ کاراکتر باشد")
      // .max(20, "کد نمی‌تواند بیشتر از ۲۰ کاراکتر باشد"),
    }),
    onSubmit: (values) => {
      dispatch(
        verificationDirectBuyingCode({
          kill_request_key: kill_request_key,
          input_direct_buying_code: values.input_direct_buying_code,
          role: "KillHouse",
        })
      ).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",
          });
          updateTable();
        }
        setIsEditMode(false);
      });
    },
  });

  useEffect(() => {
    formik.setValues({ input_direct_buying_code: inputDirectBuyingCode });
    setIsEditMode(false);
  }, [inputDirectBuyingCode]);

  return isEditMode ? (
    <Grid container minWidth="130px">
      <form onSubmit={formik.handleSubmit}>
        <TextField
          variant="standard"
          name="input_direct_buying_code"
          value={formik.values.input_direct_buying_code}
          size="small"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={
            formik.touched.input_direct_buying_code &&
            Boolean(formik.errors.input_direct_buying_code)
          }
          helperText={
            formik.touched.input_direct_buying_code &&
            formik.errors.input_direct_buying_code
          }
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <Typography
                  style={{ cursor: "pointer" }}
                  color="primary"
                  fontWeight="bold"
                  variant="caption"
                  onClick={formik.handleSubmit}
                >
                  ثبت
                </Typography>
              </InputAdornment>
            ),
          }}
        />
      </form>
    </Grid>
  ) : (
    <Grid container alignItems="center">
      <Typography variant="caption">{inputDirectBuyingCode}</Typography>
      <IconButton
        aria-label="delete"
        size="small"
        color="primary"
        onClick={() => {
          setIsEditMode(!isEditMode);
        }}
      >
        <EditIcon />
      </IconButton>
    </Grid>
  );
}

export default EditVerificationDirectBuy;
