import React, { useContext, useEffect } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { Button, TextField } from "@mui/material";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { useDispatch } from "react-redux";
import { slaughterPayFactorService } from "../../services/slaughter-pay-factor";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { slaughterPayProvinceFactor } from "../../../file/services/slaughterPayProvinceFactor";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterFinalFactorsService } from "../../services/slaughter-final-factors";
import { slaughterFactorsService } from "../../services/slaughter-factors";

const validationSchema = yup.object({
  paymentCode: yup.string().required("This field is required"),
});

export const SlaughterPayFactor = ({ factorKey, isFinalFactor }) => {
  const [image, setImage] = React.useState();
  const [images, setImages] = React.useState([]);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      paymentCode: "",
      doc: "",
      amount: "",
    },
    validationSchema,
    onSubmit: (values) => {
      if (!isFinalFactor) {
        dispatch(
          slaughterPayFactorService({
            factor_key: factorKey,
            image: values.doc,
            payment_code: values.paymentCode,
            amount: values.amount,
          })
        ).then((r) => {
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        });
      } else {
        dispatch(
          slaughterPayProvinceFactor({
            key: factorKey,
            factor_image: values.doc,
            payment_code: values.paymentCode,
            role: getRoleFromUrl(),
          })
        ).then((r) => {
          dispatch(slaughterFactorsService({ selectedDate1, selectedDate2 }));
          dispatch(slaughterFinalFactorsService());
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        });
      }
    },
  });

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      setImage(fixBase64(imageList[0]?.data_url));
    }
    setImages(imageList);
  };

  useEffect(() => {
    formik.setFieldValue("doc", image);
  }, [image]);

  return (
    <div>
      <form onSubmit={formik.handleSubmit}>
        <TextField
          label="شناسه پرداخت"
          name="paymentCode"
          variant="outlined"
          margin="normal"
          fullWidth
          error={
            formik.touched.paymentCode && Boolean(formik.errors.paymentCode)
          }
          helperText={formik.touched.paymentCode && formik.errors.paymentCode}
          value={formik.values.paymentCode}
          onChange={formik.handleChange}
        />
        {!isFinalFactor && (
          <NumberInput
            allowLeadingZeros
            thousandSeparator=","
            label="مبلغ واریزی (ریال)"
            id="amount"
            variant="outlined"
            margin="normal"
            fullWidth
            error={formik.touched.amount && Boolean(formik.errors.amount)}
            helperText={formik.touched.amount && formik.errors.amount}
            value={formik.values.amount}
            onChange={formik.handleChange}
          />
        )}
        <Grid mb={SPACING.SMALL}>
          <ImageUpload
            onChange={factorPaymentHandler}
            images={images}
            maxNumber={1}
            title={"بارگذاری سند"}
          />
        </Grid>
        <Button fullWidth type="submit" variant="contained" color="primary">
          ثبت
        </Button>
      </form>
    </div>
  );
};
