import React, { ChangeEvent, useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import {
  Box,
  Paper,
  Button,
  Container,
  Typography,
  Stack,
  Snackbar,
  Alert,
  IconButton,
  InputAdornment,
  useMediaQuery,
  Link,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
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 { CHANGE_PASSWORD } 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 AdminChangePassword: React.FC = () => {
  const [password, setPassword] = useState("");
  const { login } = useSession();
  const [confirmPassword, setConfirmPassword] = useState("");
  const [passwordErrorMessage, setPasswordErrorMessage] = useState("");
  const [confirmPasswordErrorMessage, setConfirmPasswordErrorMessage] =
    useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">(
    "error"
  );
  const [isSubmitButtonDisabled, setIsSubmitButtonDisabled] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const isMobile = useMediaQuery("(max-width:600px)");
  const isTablet = useMediaQuery("(min-width:601px) and (max-width:900px)");
  const [changePassword, { loading: changeLoading, error: changeError }] =
    useMutation(CHANGE_PASSWORD);

  const queryParams = new URLSearchParams(location.search);
  const token = queryParams.get("token") || "";

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

  const isPasswordMatch = (
    password: string,
    confirmPassword: string
  ): boolean => {
    return password === confirmPassword;
  };

  useEffect(() => {
    const passwordValid = isValidPassword(password);
    const passwordsMatch = isPasswordMatch(password, confirmPassword);
    const tokenValid = token !== "";
    setIsSubmitButtonDisabled(!(passwordValid && passwordsMatch && tokenValid));
  }, [password, confirmPassword, token]);

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

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

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

  const handleConfirmPasswordFocus = () => {
    setConfirmPasswordErrorMessage("");
  };

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

  const handleConfirmPasswordBlur = () => {
    if (confirmPassword.length === 0) {
      setConfirmPasswordErrorMessage(TEXT.CONFIRM_PASSWORD);
    } else if (!isPasswordMatch(password, confirmPassword)) {
      setConfirmPasswordErrorMessage(ERROR_MESSAGES.PASSWORD_DO_NOT_MATCH);
    } else {
      setConfirmPasswordErrorMessage("");
    }
  };

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

  const handleToggleConfirmPassword = () => {
    setShowConfirmPassword(!showConfirmPassword);
  };

  const handleSubmit = async () => {
    if (!token) {
      setSuccessMessage(TEXT.INVAILDP_TOKEN);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }
    if (!isValidPassword(password)) {
      setPasswordErrorMessage(ERROR_MESSAGES.PASSWORD_MUST_CHAR);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }
    if (!isPasswordMatch(password, confirmPassword)) {
      setConfirmPasswordErrorMessage(ERROR_MESSAGES.PASSWORD_DO_NOT_MATCH);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }

    try {
      const { data } = await changePassword({
        variables: { token, newPassword: password },
      });

      if (data.changePassword.success) {
        login();
        setSuccessMessage(data.changePassword.message || TEXT.PASSWORD_CHANGED);
        setSnackbarSeverity("success");
      } else {
        setSuccessMessage(data.changePassword.message);
        setSnackbarSeverity("error");
      }
      setSnackbarOpen(true);
    } catch (error: any) {
      const errorMessage = error.message.includes("Invalid token")
        ? "Invalid or expired token."
        : error.message;
      setSuccessMessage(errorMessage);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

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

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
    login();
    if (snackbarSeverity === "success") {
      navigate("/admin/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",
                  }}
                >
                  Change Password
                </Typography>
              </Item>
              <Item>
                <Stack direction="column" spacing={1} width="100%">
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    New Password
                  </Typography>
                  <IntelliwealthTextField
                    id="password"
                    type={showPassword ? "text" : "password"}
                    value={password}
                    placeholder="Enter your new password"
                    onChange={handlePasswordChange}
                    onFocus={handlePasswordFocus}
                    onBlur={handlePasswordBlur}
                    error={Boolean(passwordErrorMessage)}
                    helperText={passwordErrorMessage}
                    fullWidth
                    errorMessage={passwordErrorMessage}
                    setErrorMessage={setPasswordErrorMessage}
                    sx={{
                      "& .MuiOutlinedInput-root": { borderRadius: "8px" },
                      "& .MuiInputLabel-root": {
                        fontSize: isMobile ? "14px" : "16px",
                      },
                      "& .MuiInputBase-input": {
                        fontSize: isMobile ? "14px" : "16px",
                      },
                    }}
                    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="column" spacing={1} width="100%">
                  <Typography
                    variant="body2"
                    sx={{
                      color: "#222222",
                      fontFamily: themestyle.fontFamily.lato,
                      fontWeight: 500,
                      textAlign: "left",
                    }}
                  >
                    Confirm New Password
                  </Typography>
                  <IntelliwealthTextField
                    id="confirm-password"
                    type={showConfirmPassword ? "text" : "password"}
                    value={confirmPassword}
                    placeholder="Confirm your new password"
                    onChange={handleConfirmPasswordChange}
                    onFocus={handleConfirmPasswordFocus}
                    onBlur={handleConfirmPasswordBlur}
                    error={Boolean(confirmPasswordErrorMessage)}
                    helperText={confirmPasswordErrorMessage}
                    fullWidth
                    errorMessage={confirmPasswordErrorMessage}
                    setErrorMessage={setConfirmPasswordErrorMessage}
                    sx={{
                      "& .MuiOutlinedInput-root": { borderRadius: "8px" },
                      "& .MuiInputLabel-root": {
                        fontSize: isMobile ? "14px" : "16px",
                      },
                      "& .MuiInputBase-input": {
                        fontSize: isMobile ? "14px" : "16px",
                      },
                    }}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            onClick={handleToggleConfirmPassword}
                            edge="end"
                            sx={{ color: themestyle.colors.primary }}
                          >
                            {showConfirmPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      ),
                    }}
                  />
                </Stack>
              </Item>
              <Item>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleSubmit}
                  disabled={isSubmitButtonDisabled || changeLoading}
                  fullWidth
                  sx={{
                    padding: isMobile ? "8px" : "10px",
                    fontSize: isMobile ? "14px" : "16px",
                    transform: "none",
                    bgcolor: themestyle.colors.primary,
                    textTransform: "none",
                  }}
                >
                  {changeLoading ? "Changing Password..." : "Change Password"}
                </Button>
              </Item>
              <Item>
                <Link
                  href="/admin/login"
                  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={3000}
        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 ||
            passwordErrorMessage ||
            confirmPasswordErrorMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default AdminChangePassword;
