import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  FormControlLabel,
  Checkbox,
  Alert,
  CircularProgress,
  Paper,
  Divider,
  InputAdornment,
  IconButton,
  Tooltip,
  Collapse
} from '@mui/material';
import {
  SendOutlined as SendIcon,
  InfoOutlined as InfoIcon,
  CheckCircleOutline as CheckCircleIcon,
} from '@mui/icons-material';
import apiClient from '@services/api';

/**
 * A reusable subscription form component for mailing lists
 * 
 * @param {Object} props - Component props
 * @param {string} props.listId - The ID of the mailing list to subscribe to
 * @param {string} props.title - Form title
 * @param {string} props.description - Form description
 * @param {string} props.buttonText - Submit button text
 * @param {string} props.successMessage - Message to show after successful submission
 * @param {boolean} props.collectNames - Whether to collect first and last names
 * @param {boolean} props.embedded - Whether this form is embedded in another component (styling)
 * @param {function} props.onSuccess - Callback function after successful subscription
 */
const SubscriptionForm = ({
  listId,
  title = "Subscribe to Our Newsletter",
  description = "Stay updated with our latest news and offers.",
  buttonText = "Subscribe",
  successMessage = "Thank you for subscribing! Please check your email to confirm your subscription.",
  collectNames = true,
  embedded = false,
  onSuccess = null,
}) => {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
  });
  const [formErrors, setFormErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [error, setError] = useState(null);
  const [showPrivacyInfo, setShowPrivacyInfo] = useState(false);
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // Clear error when field is edited
    if (formErrors[name]) {
      setFormErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };
  
  const validate = () => {
    const errors = {};
    
    // Validate email
    if (!formData.email) {
      errors.email = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      errors.email = 'Email is invalid';
    }
    
    // Validate names if collectNames is true
    if (collectNames) {
      if (!formData.firstName) {
        errors.firstName = 'First name is required';
      }
    }
    
    // Validate terms acceptance
    if (!acceptedTerms) {
      errors.terms = 'You must accept the terms to subscribe';
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Reset previous errors/success
    setError(null);
    
    // Validate form
    if (!validate()) return;
    
    setIsSubmitting(true);
    
    try {
      // Call the API to subscribe
      await apiClient.post('/api/subscribers/subscribe', {
        email: formData.email,
        firstName: formData.firstName,
        lastName: formData.lastName,
        listId: listId
      });
      
      // Show success message and reset form
      setIsSuccess(true);
      setFormData({
        firstName: '',
        lastName: '',
        email: '',
      });
      setAcceptedTerms(false);
      
      // Call onSuccess callback if provided
      if (onSuccess) onSuccess();
    } catch (err) {
      setError(err.response?.data?.message || 'An error occurred. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };
  
  const containerStyles = embedded 
    ? {} 
    : { 
        maxWidth: 500, 
        mx: 'auto', 
        my: 4, 
        p: 3, 
        borderRadius: 2,
        boxShadow: 3
      };
  
  return (
    <Paper 
      component="form" 
      onSubmit={handleSubmit} 
      sx={containerStyles} 
      elevation={embedded ? 0 : 1}
    >
      {/* Form Header */}
      <Box sx={{ mb: 3, textAlign: embedded ? 'left' : 'center' }}>
        <Typography variant={embedded ? "h6" : "h5"} component="h2" gutterBottom>
          {title}
        </Typography>
        {description && (
          <Typography variant="body2" color="text.secondary">
            {description}
          </Typography>
        )}
      </Box>
      
      {/* Success Message */}
      {isSuccess && (
        <Alert 
          icon={<CheckCircleIcon fontSize="inherit" />} 
          severity="success"
          sx={{ mb: 3 }}
        >
          {successMessage}
        </Alert>
      )}
      
      {/* Error Message */}
      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}
      
      {/* Form Fields */}
      <Box sx={{ display: isSuccess ? 'none' : 'block' }}>
        {collectNames && (
          <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
            <TextField
              name="firstName"
              label="First Name"
              value={formData.firstName}
              onChange={handleInputChange}
              error={!!formErrors.firstName}
              helperText={formErrors.firstName}
              fullWidth
              required
              margin="normal"
              size={embedded ? "small" : "medium"}
            />
            <TextField
              name="lastName"
              label="Last Name"
              value={formData.lastName}
              onChange={handleInputChange}
              error={!!formErrors.lastName}
              helperText={formErrors.lastName}
              fullWidth
              margin="normal"
              size={embedded ? "small" : "medium"}
            />
          </Box>
        )}
        
        <TextField
          name="email"
          label="Email Address"
          type="email"
          value={formData.email}
          onChange={handleInputChange}
          error={!!formErrors.email}
          helperText={formErrors.email}
          fullWidth
          required
          margin="normal"
          size={embedded ? "small" : "medium"}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <Tooltip title="We'll send a confirmation email to verify your address.">
                  <IconButton edge="end" size="small" tabIndex={-1}>
                    <InfoIcon fontSize="small" />
                  </IconButton>
                </Tooltip>
              </InputAdornment>
            ),
          }}
        />
        
        {/* Privacy Info & Terms Checkbox */}
        <Box sx={{ mt: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
            <FormControlLabel
              control={
                <Checkbox 
                  checked={acceptedTerms} 
                  onChange={(e) => setAcceptedTerms(e.target.checked)} 
                  size={embedded ? "small" : "medium"}
                />
              }
              label="I agree to receive emails and accept the terms"
            />
            <Tooltip title="Click for more information">
              <IconButton 
                size="small" 
                onClick={() => setShowPrivacyInfo(!showPrivacyInfo)}
              >
                <InfoIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          </Box>
          
          {formErrors.terms && (
            <Typography variant="caption" color="error" sx={{ ml: 2 }}>
              {formErrors.terms}
            </Typography>
          )}
          
          <Collapse in={showPrivacyInfo}>
            <Box sx={{ mt: 1, p: 2, bgcolor: 'background.paper', borderRadius: 1, fontSize: 'small' }}>
              <Typography variant="body2" paragraph>
                By subscribing, you agree to receive marketing emails from us. We respect your privacy and will never share your information with third parties.
              </Typography>
              <Typography variant="body2">
                You can unsubscribe at any time by clicking the unsubscribe link in the footer of our emails. For information about our privacy practices, visit our website.
              </Typography>
            </Box>
          </Collapse>
        </Box>
        
        {/* Submit Button */}
        <Box sx={{ mt: 3, display: 'flex', justifyContent: embedded ? 'flex-start' : 'center' }}>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            disabled={isSubmitting}
            startIcon={isSubmitting ? <CircularProgress size={20} /> : <SendIcon />}
          >
            {isSubmitting ? 'Subscribing...' : buttonText}
          </Button>
        </Box>
      </Box>
    </Paper>
  );
};

export default SubscriptionForm;