import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { 
  Box, 
  Typography, 
  Paper, 
  Button, 
  CircularProgress, 
  Alert,
  Divider,
} from '@mui/material';
import CheckCircleIcon from '@mui/icons-material/CheckCircleOutline';
import { useStripe } from '../context/StripeContext';
import { useAuth } from '../hooks/reduxHooks';

const PaymentSuccessPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { checkSessionStatus, completeOrder } = useStripe();
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [orderDetails, setOrderDetails] = useState(null);

  useEffect(() => {
    const processPayment = async () => {
      try {
        // Get the session ID from the URL
        const params = new URLSearchParams(location.search);
        const sessionId = params.get('session_id');

        if (!sessionId) {
          setError('No session ID found. Please contact customer support.');
          setIsLoading(false);
          return;
        }

        // Check the session status
        const sessionData = await checkSessionStatus(sessionId);
        
        if (sessionData.status !== 'paid') {
          setError('Payment not completed. Please try again or contact customer support.');
          setIsLoading(false);
          return;
        }

        // Get metadata from session
        const { metadata } = sessionData;
        
        if (!metadata || !metadata.order_id) {
          setError('Missing order information. Please contact customer support.');
          setIsLoading(false);
          return;
        }

        // Complete the order in our system
        const orderResult = await completeOrder(
          metadata.order_id,
          sessionId,
          user
        );

        setOrderDetails({
          orderId: metadata.order_id,
          sessionId
        });
        
        setIsLoading(false);
      } catch (err) {
        console.error('Error processing payment success:', err);
        setError(err.message || 'An error occurred while processing your payment.');
        setIsLoading(false);
      }
    };

    processPayment();
  }, [location.search, checkSessionStatus, completeOrder, user]);

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', py: 6 }}>
        <CircularProgress size={60} sx={{ mb: 3 }} />
        <Typography variant="h6">
          Processing your payment...
        </Typography>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ py: 4 }}>
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
        <Button
          variant="contained"
          onClick={() => navigate('/cart')}
        >
          Return to Cart
        </Button>
      </Box>
    );
  }

  return (
    <Box sx={{ py: 4 }}>
      <Paper sx={{ p: 4, maxWidth: 600, mx: 'auto', textAlign: 'center' }}>
        <CheckCircleIcon color="success" sx={{ fontSize: 80, mb: 2 }} />
        
        <Typography variant="h4" component="h1" gutterBottom>
          Payment Successful!
        </Typography>
        
        <Typography variant="body1" paragraph>
          Thank you for your purchase. Your order has been completed and a confirmation email will be sent shortly.
        </Typography>
        
        <Divider sx={{ my: 3 }} />
        
        <Box sx={{ textAlign: 'left', mb: 3 }}>
          <Typography variant="subtitle1">
            Order Reference: {orderDetails?.orderId.substring(0, 8)}...
          </Typography>
        </Box>
        
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4 }}>
          <Button
            variant="outlined"
            onClick={() => navigate('/products')}
          >
            Continue Shopping
          </Button>
          
          <Button
            variant="contained"
            onClick={() => navigate('/account/orders')}
          >
            View Orders
          </Button>
        </Box>
      </Paper>
    </Box>
  );
};

export default PaymentSuccessPage;