import React, { useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import { provinceSubmitProductPrice } from "../../services/province-submit-product-price";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceGetProducts } from "../../services/province-get-producrs";

export const ProvinceSubmitProductPrice = ({ item }) => {
  const [openNotif] = useContext(AppContext);

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

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

  return (
    <Grid container justifyContent="center" gap={2} alignItems="center">
      <Grid>
        <TextField
          fullWidth
          id="price"
          label="قیمت"
          value={formik.values.price}
          error={formik.touched.price ? Boolean(formik.errors.price) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.price && Boolean(formik.errors.price)
              ? formik.errors.price
              : null
          }
          autoComplete="current-password"
          variant="outlined"
        />
      </Grid>
      <Grid>
        <Button
          disabled={!formik.isValid}
          variant="contained"
          onClick={() => {
            dispatch(
              provinceSubmitProductPrice({
                product_key: item?.key,
                selling_free_price: item?.sellingFreePrice,
                selling_approved_price: item?.sellingApprovedPrice,
                selling_more_than_inventory: item?.sellingMoreThanInventory,
                selling_other_products: item?.sellingOtherProducts,
                price: formik.values.price,
              })
            ).then((r) => {
              if (r.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
                dispatch(provinceGetProducts());
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
