import React, { useContext } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useFormik } from "formik";
import * as Yup from "yup";
import { TextField, Button } from "@mui/material";
import { useDispatch } from "react-redux";
import {
  provincePolicyEditBeneficiaryAccountsSevice,
  provincePolicySubmitBeneficiaryAccountsSevice,
} from "../../services/province-policy-get-accounts";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";

const validationSchema = Yup.object().shape({
  sheba: Yup.string()
    .required("شبا الزامی است")
    .matches(
      /^IR[0-9]{24}$/,
      "شماره شبا باید با IR شروع شود و شامل 24 رقم باشد"
    ),
  name: Yup.string().required("نام ذینفع الزامی است"),
  percentage: Yup.number()
    .required("درصد الزامی است")
    .min(0, "درصد نمی‌تواند کمتر از 0 باشد")
    .max(100, "درصد نمی‌تواند بیشتر از 100 باشد"),
});

export const ProvincePolicyAccountsSubmitBeneficiary = ({
  fetchData,
  item,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();

  const handleFinishSubmit = (r) => {
    if (r.payload.error) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: r.payload.error,
        severity: "error",
      });
    } else {
      fetchData();
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "عملیات با موفقیت انجام شد.",
        severity: "success",
      });
      dispatch(DRAWER({ right: false, bottom: false, content: null }));
    }
  };
  const formik = useFormik({
    initialValues: {
      name: item?.name || "",
      sheba: item?.shaba || "IR",
      percentage: item?.percent || "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      if (item) {
        dispatch(
          provincePolicyEditBeneficiaryAccountsSevice({
            name: values.name,
            percent: values.percentage,
            shaba: values.sheba,
            account_key: item?.key,
          })
        ).then((r) => {
          handleFinishSubmit(r);
        });
      } else {
        dispatch(
          provincePolicySubmitBeneficiaryAccountsSevice({
            name: values.name,
            percent: values.percentage,
            shaba: values.sheba,
          })
        ).then((r) => {
          handleFinishSubmit(r);
        });
      }
    },
  });

  return (
    <Grid container xs={12} direction="grid" gap={2}>
      <TextField
        id="name"
        label="نام"
        variant="outlined"
        sx={{ width: "100%", height: "100%" }}
        value={formik.values.name}
        error={formik.touched.name ? Boolean(formik.errors.name) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.name && Boolean(formik.errors.name)
            ? formik.errors.name
            : null
        }
      />

      <TextField
        id="sheba"
        label="شماره شبا"
        variant="outlined"
        sx={{ width: "100%" }}
        value={formik.values.sheba}
        error={formik.touched.sheba ? Boolean(formik.errors.sheba) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.sheba && Boolean(formik.errors.sheba)
            ? formik.errors.sheba
            : null
        }
      />

      <TextField
        fullWidth
        id="percentage"
        name="percentage"
        label="درصد"
        variant="outlined"
        type="number"
        value={formik.values.percentage}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={formik.touched.percentage && Boolean(formik.errors.percentage)}
        helperText={formik.touched.percentage && formik.errors.percentage}
        inputProps={{
          min: 0,
          max: 100,
          step: "0.01",
        }}
      />

      <Button fullWidth variant="contained" onClick={formik.handleSubmit}>
        ثبت
      </Button>
    </Grid>
  );
};
