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

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

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      account: item?.account ? item?.account : "",
    },
    validationSchema: Yup.object({
      account: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را پر کنید!")
        .max(26, "شماره شبا نامعتبر است!")
        .min(26, "شماره شبا نامعتبر است!"),
    }),
  });

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

  return (
    <Grid xs={12} container direction="column" gap={2}>
      <Typography variant="body1" color="primary">
        ویرایش حساب {item?.name}
      </Typography>
      <TextField
        id="account"
        label="شماره شبا"
        variant="outlined"
        sx={{ width: "100%", height: "100%" }}
        value={formik.values.account}
        error={
          formik.touched.account && formik.values.account !== "-"
            ? Boolean(formik.errors.account)
            : null
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.account &&
          formik.values.account !== "-" &&
          Boolean(formik.errors.account)
            ? formik.errors.account
            : null
        }
      />

      <Grid>
        <Button
          fullWidth
          variant="contained"
          disabled={!formik.isValid && formik.values.account !== "-"}
          onClick={() => {
            dispatch(
              provincePolicyEditAccountsSevice({
                account_key: item?.key,
                account: formik.values.account,
              })
            ).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",
                });
                dispatch(CLOSE_MODAL());
                fetchData();
              }
            });
          }}
        >
          ویرایش شماره شبا
        </Button>
      </Grid>
    </Grid>
  );
};
