import React, { ChangeEvent, useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import {
  InputAdornment,
  Box,
  Paper,
  Button,
  Container,
  Typography,
  Stack,
  IconButton,
  Checkbox,
  FormControlLabel,
  Snackbar,
  Alert,
  Link,
  useMediaQuery,
} from "@mui/material";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
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 { LOGIN_USER } from "../../graphql/mutation";
import IntelliwealthTextField from "../../components/intelliwealthTextField";
import { useSession } from "../../context/sessioncontext";

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

const Login: React.FC = () => {
  const [email, setEmail] = useState(localStorage.getItem("email") || "");
  const [password, setPassword] = useState(
    localStorage.getItem("password") || ""
  );
  const { login } = useSession();
  const [emailErrorMessage, setEmailErrorMessage] = useState("");
  const [passwordErrorMessage, setPasswordErrorMessage] = useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [rememberMe, setRememberMe] = useState(!!localStorage.getItem("email"));
  const [showPassword, setShowPassword] = useState(false);
  const [isLoginButtonDisabled, setIsLoginButtonDisabled] = useState(true);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "error"
  );
  const navigate = useNavigate();
  const location = useLocation();
  const isMobile = useMediaQuery("(max-width:600px)");
  const [loginUser, { loading: loginLoading, error: loginError }] =
    useMutation(LOGIN_USER);

  useEffect(() => {
    try {
      const storedEmail = localStorage.getItem("email");
      const storedPassword = localStorage.getItem("password");
      if (storedEmail) {
        setEmail(storedEmail);
        setRememberMe(true);
      }
      if (storedPassword) {
        setPassword(storedPassword);
      }
    } catch (e) {
      console.error("Failed to read from localStorage:", e);
    }
  }, []);

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

  const isValidPassword = (password: string): boolean => {
    const minLength = 8;
    return password.length >= minLength;
  };

  useEffect(() => {
    if (rememberMe) {
      try {
        localStorage.setItem("email", email);
        localStorage.setItem("password", password);
      } catch (e) {
        console.error("Failed to write to localStorage:", e);
      }
    }
  }, [email, password, rememberMe]);

  useEffect(() => {
    const emailValid = isValidEmail(email);
    const passwordValid = isValidPassword(password);
    setIsLoginButtonDisabled(!(emailValid && passwordValid));
  }, [email, password]);

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

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

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

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

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

  const handlePasswordFocus = () => {
    setPasswordErrorMessage("");
  };

  const handlePasswordBlur = () => {
    if (password.length === 0) {
      setPasswordErrorMessage(ERROR_MESSAGES.PASS_REQUIRED);
    } else if (!isValidPassword(password)) {
      setPasswordErrorMessage(ERROR_MESSAGES.PASSWORD_MUST_CHAR);
    } else {
      setPasswordErrorMessage("");
    }
  };

  const handleRememberMeChange = () => {
    const updatedRememberMe = !rememberMe;
    setRememberMe(updatedRememberMe);
    if (!updatedRememberMe) {
      try {
        localStorage.removeItem("email");
        localStorage.removeItem("password");
      } catch (e) {
        console.error("Failed to clear localStorage:", e);
      }
    }
  };

  const handleLogin = async () => {
    if (!isValidEmail(email)) {
      setEmailErrorMessage(ERROR_MESSAGES.EMAIL_VAILD);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }
    if (!isValidPassword(password)) {
      setPasswordErrorMessage(ERROR_MESSAGES.PASSWORD_MUST_CHAR);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }

    try {
      const { data } = await loginUser({
        variables: { email, password },
      });

      const { token, user } = data.loginUser;
      localStorage.setItem("token", token);
      localStorage.setItem("user", JSON.stringify(user));

      if (rememberMe) {
        localStorage.setItem("email", email);
        localStorage.setItem("password", password);
      } else {
        localStorage.removeItem("email");
        localStorage.removeItem("password");
      }
      login();
      setSuccessMessage(ERROR_MESSAGES.LOGIN_SUCCESSFUL);
      setSnackbarSeverity("success");
      setSnackbarOpen(true);
    } catch (error: any) {
      let errorMessage = error.message.includes("Invalid credentials")
        ? "Invalid Credentials"
        : error.message;
      errorMessage = errorMessage.replace(/^Login failed:\s*/i, "");
      setSuccessMessage(errorMessage);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

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

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
    if (snackbarSeverity === "success") {
      login();
      navigate("/dashboard");
    }
  };

  // Show notices passed from KYC Status routing
  useEffect(() => {
    const state = location.state as any;
    if (state && typeof state.notice === "string") {
      setSuccessMessage(state.notice);
      setSnackbarSeverity(state.severity === "success" ? "success" : "error");
      setSnackbarOpen(true);
      // Clear the state so it doesn't persist on back navigation
      navigate(location.pathname, { replace: true });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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" : "20px",
            width: "100%",
            maxWidth: isMobile ? "95%" : "400px",
            borderRadius: "8px",
            margin: "auto",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Stack spacing={isMobile ? 1 : 1} 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",
                  }}
                >
                  {TEXT.LOGIN}
                </Typography>
              </Item>
              <Item>
                <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    Email
                  </Typography>
                  <IntelliwealthTextField
                    id="username-email"
                    type="text"
                    value={email}
                    placeholder="Enter email"
                    onChange={handleEmailChange}
                    onFocus={handleEmailFocus}
                    onBlur={handleEmailBlur}
                    error={Boolean(emailErrorMessage)}
                    helperText={emailErrorMessage}
                    fullWidth
                    errorMessage={emailErrorMessage}
                    setErrorMessage={setEmailErrorMessage}
                  />
                </Stack>
              </Item>
              <Item>
                <Stack direction="column" spacing={1} sx={{ flex: 1 }}>
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    Password
                  </Typography>
                  <IntelliwealthTextField
                    id="password"
                    type={showPassword ? "text" : "password"}
                    value={password}
                    placeholder="Enter your password"
                    onChange={handlePasswordChange}
                    onFocus={handlePasswordFocus}
                    onBlur={handlePasswordBlur}
                    error={Boolean(passwordErrorMessage)}
                    helperText={passwordErrorMessage}
                    fullWidth
                    errorMessage={passwordErrorMessage}
                    setErrorMessage={setPasswordErrorMessage}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            onClick={handleTogglePassword}
                            edge="end"
                            sx={{ color: themestyle.colors.primary }}
                          >
                            {showPassword ? <Visibility /> : <VisibilityOff />}
                          </IconButton>
                        </InputAdornment>
                      ),
                    }}
                  />
                </Stack>
              </Item>
              <Item>
                <Stack
                  direction={isMobile ? "column" : "row"}
                  justifyContent={isMobile ? "flex-start" : "space-between"}
                  alignItems={isMobile ? "flex-start" : "center"}
                  sx={{ width: "100%" }}
                >
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={rememberMe}
                        onChange={handleRememberMeChange}
                      />
                    }
                    label="Remember Me"
                    sx={{ fontSize: isMobile ? "12px" : "14px" }}
                  />
                  <Link
                    href="/reset-password"
                    sx={{
                      color: themestyle.colors.primary,
                      textDecoration: "none",
                      fontSize: isMobile ? "12px" : "14px",
                      marginTop: isMobile ? "8px" : "0",
                      "&:hover": {
                        textDecoration: "underline",
                      },
                    }}
                  >
                    {TEXT.FORGOT_PASSWORD}
                  </Link>
                </Stack>
              </Item>
              <Item>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleLogin}
                  disabled={isLoginButtonDisabled || loginLoading}
                  fullWidth
                  sx={{
                    padding: isMobile ? "8px" : "10px",
                    fontSize: isMobile ? "14px" : "16px",
                    transform: "none",
                    bgcolor: themestyle.colors.primary,
                    textTransform: "none",
                  }}
                >
                  {loginLoading ? "Logging in..." : TEXT.LOGIN}
                </Button>
              </Item>
              <Item>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={() => navigate("/signup")}
                  fullWidth
                  sx={{
                    padding: isMobile ? "8px" : "10px",
                    fontSize: isMobile ? "14px" : "16px",
                    transform: "none",
                    bgcolor: themestyle.colors.primary,
                    textTransform: "none",
                  }}
                >
                  Don't have an account?
                </Button>
              </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 || passwordErrorMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default Login;
