import React, { Component } from 'react';
import { Navigate } from 'react-router-dom';
import { Box, CircularProgress, Typography } from '@mui/material';

class PaymentSuccess extends Component {


  constructor(props) {
    super(props);
    this.state = {
      redirectUrl: null,
      processing: true,
      error: null
    };
  }

  componentDidMount() {
    this.processMolliePayment();
  }

  processMolliePayment = () => {
    try {
      // Get the stored payment ID from localStorage
      const pendingPayment = localStorage.getItem('pendingPayment');
      
      if (!pendingPayment) {
        console.error('No pending payment found in localStorage');
        this.setState({
          redirectUrl: '/profile#cart',
          processing: false,
          error: 'No payment information found'
        });
        return;
      }

      let paymentData;
      try {
        paymentData = JSON.parse(pendingPayment);
        // Clear the pending payment data
        localStorage.removeItem('pendingPayment');
      } catch (error) {
        console.error('Error parsing pending payment data:', error);
        this.setState({
          redirectUrl: '/profile#cart',
          processing: false,
          error: 'Invalid payment data'
        });
        return;
      }

      if (!paymentData.paymentId) {
        console.error('No payment ID found in stored payment data');
        this.setState({
          redirectUrl: '/profile#cart',
          processing: false,
          error: 'Missing payment ID'
        });
        return;
      }

      // Check payment status with backend
      this.checkMolliePaymentStatus(paymentData.paymentId);
      
    } catch (error) {
      console.error('Error processing Mollie payment:', error);
      this.setState({
        redirectUrl: '/profile#cart',
        processing: false,
        error: 'Payment processing failed'
      });
    }
  };

  checkMolliePaymentStatus = (paymentId) => {
 


    window.socketManager.emit('checkMollieIntent', { paymentId }, (response) => {
      if (response.success) {
        console.log('Payment Status:', response.payment.status);
        console.log('Is Paid:', response.payment.isPaid);
        console.log('Order Created:', response.order.created);
        
        if (response.order.orderId) {
          console.log('Order ID:', response.order.orderId);
        }

        // Build the redirect URL with Mollie completion parameters
        const profileUrl = new URL('/profile', window.location.origin);
        profileUrl.searchParams.set('mollieComplete', 'true');
        profileUrl.searchParams.set('mollie_payment_id', paymentId);
        profileUrl.searchParams.set('mollie_status', response.payment.status);
        profileUrl.searchParams.set('mollie_amount', response.payment.amount);
        profileUrl.searchParams.set('mollie_timestamp', Date.now().toString());
        profileUrl.searchParams.set('mollie_is_paid', response.payment.isPaid.toString());
        
        if (response.order.orderId) {
          profileUrl.searchParams.set('mollie_order_id', response.order.orderId.toString());
        }
        
        // Set hash based on payment success: orders for successful payments, cart for failed payments
        profileUrl.hash = response.payment.isPaid ? '#orders' : '#cart';
        
        this.setState({
          redirectUrl: profileUrl.pathname + profileUrl.search + profileUrl.hash,
          processing: false
        });
      } else {
        console.error('Failed to check payment status:', response.error);
        this.setState({
          redirectUrl: '/profile#cart',
          processing: false,
          error: response.error || 'Payment verification failed'
        });
      }
    });
  };

  render() {
    const { redirectUrl, processing, error } = this.state;

    if (processing) {
      return (
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
            minHeight: '60vh',
            gap: 2
          }}
        >
          <CircularProgress size={60} />
          <Typography variant="h6" color="text.secondary">
            Zahlung wird überprüft...
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Bitte warten Sie, während wir Ihre Zahlung bei Mollie überprüfen.
          </Typography>
        </Box>
      );
    }

    if (error) {
      return <Navigate to="/profile#cart" replace />;
    }

    if (redirectUrl) {
      return <Navigate to={redirectUrl} replace />;
    }

    // Fallback redirect to profile
    return <Navigate to="/profile#cart" replace />;
  }
}

export default PaymentSuccess; 