import {
  Button,
  IconButton,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  forgetPassword,
  forgetPasswordChangePassword,
  forgetPasswordSendOpt,
  loginWithPassword,
} from "../../services/login";
import { PropTypes } from "prop-types";
import { Yup } from "../../../../lib/yup/yup";
import { useContext, useEffect } from "react";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { useState } from "react";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterGetPermisionState } from "../../../slaughter-house/services/slaughter-get-permision";
import { getUserAnnouncement } from "../../services/get-announcement";
import { getUserMovingTextsService } from "../../services/getUserMovingTexts";

const modalContentStyle = {
  backgroundColor: "#ffffff",
  padding: "20px",
  borderRadius: "4px",
  outline: "none",
  minWidth: "300px",
  maxWidth: "600px",
  textAlign: "center",
};

const descriptionStyle = {
  marginBottom: "10px",
};

const buttonStyle = {
  marginTop: "10px",
};

export const EnterPassword = ({ mobile, isUserHandler }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const formikMain = useFormik({
    initialValues: {
      password: "",
    },
    validationSchema: Yup.object({
      password: Yup.mixed().required("این فیلد اجباری است!"),
    }),
  });

  const getUserMovingTexts = () => {
    dispatch(getUserMovingTextsService());
  };

  const getSlaughterState = (role) => {
    dispatch(slaughterGetPermisionState());
    dispatch(getUserAnnouncement(role)).then((r) => {
      if (r.payload.data?.active) {
        dispatch(
          OPEN_MODAL({
            title: "اطلاعیه سیستم",
            content: (
              <Grid style={modalContentStyle}>
                <Typography
                  variant="body1"
                  color="secondary"
                  style={descriptionStyle}
                >
                  {r.payload.data?.description}
                </Typography>
                <Grid container justifyContent="center">
                  <Grid item xs={12}>
                    <Button
                      color="secondary"
                      variant="outlined"
                      onClick={() => dispatch(CLOSE_MODAL())}
                      style={buttonStyle}
                    >
                      متوجه شدم
                    </Button>
                  </Grid>
                </Grid>
              </Grid>
            ),
          })
        );
      }
    });
  };

  const formik = useFormik({
    initialValues: {
      forgetOtp: "",
      newPassword: "",
      newPasswordRepeat: "",
    },
    validationSchema: Yup.object({
      forgetOtp: Yup.mixed().required("این فیلد اجباری است!"),
      newPassword: Yup.mixed().required("این فیلد اجباری است!"),
      newPasswordRepeat: Yup.mixed().required("این فیلد اجباری است!"),
    }),
  });

  const [showPassword, setShowPassword] = useState(false);
  const [forgetPasswordKey, setForgetPasswordKey] = useState(null);
  const [isForgetOtpCodeCorrect, setIsForgetOtpCodeCorrect] = useState(false);

  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  const handleMouseDownPassword = (event) => {
    event.preventDefault();
  };

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

  return (
    <>
      {forgetPasswordKey ? (
        <>
          {isForgetOtpCodeCorrect ? (
            <Grid>
              <Typography variant="body1" py={SPACING.SMALL}>
                رمزعبور جدید خود را وارد کنید.
              </Typography>
              <Grid container gap={SPACING.SMALL}>
                <TextField
                  type={showPassword ? "text" : "password"}
                  id="newPassword"
                  label="رمزعبور جدید"
                  variant="outlined"
                  onChange={formik.handleChange}
                  value={formik.values.newPassword}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.newPassword
                      ? Boolean(formik.errors.newPassword)
                      : null
                  }
                  helperText={
                    formik.touched.newPassword &&
                    Boolean(formik.errors.newPassword)
                      ? formik.errors.newPassword
                      : null
                  }
                  fullWidth
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          aria-label="نمایش رمزعبور"
                          onClick={handleClickShowPassword}
                          edge="end"
                          onMouseDown={handleMouseDownPassword}
                        >
                          {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />
                <TextField
                  type={showPassword ? "text" : "password"}
                  id="newPasswordRepeat"
                  label="تکرار رمزعبور جدید"
                  variant="outlined"
                  onChange={formik.handleChange}
                  value={formik.values.newPasswordRepeat}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.newPasswordRepeat
                      ? Boolean(formik.errors.newPasswordRepeat)
                      : null
                  }
                  helperText={
                    formik.touched.newPasswordRepeat &&
                    Boolean(formik.errors.newPasswordRepeat)
                      ? formik.errors.newPasswordRepeat
                      : null
                  }
                  fullWidth
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          aria-label="نمایش رمزعبور"
                          onClick={handleClickShowPassword}
                          edge="end"
                          onMouseDown={handleMouseDownPassword}
                        >
                          {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />
              </Grid>
              <Grid container mt={SPACING.SMALL} gap={SPACING.MEDIUM}>
                <Grid flexGrow="1">
                  <Button
                    variant="contained"
                    disabled={
                      !(
                        formik.values.newPassword ===
                        formik.values.newPasswordRepeat
                      )
                    }
                    fullWidth
                    onClick={() => {
                      dispatch(LOADING_START());
                      dispatch(
                        forgetPasswordChangePassword({
                          username: mobile,
                          password: formik.values.newPassword,
                        })
                      ).then((r) => {
                        if (r.error) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "مشکلی پیش آمده است!",
                            severity: "error",
                          });
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "رمزعبور با موفقیت تغییر یافت!",
                            severity: "success",
                          });
                          setForgetPasswordKey(null);
                        }
                        dispatch(LOADING_END());
                      });
                    }}
                  >
                    تغییر رمزعبور
                  </Button>
                </Grid>
              </Grid>
            </Grid>
          ) : (
            <Grid>
              <Typography variant="body1" py={SPACING.SMALL}>
                کد یکبارمصرف دریافتی را وارد کنید.
              </Typography>
              <TextField
                type={showPassword ? "text" : "password"}
                id="forgetOtp"
                label="کد دریافتی"
                variant="outlined"
                onChange={formik.handleChange}
                value={formik.values.forgetOtp}
                onBlur={formik.handleBlur}
                error={
                  formik.touched.forgetOtp
                    ? Boolean(formik.errors.forgetOtp)
                    : null
                }
                helperText={
                  formik.touched.forgetOtp && Boolean(formik.errors.forgetOtp)
                    ? formik.errors.forgetOtp
                    : null
                }
                fullWidth
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton
                        aria-label="نمایش کد"
                        onClick={handleClickShowPassword}
                        edge="end"
                        onMouseDown={handleMouseDownPassword}
                      >
                        {showPassword ? <VisibilityOff /> : <Visibility />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
              />
              <Grid container mt={SPACING.SMALL} gap={SPACING.MEDIUM}>
                <Grid flexGrow="1">
                  <Button
                    variant="contained"
                    disabled={!formik.values.forgetOtp}
                    fullWidth
                    onClick={() => {
                      dispatch(LOADING_START());
                      dispatch(
                        forgetPasswordSendOpt({
                          key: forgetPasswordKey,
                          code: formik.values.forgetOtp,
                        })
                      ).then((r) => {
                        if (r.error) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "مشکلی پیش آمده است!",
                            severity: "error",
                          });
                        } else {
                          setIsForgetOtpCodeCorrect(r.payload.data.code);
                        }
                        dispatch(LOADING_END());
                      });
                    }}
                  >
                    ثبت
                  </Button>
                </Grid>
              </Grid>
            </Grid>
          )}
        </>
      ) : (
        <>
          <Typography variant="body1" py={SPACING.SMALL}>
            رمز عبور را وارد کرده و بر روی ورود کلیک نمایید.
          </Typography>
          <TextField
            type={showPassword ? "text" : "password"}
            id="password"
            label="رمزعبور"
            variant="outlined"
            onChange={formikMain.handleChange}
            value={formikMain.values.password}
            onBlur={formikMain.handleBlur}
            onKeyPress={(e) => {
              if (e.key === "Enter") {
                dispatch(LOADING_START());
                dispatch(
                  loginWithPassword({
                    mobile,
                    password: formikMain.values.password,
                  })
                ).then((r) => {
                  if (
                    r.payload?.data?.role?.includes("CityOperator") ||
                    r.payload?.data?.role?.includes("KillHouse") ||
                    r.payload?.data?.role?.includes("CityJahad") ||
                    r.payload?.data?.role?.includes("ProvinceSupervisor") ||
                    r.payload?.data?.role?.includes("ProvinceOperator")
                  ) {
                    getUserMovingTexts();
                  }

                  if (r.payload?.data?.role?.includes("KillHouse")) {
                    getSlaughterState("KillHouse");
                  } else if (r.payload?.data?.role?.includes("CityOperator")) {
                    getSlaughterState("CityOperator");
                  }
                  if (r.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "رمزعبور اشتباه است!",
                      severity: "error",
                    });
                  }
                  dispatch(LOADING_END());
                });
              }
            }}
            error={
              formikMain.touched.password
                ? Boolean(formikMain.errors.password)
                : null
            }
            helperText={
              formikMain.touched.password && Boolean(formikMain.errors.password)
                ? formikMain.errors.password
                : null
            }
            fullWidth
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    aria-label="نمایش رمز عبور"
                    onClick={handleClickShowPassword}
                    edge="end"
                    onMouseDown={handleMouseDownPassword}
                  >
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
          <Grid
            container
            direction="column"
            mt={SPACING.SMALL}
            gap={SPACING.SMALL}
          >
            <Grid container>
              <Grid flexGrow="1">
                <Button
                  variant="contained"
                  disabled={!formikMain.isValid}
                  fullWidth
                  onClick={() => {
                    dispatch(LOADING_START());
                    dispatch(
                      loginWithPassword({
                        mobile,
                        password: formikMain.values.password,
                      })
                    ).then((r) => {
                      if (r.payload?.data?.role?.includes("KillHouse")) {
                        getSlaughterState("KillHouse");
                      } else if (
                        r.payload?.data?.role?.includes("CityOperator")
                      ) {
                        getSlaughterState("CityOperator");
                      }
                      if (r.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "رمزعبور اشتباه است!",
                          severity: "error",
                        });
                      }
                      dispatch(LOADING_END());
                    });
                  }}
                >
                  ورود به سامانه
                </Button>
              </Grid>
              <Grid
                flexGrow="1"
                alignItems="center"
                alignSelf="center"
                justifyContent="center"
                display="flex"
              >
                <Button
                  onClick={() => {
                    isUserHandler();
                  }}
                >
                  بازگشت به صفحه قبل
                </Button>
              </Grid>
            </Grid>

            <Grid flexGrow="1">
              <Button
                variant="outlined"
                fullWidth
                onClick={() => {
                  dispatch(LOADING_START());
                  dispatch(
                    forgetPassword({
                      mobile,
                      state: "forget_password",
                    })
                  ).then((r) => {
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    } else {
                      setForgetPasswordKey(r.payload.data.key);
                    }
                    dispatch(LOADING_END());
                  });
                }}
              >
                رمزعبور را فراموش کرده ام (استفاده از پیامک)
              </Button>
            </Grid>
          </Grid>
        </>
      )}
    </>
  );
};

EnterPassword.propTypes = {
  mobile: PropTypes.any,
  isUserHandler: PropTypes.any,
};
