import { Button, TextField, Typography } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { loginSendMobile } from "../../services/login";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import Captcha from "../../../../components/captcha/Captcha";
import { useEffect, useState } from "react";
import { EnterPassword } from "../enter-password/EnterPassword";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";

export const Login = () => {
  const [openNotif] = useContext(AppContext);
  const [isValidCaptcha, setIsValidCaptcha] = useState(false);
  const [isUser, setIsUser] = useState(false);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      mobile: "",
      captcha: "",
    },
    validationSchema: Yup.object({
      mobile: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا اعداد انگلیسی وارد کنید!")
        .test("len", "شماره تلفن باید 11 رقم باشد!", (val, context) => {
          return context.originalValue && context.originalValue.length === 11;
        }),
    }),
  });

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

  const isUserHandler = () => {
    setIsUser(false);
    setIsValidCaptcha(false);
  };

  const submitForm = (e) => {
    e.preventDefault();
    dispatch(LOADING_START());
    dispatch(
      loginSendMobile({
        mobile: formik.values.mobile,
        state: "",
      })
    ).then((r) => {
      dispatch(LOADING_END());
      if (!r.payload.data.isUser) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "شماره تلفن شما در سامانه وجود ندارد!",
          severity: "error",
        });
      }
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی به وجود آمده است!",
          severity: "error",
        });
      } else {
        setIsUser(r.payload.data.isUser);
      }
    });
  };

  return (
    <Grid>
      <Grid container justifyContent="center" alignItems="center">
        <Grid
          container
          mx={{ xs: SPACING.SMALL, sm: SPACING.SMALL, md: 0 }}
          justifyContent="center"
        >
          <Grid p={SPACING.MEDIUM} minWidth={{ md: "520px" }}>
            {isUser ? (
              <EnterPassword
                isUserHandler={isUserHandler}
                mobile={formik.values.mobile}
              />
            ) : (
              <>
                <Typography variant="h6" color="primary">
                  سامانه رصدیار
                </Typography>
                <Typography variant="body1" py={SPACING.SMALL}>
                  شماره موبایل تان را وارد کنید.
                </Typography>
                <form onSubmit={submitForm}>
                  <Grid>
                    <TextField
                      id="mobile"
                      label="شماره تلفن"
                      variant="outlined"
                      sx={{
                        width: "100%",
                      }}
                      value={formik.values.mobile}
                      error={
                        formik.touched.mobile
                          ? Boolean(formik.errors.mobile)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.mobile && Boolean(formik.errors.mobile)
                          ? formik.errors.mobile
                          : null
                      }
                    />
                  </Grid>
                  <Grid
                    container
                    justifyContent="space-between"
                    flexWrap="nowrap"
                    sx={{
                      flexDirection: { xs: "column", sm: "row" },
                    }}
                    gap={SPACING.SMALL}
                    mt={SPACING.SMALL}
                  >
                    <Captcha onChange={(status) => setIsValidCaptcha(status)} />
                  </Grid>
                  <Grid
                    container
                    justifyContent="space-between"
                    gap={SPACING.MEDIUM}
                    direction="row"
                    mt={SPACING.SMALL}
                  >
                    <Grid flexGrow="2">
                      <Button
                        variant="contained"
                        fullWidth
                        type="submit"
                        disabled={!(isValidCaptcha && formik.isValid)}
                        onSubmit={submitForm}
                      >
                        ادامه
                      </Button>
                    </Grid>
                  </Grid>
                </form>
              </>
            )}
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};
