import React, { ChangeEvent, useState, useEffect } from "react";
import { useNavigate } 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 { REGISTER_USER, CUSTOMER_EMAIL_VERIFICATION } from "../../graphql/mutation";
import IntelliwealthTextField from "../../components/intelliwealthTextField";
import { useSession } from "../../context/sessioncontext";

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

const Signup: React.FC = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { login } = useSession();
  const [confirmPassword, setConfirmPassword] = useState("");
  const [emailErrorMessage, setEmailErrorMessage] = 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 isMobile = useMediaQuery("(max-width:600px)");
  const isTablet = useMediaQuery("(min-width:601px) and (max-width:900px)");
  const [registerUser, { loading: registerLoading, error: registerError }] = useMutation(REGISTER_USER);
  const [emailVerification, { loading: verificationLoading, error: verificationError }] = useMutation(CUSTOMER_EMAIL_VERIFICATION);

  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;
  };

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

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

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

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

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

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

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

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

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

  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 (!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;
    }
    if (!isPasswordMatch(password, confirmPassword)) {
      setConfirmPasswordErrorMessage(ERROR_MESSAGES.PASSWORD_DO_NOT_MATCH);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
      return;
    }

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

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

      // Send verification email
      try {
        const verificationResult = await emailVerification({
          variables: { email },
        });
        const { success, message } = verificationResult.data.customerVerification;
        setSuccessMessage(
          success
            ? "Registration successful! Please check your email to verify your account."
            : message || "Registration successful, but failed to send verification email."
        );
        setSnackbarSeverity(success ? "success" : "error");
      } catch (error: any) {
        setSuccessMessage(`Registration successful, but failed to send verification email: ${error.message}`);
        setSnackbarSeverity("error");
      }

      setSnackbarOpen(true);
    } catch (error: any) {
      const errorMessage = error.message.includes("Email already exists")
        ? "Email already exists"
        : error.message;
      setSuccessMessage(errorMessage);
      setSnackbarSeverity("error");
      setSnackbarOpen(true);
    }
  };

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

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
    if (snackbarSeverity === "success") {
      setTimeout(() => {
        navigate("/");
      }, 2000); // Delay navigation to allow Snackbar to be visible
    }
  };

  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 : 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",
                  }}
                >
                  Signup
                </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>
                <Stack direction="column" spacing={1} width="100%">
                  <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}
                    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 Password
                  </Typography>
                  <IntelliwealthTextField
                    id="confirm-password"
                    type={showConfirmPassword ? "text" : "password"}
                    value={confirmPassword}
                    placeholder="Confirm your 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 || registerLoading || verificationLoading}
                  fullWidth
                  sx={{
                    padding: isMobile ? "8px" : "10px",
                    fontSize: isMobile ? "14px" : "16px",
                    transform: "none",
                    bgcolor: themestyle.colors.primary,
                    textTransform: "none",
                  }}
                >
                  {registerLoading || verificationLoading ? "Signing up..." : "Signup"}
                </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 ||
            passwordErrorMessage ||
            confirmPasswordErrorMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default Signup;