import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  Container,
  CircularProgress,
  Alert,
  Button,
  TextField,
  Card,
  CardContent,
  Divider,
  FormControlLabel,
  Checkbox,
  Radio,
  RadioGroup,
  FormControl,
  FormLabel,
  Chip
} 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 UnsubscribePage = () => {
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(false);
  const [unsubscribed, setUnsubscribed] = useState(false);
  const [error, setError] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [email, setEmail] = useState('');
  const [reason, setReason] = useState('');
  const [customReason, setCustomReason] = useState('');
  const location = useLocation();
  const navigate = useNavigate();
  
  useEffect(() => {
    const checkUnsubscribeParams = async () => {
      try {
        // Get token from URL query params
        const params = new URLSearchParams(location.search);
        const token = params.get('token');
        const emailParam = params.get('email');
        const listId = params.get('listId');
        
        // If we have a token, use it to unsubscribe automatically
        if (token) {
          await handleUnsubscribe(null, token, listId);
        } 
        // If we just have an email, pre-fill the form
        else if (emailParam) {
          setEmail(emailParam);
          setShowForm(true);
          setLoading(false);
        }
        // No token or email, show the form
        else {
          setShowForm(true);
          setLoading(false);
        }
      } catch (error) {
        setError(
          error.response?.data?.message || 
          'An error occurred. Please try again or contact support.'
        );
        setLoading(false);
      }
    };
    
    checkUnsubscribeParams();
  }, [location]);
  
  const handleUnsubscribe = async (e, tokenOverride = null, listIdOverride = null) => {
    if (e) e.preventDefault();
    
    if (!tokenOverride && !email) {
      setError('Please enter your email address.');
      return;
    }
    
    setProcessing(true);
    
    try {
      // Construct parameters
      const params = new URLSearchParams();
      if (tokenOverride) params.append('token', tokenOverride);
      if (!tokenOverride && email) params.append('email', email);
      if (listIdOverride) params.append('listId', listIdOverride);
      
      // Call the API to process the unsubscribe request
      await apiClient.get(`/api/subscribers/unsubscribe?${params.toString()}`);
      
      // Save feedback if provided
      if (reason) {
        try {
          await apiClient.post('/api/subscribers/feedback', {
            email,
            reason: reason === 'other' ? customReason : reason
          });
        } catch (feedbackError) {
          console.error('Error saving feedback:', feedbackError);
          // We don't want to show an error for feedback submission failure
        }
      }
      
      setUnsubscribed(true);
      setProcessing(false);
    } catch (error) {
      setError(
        error.response?.data?.message || 
        'An error occurred while processing your request. Please try again or contact support.'
      );
      setProcessing(false);
    }
  };
  
  return (
    <Container maxWidth="sm">
      <Box sx={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center', 
        justifyContent: 'center', 
        minHeight: '70vh',
        py: 4
      }}>
        <Card sx={{ width: '100%', mb: 4 }}>
          <CardContent sx={{ p: 4 }}>
            {loading ? (
              <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', py: 4 }}>
                <CircularProgress size={60} sx={{ mb: 3 }} />
                <Typography variant="h6">
                  Processing your request...
                </Typography>
              </Box>
            ) : unsubscribed ? (
              <Box sx={{ textAlign: 'center' }}>
                <CheckCircleIcon color="success" sx={{ fontSize: 80, mb: 2 }} />
                <Typography variant="h4" component="h1" gutterBottom>
                  Unsubscribed Successfully
                </Typography>
                <Typography variant="body1" paragraph>
                  You have been successfully unsubscribed from our mailing list.
                  We're sorry to see you go, but we respect your decision.
                </Typography>
                <Typography variant="body2" color="text.secondary" paragraph>
                  If you change your mind, you can always subscribe again in the future.
                </Typography>
                <Divider sx={{ my: 3 }} />
                <Button
                  variant="contained"
                  color="primary"
                  onClick={() => navigate('/')}
                >
                  Return to Home Page
                </Button>
              </Box>
            ) : showForm ? (
              <Box>
                <Typography variant="h4" component="h1" gutterBottom align="center">
                  Unsubscribe
                </Typography>
                <Typography variant="body1" paragraph align="center">
                  We're sorry to see you go. Please enter your email address below to unsubscribe from our mailing list.
                </Typography>
                
                {error && (
                  <Alert severity="error" sx={{ mb: 3 }}>
                    {error}
                  </Alert>
                )}
                
                <Box component="form" onSubmit={handleUnsubscribe} sx={{ mt: 3 }}>
                  <TextField
                    fullWidth
                    label="Email Address"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    margin="normal"
                    required
                    type="email"
                    disabled={processing}
                  />
                  
                  <Box sx={{ mt: 3, mb: 2 }}>
                    <FormControl component="fieldset">
                      <FormLabel component="legend">Would you mind telling us why you're unsubscribing? (Optional)</FormLabel>
                      <RadioGroup
                        value={reason}
                        onChange={(e) => setReason(e.target.value)}
                      >
                        <FormControlLabel 
                          value="too_many" 
                          control={<Radio />} 
                          label="I receive too many emails" 
                        />
                        <FormControlLabel 
                          value="not_relevant" 
                          control={<Radio />} 
                          label="The content is not relevant to me" 
                        />
                        <FormControlLabel 
                          value="not_subscribed" 
                          control={<Radio />} 
                          label="I never subscribed" 
                        />
                        <FormControlLabel 
                          value="other" 
                          control={<Radio />} 
                          label="Other reason" 
                        />
                      </RadioGroup>
                    </FormControl>
                    
                    {reason === 'other' && (
                      <TextField
                        fullWidth
                        label="Please specify"
                        value={customReason}
                        onChange={(e) => setCustomReason(e.target.value)}
                        margin="normal"
                        disabled={processing}
                        multiline
                        rows={2}
                      />
                    )}
                  </Box>
                  
                  <Box sx={{ mt: 4, display: 'flex', justifyContent: 'space-between' }}>
                    <Button
                      variant="outlined"
                      onClick={() => navigate('/')}
                      disabled={processing}
                    >
                      Cancel
                    </Button>
                    <Button
                      type="submit"
                      variant="contained"
                      color="primary"
                      disabled={!email || processing}
                    >
                      {processing ? <CircularProgress size={24} /> : 'Unsubscribe'}
                    </Button>
                  </Box>
                </Box>
              </Box>
            ) : (
              <Box sx={{ textAlign: 'center' }}>
                <ErrorIcon color="error" sx={{ fontSize: 80, mb: 2 }} />
                <Typography variant="h4" component="h1" gutterBottom>
                  Something Went Wrong
                </Typography>
                <Alert severity="error" sx={{ mb: 3 }}>
                  {error || 'Unable to process your request. Please try again or contact support.'}
                </Alert>
                <Button
                  variant="contained"
                  onClick={() => navigate('/')}
                >
                  Return to Home Page
                </Button>
              </Box>
            )}
          </CardContent>
        </Card>
      </Box>
    </Container>
  );
};

export default UnsubscribePage;