import React, { useState, useEffect, useRef } from "react";
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  CircularProgress,
  Avatar,
  LinearProgress,
  Chip,
  Stack,
  Paper,
  Divider,
  Alert,
} from "@mui/material";
import {
  CheckCircle,
  Schedule,
  ArrowBack,
  OpenInNew,
  Error,
  Refresh,
} from "@mui/icons-material";
import { green, blue, red, grey } from "@mui/material/colors";
import { API_BASE_URL } from "../../common/envVariables";
import { useNavigate } from "react-router-dom";

const PaymentSuccessPage = () => {
  const [status, setStatus] = useState("processing"); // 'processing', 'success', 'error'
  const [invoiceUrl, setInvoiceUrl] = useState("");
  const [timeElapsed, setTimeElapsed] = useState(0);
  const [token, setToken] = useState("");
  const navigate = useNavigate();
  
  // Use refs to track active polling and timer
  const pollingRef = useRef(null);
  const timerRef = useRef(null);
  const isPollingActiveRef = useRef(false);

  const checkPaymentStatus = async () => {
    try {
      if (!token || !isPollingActiveRef.current) {
        return;
      }

      const response = await fetch(`${API_BASE_URL}/stripe/get-invoice`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      });

      const data = await response.json();

      if (data.data && isPollingActiveRef.current) {
        // Success - stop polling and timer
        isPollingActiveRef.current = false;
        if (pollingRef.current) {
          clearTimeout(pollingRef.current);
          pollingRef.current = null;
        }
        if (timerRef.current) {
          clearInterval(timerRef.current);
          timerRef.current = null;
        }
        
        setStatus("success");
        setInvoiceUrl(data.data);
      } else if (isPollingActiveRef.current) {
        // Still processing, check again in 10 seconds
        pollingRef.current = setTimeout(() => checkPaymentStatus(), 10000);
      }
    } catch (error) {
      console.error("Error checking payment status:", error);
      if (isPollingActiveRef.current) {
        // Retry after 10 seconds on error
        pollingRef.current = setTimeout(() => checkPaymentStatus(), 10000);
      }
    }
  };

  const startTimer = () => {
    timerRef.current = setInterval(() => {
      setTimeElapsed(prev => prev + 1);
    }, 1000);
  };

  const stopPollingAndTimer = () => {
    isPollingActiveRef.current = false;
    
    if (pollingRef.current) {
      clearTimeout(pollingRef.current);
      pollingRef.current = null;
    }
    
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  const openInvoice = () => {
    // Stop all polling and timer before navigation
    stopPollingAndTimer();
    
    if (invoiceUrl) {
      window.open(invoiceUrl, "_blank");
    }
    
    // Clean up and navigate
    localStorage.removeItem("temp_signup_token");
    setToken("");
    navigate("/auth/login");
  };

  const goToLogin = () => {
    stopPollingAndTimer();
    localStorage.removeItem("temp_signup_token");
    navigate("/auth/login");
  };

  const goToDashboard = () => {
    stopPollingAndTimer();
    navigate("/dashboard");
  };

  const handleRetry = () => {
    stopPollingAndTimer();
    setStatus("processing");
    setTimeElapsed(0);
    isPollingActiveRef.current = true;
    startTimer();
    checkPaymentStatus();
  };

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };

  useEffect(() => {
    const storedToken = localStorage.getItem("temp_signup_token");
    if (!storedToken) {
      navigate("/auth/login");
      return;
    }
    
    setToken(storedToken);
    isPollingActiveRef.current = true;
    startTimer();
    
    // Start checking payment status once token is set
    const initializeChecking = async () => {
      if (storedToken) {
        checkPaymentStatus();
      }
    };
    
    initializeChecking();

    // Cleanup function
    return () => {
      stopPollingAndTimer();
    };
  }, []); // Remove token from dependency array to avoid infinite loop

  // Separate useEffect for when token changes
  useEffect(() => {
    if (token && status === "processing" && !isPollingActiveRef.current) {
      isPollingActiveRef.current = true;
      checkPaymentStatus();
    }
  }, [token]);

  if (status === "processing") {
    return (
      <Box
        sx={{
          minHeight: "100vh",
          background: "linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          p: 2,
        }}
      >
        <Card sx={{ maxWidth: 400, width: "100%", textAlign: "center" }}>
          <CardContent sx={{ p: 4 }}>
            {/* Header */}
            <Avatar
              sx={{
                width: 64,
                height: 64,
                bgcolor: blue[100],
                color: blue[600],
                mx: "auto",
                mb: 2,
              }}
            >
              <Schedule />
            </Avatar>

            <Typography variant="h5" fontWeight="bold" gutterBottom>
              Processing Your Payment
            </Typography>

            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              Please wait while we confirm your subscription and prepare your
              invoice...
            </Typography>

            {/* Loading Animation */}
            <Box sx={{ mb: 3 }}>
              <CircularProgress size={40} sx={{ mb: 2 }} />
              <Typography variant="body2" color="text.secondary">
                Time elapsed: {formatTime(timeElapsed)}
              </Typography>
            </Box>

            {/* Progress Steps */}
            <Box sx={{ mb: 4 }}>
              <Stack spacing={1}>
                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "flex-start",
                  }}
                >
                  <CheckCircle
                    sx={{ color: green[500], mr: 1, fontSize: 18 }}
                  />
                  <Typography variant="body2" sx={{ color: green[600] }}>
                    Payment Submitted
                  </Typography>
                </Box>

                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "flex-start",
                  }}
                >
                  <CircularProgress
                    size={16}
                    sx={{ mr: 1, color: blue[500] }}
                  />
                  <Typography variant="body2" sx={{ color: blue[600] }}>
                    Confirming Payment
                  </Typography>
                </Box>

                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "flex-start",
                  }}
                >
                  <Schedule sx={{ color: grey[400], mr: 1, fontSize: 18 }} />
                  <Typography variant="body2" color="text.disabled">
                    Generating Invoice
                  </Typography>
                </Box>
              </Stack>
            </Box>

            {/* Back Button */}
            <Button
              fullWidth
              variant="outlined"
              startIcon={<ArrowBack />}
              onClick={goToLogin}
              sx={{ mt: 2 }}
            >
              Back to Login
            </Button>
          </CardContent>
        </Card>
      </Box>
    );
  }

  if (status === "success") {
    return (
      <Box
        sx={{
          minHeight: "100vh",
          background: "linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          p: 2,
        }}
      >
        <Card sx={{ maxWidth: 400, width: "100%", textAlign: "center" }}>
          <CardContent sx={{ p: 4 }}>
            {/* Success Header */}
            <Avatar
              sx={{
                width: 64,
                height: 64,
                bgcolor: green[100],
                color: green[600],
                mx: "auto",
                mb: 2,
              }}
            >
              <CheckCircle />
            </Avatar>

            <Typography variant="h5" fontWeight="bold" gutterBottom>
              Payment Successful!
            </Typography>

            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              Your subscription has been activated and your invoice is ready.
            </Typography>

            {/* Processing Time */}
            <Chip
              label={`Processed in ${formatTime(timeElapsed)}`}
              color="success"
              variant="outlined"
              sx={{ mb: 3 }}
            />

            {/* Action Buttons */}
            <Stack spacing={2}>
              <Button
                fullWidth
                variant="contained"
                startIcon={<OpenInNew />}
                onClick={openInvoice}
                sx={{ py: 1.5 }}
              >
                View Invoice
              </Button>

              <Button
                fullWidth
                variant="outlined"
                onClick={goToDashboard}
                sx={{ py: 1.5 }}
              >
                Continue to Dashboard
              </Button>

              <Divider sx={{ my: 1 }} />

              <Button
                fullWidth
                color="inherit"
                startIcon={<ArrowBack />}
                onClick={goToLogin}
              >
                Back to Login
              </Button>
            </Stack>
          </CardContent>
        </Card>
      </Box>
    );
  }

  if (status === "error") {
    return (
      <Box
        sx={{
          minHeight: "100vh",
          background: "linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%)",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          p: 2,
        }}
      >
        <Card sx={{ maxWidth: 400, width: "100%", textAlign: "center" }}>
          <CardContent sx={{ p: 4 }}>
            {/* Error Header */}
            <Avatar
              sx={{
                width: 64,
                height: 64,
                bgcolor: red[100],
                color: red[600],
                mx: "auto",
                mb: 2,
              }}
            >
              <Error />
            </Avatar>

            <Typography variant="h5" fontWeight="bold" gutterBottom>
              Payment Processing Error
            </Typography>

            <Alert severity="error" sx={{ mb: 3, textAlign: "left" }}>
              We encountered an issue while processing your payment. Please try
              again or contact support.
            </Alert>

            {/* Action Buttons */}
            <Stack spacing={2}>
              <Button
                fullWidth
                variant="contained"
                startIcon={<Refresh />}
                onClick={handleRetry}
                sx={{ py: 1.5 }}
              >
                Try Again
              </Button>

              <Button
                fullWidth
                variant="outlined"
                startIcon={<ArrowBack />}
                onClick={goToLogin}
                sx={{ py: 1.5 }}
              >
                Back to Login
              </Button>
            </Stack>
          </CardContent>
        </Card>
      </Box>
    );
  }
};

export default PaymentSuccessPage;