import React, { ChangeEvent, useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Paper,
  Button,
  Container,
  Typography,
  Stack,
  Snackbar,
  Alert,
  IconButton,
  useMediaQuery,
  Link,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import logo from "../../assets/logo.png";
import { styled } from "@mui/material";
import themestyle from "../../theme";
import { TEXT, ERROR_MESSAGES } from "../../const";
import { useMutation } from "@apollo/client";
import { FORGOT_PASSWORD } from "../../graphql/mutation";
import IntelliwealthTextField from "../../components/intelliwealthTextField";
import { useSession } from "../../context/sessioncontext";

const Item = styled("div")(({ theme }) => ({
  marginBottom: "10px",
  padding: "8px",
  textAlign: "center",
  [theme.breakpoints.down("sm")]: {
    marginBottom: "10px",
    padding: "6px",
  },
}));

const ResetPassword: React.FC = () => {
  const [email, setEmail] = useState("");
  const { login } = useSession();
  const [emailErrorMessage, setEmailErrorMessage] = useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "error"
  );
  const [isSubmitButtonDisabled, setIsSubmitButtonDisabled] = useState(true);
  const navigate = useNavigate();
  const isMobile = useMediaQuery("(max-width:600px)");
  const isTablet = useMediaQuery("(min-width:601px) and (max-width:900px)");
  const [
    forgotPassword,
    { loading: forgotPasswordLoading, error: forgotPasswordError },
  ] = useMutation(FORGOT_PASSWORD);

  const isValidEmail = (email: string): boolean => {
    const emailRegex = ERROR_MESSAGES.EMAILREG;
    return emailRegex.test(email);
  };

  useEffect(() => {
    const emailValid = isValidEmail(email);
    setIsSubmitButtonDisabled(!emailValid);
  }, [email]);

  const handleEmailChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
  };

  const handleEmailFocus = () => {
    setEmailErrorMessage("");
  };

  const handleEmailBlur = () => {
    if (!isValidEmail(email) && email.length > 0) {
      setEmailErrorMessage(ERROR_MESSAGES.EMAIL_VAILD);
    } else {
      setEmailErrorMessage("");
    }
  };

  const handleSubmit = async () => {
    if (!isValidEmail(email)) {
      setEmailErrorMessage(ERROR_MESSAGES.EMAIL_VAILD);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }

    try {
      const { data } = await forgotPassword({
        variables: { email },
      });
      if (data.forgotPassword.success) {
        login();
        setSuccessMessage(
          data.forgotPassword.message || TEXT.PASSWORD_RESET_PASSWORD
        );
        setSnackbarSeverity("success");
        setSnackbarOpen(true);

        setTimeout(() => {
          navigate("/");
        }, 3000);
      } else {
        setSuccessMessage(data.forgotPassword.message);
        setSnackbarSeverity("error");
        setSnackbarOpen(true);
      }
    } catch (error: any) {
      const errorMessage = error.message.includes("User not found")
        ? "User not found"
        : error.message;
      setSuccessMessage(errorMessage);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === "Enter") {
      handleSubmit();
    }
  };

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
    login();
  };

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minHeight: "85vh",
        backgroundColor: "#F9FAFC",
      }}
    >
      <Container maxWidth={isMobile ? "xs" : "sm"}>
        <Paper
          elevation={3}
          sx={{
            padding: isMobile ? "10px" : isTablet ? "15px" : "20px",
            width: "100%",
            maxWidth: isMobile ? "95%" : "400px",
            borderRadius: "8px",
            margin: "auto",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Stack spacing={isMobile ? 1 : 2} direction="column">
            <Item>
              <img
                src={logo}
                alt="Intelliwealth Logo"
                style={{
                  width: isMobile ? "150px" : "180px",
                  height: isMobile ? "45px" : "45px",
                }}
              />
            </Item>
            <Box component="form" onKeyPress={handleKeyPress}>
              <Item>
                <Typography
                  variant={isMobile ? "h6" : "h5"}
                  sx={{
                    color: themestyle.colors.primary,
                    fontFamily: themestyle.fontFamily.lato,
                    fontWeight: "bold",
                  }}
                >
                  Reset Password
                </Typography>
              </Item>
              <Item>
                <Typography
                  variant="body2"
                  sx={{
                    color: "#222222",
                    fontFamily: themestyle.fontFamily.lato,
                    fontWeight: 500,
                    textAlign: "center",
                    fontSize: isMobile ? "12px" : isTablet ? "14px" : "16px",
                  }}
                >
                  Please enter your email address.
                  <br />
                  You will receive a link to create a new password via email.
                </Typography>
              </Item>
              <Item>
                <Stack direction="column" spacing={1} width="100%">
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    Email
                  </Typography>
                  <IntelliwealthTextField
                    id="email"
                    type="text"
                    value={email}
                    placeholder="Enter your email"
                    onChange={handleEmailChange}
                    onFocus={handleEmailFocus}
                    onBlur={handleEmailBlur}
                    error={Boolean(emailErrorMessage)}
                    helperText={emailErrorMessage}
                    fullWidth
                    errorMessage={emailErrorMessage}
                    setErrorMessage={setEmailErrorMessage}
                    sx={{
                      "& .MuiOutlinedInput-root": { borderRadius: "8px" },
                      "& .MuiInputLabel-root": {
                        fontSize: isMobile ? "14px" : "16px",
                      },
                      "& .MuiInputBase-input": {
                        fontSize: isMobile ? "14px" : "16px",
                      },
                    }}
                  />
                </Stack>
              </Item>
              <Item>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleSubmit}
                  disabled={isSubmitButtonDisabled || forgotPasswordLoading}
                  fullWidth
                  sx={{
                    padding: isMobile ? "8px" : "10px",
                    fontSize: isMobile ? "14px" : "16px",
                    transform: "none",
                    bgcolor: themestyle.colors.primary,
                    textTransform: "none",
                  }}
                >
                  {forgotPasswordLoading ? "Sending..." : TEXT.GET_NEW_PASSWORD}
                </Button>
              </Item>
              <Item>
                <Link
                  href="/"
                  sx={{
                    color: themestyle.colors.primary,
                    textDecoration: "none",
                    fontSize: isMobile ? "12px" : "14px",
                    marginTop: isMobile ? "8px" : "0",
                    "&:hover": {
                      textDecoration: "underline",
                    },
                  }}
                >
                  Already have an account?
                </Link>
              </Item>
            </Box>
          </Stack>
        </Paper>
      </Container>
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={2000}
        onClose={handleSnackbarClose}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
      >
        <Alert
          onClose={handleSnackbarClose}
          severity={snackbarSeverity}
          sx={{ width: isMobile ? "90%" : "100%" }}
          action={
            <IconButton
              size="small"
              aria-label="close"
              color="inherit"
              onClick={handleSnackbarClose}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          }
        >
          {successMessage || emailErrorMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default ResetPassword;
