import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  Container,
  CircularProgress,
  Alert,
  Button,
  Card,
  CardContent,
  Divider
} from '@mui/material';
import { useNavigate, useLocation } from 'react-router-dom';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import apiClient from '@services/api';

const SubscriptionConfirmPage = () => {
  const [loading, setLoading] = useState(true);
  const [confirmed, setConfirmed] = useState(false);
  const [error, setError] = useState(null);
  const location = useLocation();
  const navigate = useNavigate();
  
  useEffect(() => {
    const confirmSubscription = async () => {
      try {
        // Get token from URL query params
        const params = new URLSearchParams(location.search);
        const token = params.get('token');
        
        if (!token) {
          setError('Missing confirmation token. Please check your email and click the link again.');
          setLoading(false);
          return;
        }
        
        // Call the API to confirm the subscription
        const response = await apiClient.get(`/api/subscribers/confirm?token=${token}`);
        
        setConfirmed(true);
        setLoading(false);
      } catch (error) {
        setError(
          error.response?.data?.message || 
          'An error occurred while confirming your subscription. The link may be invalid or expired.'
        );
        setLoading(false);
      }
    };
    
    confirmSubscription();
  }, [location]);
  
  return (
    <Container maxWidth="sm">
      <Box sx={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center', 
        justifyContent: 'center', 
        minHeight: '70vh' 
      }}>
        <Card sx={{ width: '100%', mb: 4 }}>
          <CardContent sx={{ textAlign: 'center', p: 4 }}>
            {loading ? (
              <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', py: 4 }}>
                <CircularProgress size={60} sx={{ mb: 3 }} />
                <Typography variant="h6">
                  Confirming your subscription...
                </Typography>
              </Box>
            ) : confirmed ? (
              <Box>
                <CheckCircleIcon color="success" sx={{ fontSize: 80, mb: 2 }} />
                <Typography variant="h4" component="h1" gutterBottom>
                  Subscription Confirmed!
                </Typography>
                <Typography variant="body1" paragraph>
                  Thank you for confirming your subscription. You're now signed up to receive our newsletters and updates.
                </Typography>
                <Divider sx={{ my: 3 }} />
                <Button
                  variant="contained"
                  color="primary"
                  onClick={() => navigate('/')}
                  sx={{ mt: 2 }}
                >
                  Return to Home Page
                </Button>
              </Box>
            ) : (
              <Box>
                <ErrorIcon color="error" sx={{ fontSize: 80, mb: 2 }} />
                <Typography variant="h4" component="h1" gutterBottom>
                  Confirmation Failed
                </Typography>
                <Alert severity="error" sx={{ mb: 3 }}>
                  {error}
                </Alert>
                <Button
                  variant="contained"
                  onClick={() => navigate('/')}
                >
                  Return to Home Page
                </Button>
              </Box>
            )}
          </CardContent>
        </Card>
      </Box>
    </Container>
  );
};

export default SubscriptionConfirmPage;