import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import { TextField, Button, Grid, Typography } from "@mui/material";
import { useDispatch } from "react-redux";
import { provincePolicyGetPaymentFractions } from "../../services/province-policy-get-payment-fractions";
import { provincePolicyEditPaymentFractions } from "../../services/province-policy-edit-payment-fractions";
import { AppContext } from "../../../../contexts/AppContext";

const ProvincePolicyWageFractions = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [percentage, setPercentages] = useState();
  const formik = useFormik({
    initialValues: {
      website: "",
      union: "",
      guilds: "",
      other: "",
    },
    validationSchema: Yup.object({
      website: Yup.number()
        .required("این فیلد اجباری است!")
        .min(0, "درصدی بیش از 0 وارد کنید!"),
      union: Yup.number()
        .required("این فیلد اجباری است!")
        .min(0, "درصدی بیش از 0 وارد کنید!"),
      guilds: Yup.number()
        .required("این فیلد اجباری است!")
        .min(0, "درصدی بیش از 0 وارد کنید!"),
      other: Yup.number()
        .required("این فیلد اجباری است!")
        .min(0, "درصدی بیش از 0 وارد کنید!"),
    }),
    onSubmit: (values) => {
      dispatch(
        provincePolicyEditPaymentFractions({
          company: values.website,
          union: values.union,
          guilds: values.guilds,
          other: values.other,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

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

  useEffect(() => {
    dispatch(provincePolicyGetPaymentFractions()).then((r) => {
      setPercentages(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (percentage?.company || percentage?.guilds || percentage?.union) {
      formik.setFieldValue("website", percentage.company);
      formik.setFieldValue("union", percentage.union);
      formik.setFieldValue("guilds", percentage.guilds);
      formik.setFieldValue("other", percentage.other);
    }
  }, [percentage]);

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container spacing={2} alignItems="center">
        <Grid container item xs={12}>
          <Typography variant="body1" gutterBottom>
            سهم بندی کارمزدها
          </Typography>
        </Grid>
        <Grid item xs={12} sm={3} md={2}>
          <TextField
            fullWidth
            id="website"
            name="website"
            label="سامانه"
            value={formik.values.website}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.website && Boolean(formik.errors.website)}
            helperText={formik.touched.website && formik.errors.website}
          />
        </Grid>
        <Grid item xs={12} sm={3} md={2}>
          <TextField
            fullWidth
            id="union"
            name="union"
            label="اتحادیه"
            value={formik.values.union}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.union && Boolean(formik.errors.union)}
            helperText={formik.touched.union && formik.errors.union}
          />
        </Grid>
        <Grid item xs={12} sm={3} md={2}>
          <TextField
            fullWidth
            id="guilds"
            name="guilds"
            label="اصناف"
            value={formik.values.guilds}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.guilds && Boolean(formik.errors.guilds)}
            helperText={formik.touched.guilds && formik.errors.guilds}
          />
        </Grid>
        <Grid item xs={12} sm={3} md={2}>
          <TextField
            fullWidth
            id="other"
            name="other"
            label="سایر"
            value={formik.values.other}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.other && Boolean(formik.errors.other)}
            helperText={formik.touched.other && formik.errors.other}
          />
        </Grid>
        <Grid item xs={12} sm={3} md={2}>
          <Typography variant="body1" color="primary">
            مجموع:{" "}
            {Number(formik.values.guilds) +
              Number(formik.values.union) +
              Number(formik.values.website) +
              Number(formik.values.other)}{" "}
            درصد
          </Typography>
        </Grid>
        <Grid item xs={12} md={3}>
          <Button
            disabled={
              !formik.isValid ||
              Number(formik.values.guilds) +
                Number(formik.values.union) +
                Number(formik.values.website) +
                Number(formik.values.other) >
                100
            }
            variant="contained"
            color="primary"
            type="submit"
            fullWidth
          >
            ثبت
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};

export default ProvincePolicyWageFractions;
