import React, { useState, useEffect, useRef } from "react";
import { Typography, Box, Button, IconButton, useTheme, useMediaQuery, Alert, CircularProgress, Snackbar } from "@mui/material";
import { useNavigate, useLocation } from "react-router-dom";
import CloseIcon from "@mui/icons-material/Close";
import EmailIcon from "@mui/icons-material/Email";
import { EMAIL_APPROVAL, EMAIL_VERIFICATION } from "../../graphql/mutation";
import { useMutation, useQuery } from "@apollo/client";
import { GET_USER_BY_TOKEN } from "../../graphql/query";

interface ApprovalResponse {
  success: boolean;
  message: string;
}

interface User {
  id: string;
  email: string;
}

const AdminEmailVerification = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const navigate = useNavigate();
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const token = queryParams.get("token") || "";
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [approvalStatus, setApprovalStatus] = useState<ApprovalResponse | null>(null);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">("success");
  const [snackbarMessage, setSnackbarMessage] = useState("");
  const [emailApproval] = useMutation(EMAIL_APPROVAL);
  const [emailVerification, { loading: verificationLoading, error: verificationError }] = useMutation(EMAIL_VERIFICATION);
  const isMounted = useRef(true);

  const { data, error: fetchError } = useQuery(GET_USER_BY_TOKEN, {
    variables: { token },
    skip: !token,
  });

  useEffect(() => {
    isMounted.current = true;
    if (data && data.getUserByToken) {
      localStorage.setItem("user", JSON.stringify(data.getUserByToken));
      setUser(data.getUserByToken);
      setLoading(false);
    } else if (fetchError) {
      console.error("Fetch error:", fetchError.message);
      setApprovalStatus({ success: false, message: "Failed to fetch user data, token may be expired" });
      setSnackbarSeverity("error");
      setSnackbarMessage("Failed to fetch user data, token may be expired. Please resend verification email.");
      setSnackbarOpen(true);
      setLoading(false);
    }
    return () => {
      isMounted.current = false;
    };
  }, [data, fetchError, location.pathname]);

  useEffect(() => {
    if (token && user && isMounted.current) {
      handleApprove();
    }
  }, [token, user]);

  const handleApprove = async () => {
    setLoading(true);
    try {
      const { data } = await emailApproval({
        variables: { token },
      });
      setApprovalStatus(data.emailApproval);
      setLoading(false);
      setSnackbarSeverity(data.emailApproval.success ? "success" : "error");
      setSnackbarMessage(
        data.emailApproval.success ? "Verifying your email, please wait..." : data.emailApproval.message || "Approval failed."
      );
      setSnackbarOpen(true);
      if (data.emailApproval.success) {
      } else {
        console.error("Approval failed:", data.emailApproval.message);
        if (
          data.emailApproval.message?.toLowerCase().includes("already used") ||
          data.emailApproval.message?.toLowerCase().includes("already verified") ||
          data.emailApproval.message?.toLowerCase().includes("invalid token")
        ) {
          setSnackbarSeverity("success");
          setSnackbarMessage("Verifying your email, please wait...");
          setSnackbarOpen(true);
        }
      }
    } catch (error: any) {
      console.error("Error during approval:", error.message);
      setApprovalStatus({ success: false, message: `Approval failed: ${error.message}` });
      setSnackbarSeverity("error");
      setSnackbarMessage(`Approval failed: ${error.message}`);
      setSnackbarOpen(true);
      setLoading(false);
      if (
        error.message?.toLowerCase().includes("already used") ||
        error.message?.toLowerCase().includes("already verified") ||
        error.message?.toLowerCase().includes("invalid token")
      ) {
        setSnackbarSeverity("success");
        setSnackbarMessage("Your email is approved!");
        setSnackbarOpen(true);
      }
    }
  };

  const handleResendVerification = async () => {
    if (!user?.email) {
      setSnackbarSeverity("error");
      setSnackbarMessage("No email address available to resend verification.");
      setSnackbarOpen(true);
      return;
    }

    setLoading(true);
    try {
      const verificationResult = await emailVerification({
        variables: { email: user.email },
      });
      const { success, message } = verificationResult.data.emailVerification;
      setSnackbarSeverity(success ? "success" : "error");
      setSnackbarMessage(message || (success ? "Verification email resent successfully!" : "Failed to resend verification email."));
      setSnackbarOpen(true);
      setLoading(false);
    } catch (error: any) {
      console.error("Error resending verification:", error.message);
      setSnackbarSeverity("error");
      setSnackbarMessage(`Failed to resend verification email: ${error.message}`);
      setSnackbarOpen(true);
      setLoading(false);
    }
  };

  const handleSnackbarClose = () => {
    setSnackbarOpen(false);
    if (snackbarSeverity === "success" && snackbarMessage === "Verifying your email, please wait...") {
      if (isMounted.current) {
        try {
          localStorage.setItem("emailApproved", "true");
          navigate("/admin/profile", { replace: true });
        } catch (error) {
          console.error("Navigation error:", error);
        }
      } else {
        console.warn("Component unmounted, navigation to /admin/profile skipped");
      }
    }
  };

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minHeight: "85vh",
        backgroundColor: "#F9FAFC",
        p: isMobile ? 2 : 4,
      }}
    >
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          gap: 2,
          maxWidth: 400,
          width: "100%",
          backgroundColor: "#FFFFFF",
          borderRadius: "8px",
          p: isMobile ? 2 : 3,
          boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
          position: "relative",
        }}
      >
        <EmailIcon sx={{ fontSize: 60, color: "#1976D2" }} />
        <Typography variant={isMobile ? "h6" : "h5"} color="textPrimary" fontWeight="bold">
          Just One More Step
        </Typography>
        <Typography variant="body1" color="textSecondary" textAlign="center">
          Almost done! Please wait a few seconds while your email is being verified, and you’ll be automatically redirected to the next step.
        </Typography>
        <Typography variant="body1" color="primary" fontWeight="medium">
          {user ? user.email : "Loading..."}
        </Typography>
        <Button
          variant="text"
          color="primary"
          onClick={handleResendVerification}
          disabled={!user || loading || verificationLoading}
          sx={{ mt: 1, borderRadius: "20px" }}
        >
          Resend Verification Email
        </Button>
        {loading || verificationLoading ? <CircularProgress sx={{ mt: 2 }} /> : null}
        <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>
            }
          >
            {snackbarMessage}
          </Alert>
        </Snackbar>
      </Box>
    </Box>
  );
};

export default AdminEmailVerification;