import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Container,
  CircularProgress,
  Alert,
  Button,
  TextField,
  Card,
  CardContent,
  Divider,
  FormControlLabel,
  Checkbox,
  List,
  ListItem,
  ListItemText,
  Grid,
  Paper,
  Switch
} from '@mui/material';
import { useNavigate, useParams } from 'react-router-dom';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import ErrorIcon from '@mui/icons-material/Error';
import PersonIcon from '@mui/icons-material/Person';
import apiClient from '@services/api';

const SubscriptionPreferencesPage = () => {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState(null);
  const [subscriber, setSubscriber] = useState(null);
  const [lists, setLists] = useState([]);
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    listPreferences: {}
  });
  
  const { token } = useParams();
  const navigate = useNavigate();
  
  useEffect(() => {
    const loadSubscriptionPreferences = async () => {
      try {
        if (!token) {
          setError('Missing preferences token. You need a valid link to access your preferences.');
          setLoading(false);
          return;
        }
        
        // Call the API to get subscriber info and preferences
        const response = await apiClient.get(`/api/subscribers/preferences?token=${token}`);
        
        // Set subscriber info
        setSubscriber(response.data.subscriber);
        setLists(response.data.lists);
        
        // Initialize form data
        const { email, first_name, last_name } = response.data.subscriber;
        const listPrefs = {};
        
        response.data.lists.forEach(list => {
          listPrefs[list.id] = list.is_subscribed;
        });
        
        setFormData({
          firstName: first_name || '',
          lastName: last_name || '',
          email: email,
          listPreferences: listPrefs
        });
        
        setLoading(false);
      } catch (error) {
        setError(
          error.response?.data?.message || 
          'An error occurred while loading your preferences. The link may be invalid or expired.'
        );
        setLoading(false);
      }
    };
    
    loadSubscriptionPreferences();
  }, [token]);
  
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  const handleListToggle = (listId) => {
    setFormData(prev => ({
      ...prev,
      listPreferences: {
        ...prev.listPreferences,
        [listId]: !prev.listPreferences[listId]
      }
    }));
  };
  
  const handleUnsubscribeAll = () => {
    const updatedPrefs = {};
    Object.keys(formData.listPreferences).forEach(listId => {
      updatedPrefs[listId] = false;
    });
    
    setFormData(prev => ({
      ...prev,
      listPreferences: updatedPrefs
    }));
  };
  
  const handleSavePreferences = async (e) => {
    e.preventDefault();
    setSaving(true);
    
    try {
      // Call API to update preferences
      await apiClient.post(`/api/subscribers/preferences?token=${token}`, {
        firstName: formData.firstName,
        lastName: formData.lastName,
        listPreferences: formData.listPreferences
      });
      
      setSaved(true);
      setSaving(false);
    } catch (error) {
      setError(
        error.response?.data?.message || 
        'An error occurred while saving your preferences. Please try again or contact support.'
      );
      setSaving(false);
    }
  };
  
  return (
    <Container maxWidth="md">
      <Box sx={{ py: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom align="center" sx={{ mb: 4 }}>
          Email Subscription Preferences
        </Typography>
        
        {loading ? (
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', py: 4 }}>
            <CircularProgress size={60} sx={{ mb: 3 }} />
            <Typography variant="h6">
              Loading your preferences...
            </Typography>
          </Box>
        ) : error ? (
          <Card>
            <CardContent sx={{ textAlign: 'center', p: 4 }}>
              <ErrorIcon color="error" sx={{ fontSize: 80, mb: 2 }} />
              <Typography variant="h5" gutterBottom>
                Unable to Load Preferences
              </Typography>
              <Alert severity="error" sx={{ mb: 3 }}>
                {error}
              </Alert>
              <Button
                variant="contained"
                onClick={() => navigate('/')}
              >
                Return to Home Page
              </Button>
            </CardContent>
          </Card>
        ) : saved ? (
          <Card>
            <CardContent sx={{ textAlign: 'center', p: 4 }}>
              <CheckCircleIcon color="success" sx={{ fontSize: 80, mb: 2 }} />
              <Typography variant="h5" gutterBottom>
                Preferences Updated Successfully
              </Typography>
              <Typography variant="body1" paragraph>
                Your subscription preferences have been saved. Thank you for keeping your information up to date.
              </Typography>
              <Button
                variant="contained"
                color="primary"
                onClick={() => navigate('/')}
              >
                Return to Home Page
              </Button>
            </CardContent>
          </Card>
        ) : subscriber ? (
          <Box component="form" onSubmit={handleSavePreferences}>
            <Grid container spacing={4}>
              {/* Personal Information */}
              <Grid item xs={12} md={5}>
                <Paper sx={{ p: 3, height: '100%' }}>
                  <Typography variant="h6" gutterBottom>
                    Your Information
                  </Typography>
                  <Divider sx={{ mb: 3 }} />
                  
                  <Box sx={{ mb: 2 }}>
                    <TextField
                      fullWidth
                      label="Email Address"
                      value={formData.email}
                      disabled
                      margin="normal"
                    />
                    
                    <TextField
                      fullWidth
                      label="First Name"
                      name="firstName"
                      value={formData.firstName}
                      onChange={handleInputChange}
                      margin="normal"
                    />
                    
                    <TextField
                      fullWidth
                      label="Last Name"
                      name="lastName"
                      value={formData.lastName}
                      onChange={handleInputChange}
                      margin="normal"
                    />
                  </Box>
                  
                  <Box sx={{ mt: 4 }}>
                    <Typography variant="body2" color="text.secondary">
                      Your information is securely stored and we will never share it with third parties.
                    </Typography>
                  </Box>
                </Paper>
              </Grid>
              
              {/* Subscription Preferences */}
              <Grid item xs={12} md={7}>
                <Paper sx={{ p: 3 }}>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Typography variant="h6" gutterBottom>
                      Email Subscriptions
                    </Typography>
                    <Button 
                      variant="outlined" 
                      color="error" 
                      size="small"
                      onClick={handleUnsubscribeAll}
                    >
                      Unsubscribe All
                    </Button>
                  </Box>
                  <Divider sx={{ mb: 3 }} />
                  
                  {lists.length === 0 ? (
                    <Alert severity="info">
                      You are not currently subscribed to any mailing lists.
                    </Alert>
                  ) : (
                    <List>
                      {lists.map(list => (
                        <ListItem 
                          key={list.id} 
                          divider 
                          secondaryAction={
                            <Switch
                              edge="end"
                              checked={formData.listPreferences[list.id] || false}
                              onChange={() => handleListToggle(list.id)}
                            />
                          }
                        >
                          <ListItemText
                            primary={list.name}
                            secondary={list.description}
                          />
                        </ListItem>
                      ))}
                    </List>
                  )}
                  
                  <Box sx={{ mt: 4 }}>
                    <Typography variant="body2" color="text.secondary" paragraph>
                      Toggle the switches to manage your subscriptions. You can update these preferences at any time 
                      by requesting a new preferences link to your email.
                    </Typography>
                  </Box>
                </Paper>
              </Grid>
            </Grid>
            
            <Box sx={{ mt: 4, display: 'flex', justifyContent: 'space-between' }}>
              <Button
                variant="outlined"
                onClick={() => navigate('/')}
                disabled={saving}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="contained"
                color="primary"
                disabled={saving}
              >
                {saving ? <CircularProgress size={24} /> : 'Save Preferences'}
              </Button>
            </Box>
          </Box>
        ) : null}
      </Box>
    </Container>
  );
};

export default SubscriptionPreferencesPage;