import { Box } from "@mui/system";
import { Grid } from "../components/grid/Grid";
import { SPACING } from "../data/spacing";
import {
  Button,
  IconButton,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";
import Captcha from "../components/captcha/Captcha";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../lib/redux/slices/appSlice";
import {
  checkActiveUsers,
  checkUserPath,
  loginWithPassword,
} from "../features/authentication/services/login";
import { Yup } from "../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { useContext, useEffect, useState } from "react";
import { AppContext } from "../contexts/AppContext";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import { getUserMovingTextsService } from "../features/authentication/services/getUserMovingTexts";
import { slaughterGetPermisionState } from "../features/slaughter-house/services/slaughter-get-permision";
import { getUserAnnouncement } from "../features/authentication/services/get-announcement";
import bgImg from "../assets/images/login-rasadyar.png";
import loginLogo from "../assets/images/login-logo.png";
import icon from "../assets/images/logo.png";
import { motion } from "framer-motion";
import { getUserProfile } from "../features/authentication/services/getUserProfile";
import { AuthPrivacyText } from "../features/authentication/components/auth-privacy-text/AuthProvacyText";

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

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

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

const containerVariants = {
  hidden: { opacity: 0, scale: 0.9 },
  visible: { opacity: 1, scale: 1, transition: { duration: 0.5 } },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.3 } },
};

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

  useEffect(() => {
    formik.validateForm();
    dispatch(checkActiveUsers()).then((r) => {
      const currentTime = new Date();
      const hours = currentTime.getHours();

      if (hours >= 20 || hours < 5) {
        setActiveUsers(r.payload.data?.numberOfActiveUsers);
      } else {
        setActiveUsers(r.payload.data?.numberOfActiveUsers + 320);
      }
    });
  }, []);

  useEffect(() => {
    if (formik.values.mobile.length === 11) {
      dispatch(checkUserPath({ mobile: formik.values.mobile, state: "" })).then(
        (r) => {
          if (r.error) {
            formik.setFieldValue("mobile", "");
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "لطفا اتصال به اینترنت را چک کنید!",
              severity: "error",
            });
          } else {
            const notValid = !!r.error;
            setIsValidMobileChecked(true);
            if (notValid) {
              setIsValidMobile(false);
            } else {
              setIsValidMobile(true);
            }
          }
        }
      );
    }
  }, [formik.values.mobile]);

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

  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

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

  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 submitForm = (e) => {
    e.preventDefault();
    if (isValidMobile) {
      dispatch(LOADING_START());
      dispatch(
        loginWithPassword({
          mobile: formik.values.mobile,
          password: formik.values.password,
        })
      ).then((r) => {
        dispatch(getUserProfile());
        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());
      });
    } else {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "شماره موبایل در سامانه وجود ندارد!",
        severity: "error",
      });
    }
  };

  return (
    <Box
      display="flex"
      justifyContent="center"
      sx={{
        height: "100vh",
        backgroundImage: `url(${bgImg})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    >
      <Grid
        container
        justifyContent="center"
        gap={SPACING.SMALL}
        alignItems="center"
        height="100vh"
        xs={12}
      >
        <motion.div
          initial="hidden"
          animate="visible"
          variants={containerVariants}
        >
          <motion.div
            variants={itemVariants}
            style={{
              display: "flex",
              justifyContent: "center",
            }}
          >
            <Grid
              container
              justifyContent="center"
              alignItems="center"
              xs={12}
              sx={{ maxWidth: "1200px" }}
            >
              <Grid
                container
                justifyContent="center"
                alignItems="center"
                p={6}
                xs={12}
                md={6}
                borderRadius={{ xs: "15px", md: "15px 0px 0px 15px" }}
                sx={{
                  backgroundColor: "white",
                  height: "650px",
                  borderStyle: "solid",
                  borderWidth: "1px",
                  borderColor: "#8F8F8F",
                }}
              >
                <Grid container justifyContent="center" my={2}>
                  <Grid
                    container
                    xs={12}
                    justifyContent="center"
                    alignItems="center"
                    spacing={4}
                  >
                    <img
                      src={icon}
                      alt="icon"
                      style={{ width: "130px", userSelect: "none" }}
                    />
                  </Grid>

                  <Grid
                    container
                    justifyContent="center"
                    xs={12}
                    alignItems="center"
                    spacing={6}
                    my={"20px"}
                  >
                    <Grid container>
                      <motion.div
                        animate={{ opacity: [1, 0.7, 1] }}
                        transition={{ duration: 5, repeat: Infinity }}
                      >
                        <Typography
                          style={{
                            fontSize: "18px",
                            color: "#717171",
                            fontWeight: "700",
                          }}
                        >
                          سامانه رصدیار
                        </Typography>
                        {/* <Typography variant="body1">
                          شماره موبایل تان را وارد کنید.
                        </Typography> */}
                      </motion.div>
                    </Grid>
                  </Grid>
                  <Grid
                    container
                    xs={12}
                    justifyContent="center"
                    alignItems="center"
                  >
                    <form onSubmit={submitForm}>
                      <Grid>
                        <TextField
                          id="mobile"
                          label="شماره تلفن"
                          variant="outlined"
                          sx={{ width: "100%" }}
                          value={formik.values.mobile}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                        />
                      </Grid>
                      <Grid mt={"16px"}>
                        <TextField
                          type={showPassword ? "text" : "password"}
                          id="password"
                          label="رمزعبور"
                          variant="outlined"
                          onChange={formik.handleChange}
                          value={formik.values.password}
                          onBlur={formik.handleBlur}
                          onKeyDown={(e) => {
                            if (
                              e.key === "Enter" &&
                              isValidCaptcha &&
                              isValidMobileChecked
                            ) {
                              if (isValidMobile) {
                                dispatch(LOADING_START());
                                dispatch(
                                  loginWithPassword({
                                    mobile: formik.values.mobile,
                                    password: formik.values.password,
                                  })
                                ).then((r) => {
                                  dispatch(getUserProfile());
                                  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());
                                });
                              } else {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "شماره موبایل در سامانه وجود ندارد!",
                                  severity: "error",
                                });
                              }
                            }
                          }}
                          fullWidth
                          InputProps={{
                            endAdornment: (
                              <InputAdornment position="end">
                                <IconButton
                                  tabIndex={-1}
                                  aria-label="نمایش رمز عبور"
                                  onClick={handleClickShowPassword}
                                  edge="end"
                                  onMouseDown={handleMouseDownPassword}
                                >
                                  {showPassword ? (
                                    <VisibilityOff />
                                  ) : (
                                    <Visibility />
                                  )}
                                </IconButton>
                              </InputAdornment>
                            ),
                          }}
                        />
                      </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
                            sx={{ height: "48px" }}
                            variant="contained"
                            fullWidth
                            type="submit"
                            disabled={
                              !(isValidCaptcha && formik.isValid) ||
                              !isValidMobileChecked
                            }
                            onSubmit={submitForm}
                          >
                            ورود
                          </Button>
                        </Grid>
                      </Grid>
                    </form>
                  </Grid>
                  <Typography
                    variant="body2"
                    mt={2}
                    sx={{ fontWeight: 500, color: "#555" }}
                  >
                    مطالعه بیانیه{" "}
                    <Typography
                      component="span"
                      sx={{
                        color: "#1976d2",
                        fontWeight: 600,
                        cursor: "pointer",
                        position: "relative",
                        transition: "color 0.3s",
                        "&::after": {
                          content: '""',
                          position: "absolute",
                          left: 0,
                          bottom: -2,
                          width: "100%",
                          height: "2px",
                          backgroundColor: "#1976d2",
                          transform: "scaleX(0)",
                          transition: "transform 0.3s ease-in-out",
                        },
                        "&:hover": { color: "#125699" },
                        "&:hover::after": { transform: "scaleX(1)" },
                      }}
                      onClick={() =>
                        dispatch(
                          OPEN_MODAL({
                            title: "حریم خصوصی",
                            content: <AuthPrivacyText />,
                          })
                        )
                      }
                    >
                      حریم خصوصی
                    </Typography>
                  </Typography>
                </Grid>
              </Grid>
              <Grid
                container
                justifyContent="center"
                alignItems="center"
                p={6}
                display={{ xs: "none", md: "flex" }}
                xs={6}
                sx={{
                  backgroundImage:
                    "linear-gradient(to bottom, #163A5C, #0D2538)",
                  height: "650px",
                  borderRadius: "0px 15px 15px 0px",
                  borderStyle: "solid",
                  borderWidth: "1px",
                  borderColor: "#8F8F8F",
                  flexDirection: "column",
                  textAlign: "center",
                }}
              >
                {/* Logo Image */}
                <Box
                  component="img"
                  src={loginLogo}
                  alt="سامانه رصد یار"
                  sx={{ width: 360 }}
                />

                {/* Text Content */}
                <Typography
                  variant="body1"
                  color="white"
                  fontWeight="bold"
                  sx={{ fontSize: "16px" }}
                >
                  سامانه رصد و پایش زنجیره تامین، تولید و توزیع کالای اساسی
                </Typography>
                <Typography
                  variant="body1"
                  color="white"
                  mt={2}
                  sx={{ textAlign: "justify" }}
                >
                  از اینکه از سامانه برای بررسی و مدیریت کالاهای اساسی استفاده
                  می‌کنید، بسیار خرسندیم. امیدواریم که تجربه‌ی شما با این
                  سامانه، مفید و کارآمد باشد. در صورت نیاز به راهنمایی یا
                  پرسش‌های بیشتر، تیم پشتیبانی ما همواره آماده‌ی پاسخگویی به
                  شماست.
                </Typography>
                <Typography
                  variant="body1"
                  color="white"
                  fontWeight="bold"
                  mt={4}
                >
                  با تشکر از همراهی شما
                  <br />
                  سامانه رصد یار
                </Typography>
                <Typography variant="body2" color="white" mt={1}>
                  تلفن پشتیبانی : 28421237-021
                </Typography>
              </Grid>

              <Grid
                container
                justifyContent="center"
                style={{
                  backgroundColor: "transparent",
                  borderRadius: "10px",
                }}
                mt={2}
                xs={12}
              >
                {/* eslint-disable-next-line react/jsx-no-target-blank */}
                <a
                  referrerPolicy="origin"
                  // rel="noreferrer"
                  target="_blank"
                  href="https://trustseal.enamad.ir/?id=548910&Code=IOzppvkTQHlCeBeP2Gz5VsnXqqra2Gq7"
                >
                  <img
                    id="IOzppvkTQHlCeBeP2Gz5VsnXqqra2Gq7"
                    referrerPolicy="origin"
                    src="https://Trustseal.eNamad.ir/logo.aspx?id=548910&Code=IOzppvkTQHlCeBeP2Gz5VsnXqqra2Gq7"
                    // src={enamad}
                    alt="icon"
                    style={{
                      width: "100px",
                      userSelect: "none",
                      borderStyle: "solid",
                      borderWidth: "1px",
                      borderColor: "#8F8F8F",
                      borderRadius: "16px",
                    }}
                  />
                </a>
              </Grid>
            </Grid>
          </motion.div>
          <Grid container xs={12} mt={2} sx={{ justifyContent: "center" }}>
            <Box
              sx={{
                backgroundColor: "white",
                color: "white",
                padding: "8px 16px",
                borderRadius: "8px",
                display: "inline-flex",
                alignItems: "center",
                alignSelf: "center",
                // boxShadow: "0px 4px 6px rgba(0, 0, 0, 0.3)",
                zIndex: {
                  xs: 0,
                  sm: 10,
                },
              }}
            >
              <Typography
                variant="body1"
                sx={{ fontSize: "16px", color: "#5B5B5B" }}
              >
                کاربران آنلاین: {activeUsers} نفر
              </Typography>
            </Box>
          </Grid>
        </motion.div>
      </Grid>
    </Box>
  );
};

export default Auth;
