import { IconButton, Tooltip, TextField, Button, Box } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import TuneIcon from "@mui/icons-material/Tune";
import { useDispatch } from "react-redux";
import { OPEN_MODAL, CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { managementSendSms } from "../../services/province-management-send-sms";
import { Formik, Form } from "formik";
import * as Yup from "yup";

export const ProvinceSmsSubmisionManagementOperation = ({
  item,
  item_id,
  updateTable_data,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const handleOpenModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "ویرایش",
        content: <UsernamePasswordForm />,
      })
    );
  };

  const UsernamePasswordForm = () => {
    const validationSchema = Yup.object({
      username: Yup.string()
        .required("نام کاربری الزامی است")
        .min(3, "حداقل ۳ کاراکتر وارد کنید"),
      password: Yup.string()
        .required("رمز عبور الزامی است")
        .min(6, "حداقل ۶ کاراکتر وارد کنید"),
    });

    return (
      <Formik
        initialValues={{
          username: item?.username || "",
          password: item?.password || "",
        }}
        enableReinitialize={true}
        validationSchema={validationSchema}
        onSubmit={(values, { setSubmitting }) => {
          const payload = {
            id: item_id,
            username: values.username,
            password: values.password,
          };

          dispatch(managementSendSms(payload)).then((r) => {
            setSubmitting(false);
            if (r.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.error,
                severity: "error",
              });
            } else {
              updateTable_data();
              dispatch(CLOSE_MODAL());
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "ویرایش با موفقیت انجام شد",
                severity: "success",
              });
            }
          });
        }}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          isSubmitting,
        }) => (
          <Form>
            <Box display="flex" flexDirection="column" gap={2}>
              <TextField
                label="نام کاربری"
                name="username"
                value={values.username}
                onChange={handleChange}
                onBlur={handleBlur}
                error={touched.username && Boolean(errors.username)}
                helperText={touched.username && errors.username}
                fullWidth
              />
              <TextField
                label="رمز عبور"
                name="password"
                type="text"
                value={values.password}
                onChange={handleChange}
                onBlur={handleBlur}
                error={touched.password && Boolean(errors.password)}
                helperText={touched.password && errors.password}
                fullWidth
              />
              <Button
                variant="contained"
                color="primary"
                type="submit"
                disabled={!item_id || isSubmitting}
              >
                ثبت
              </Button>
            </Box>
          </Form>
        )}
      </Formik>
    );
  };

  return (
    <Grid container>
      <Tooltip title="ویرایش">
        <IconButton color="primary" onClick={handleOpenModal}>
          <TuneIcon />
        </IconButton>
      </Tooltip>
    </Grid>
  );
};
