import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  CircularProgress,
  Alert,
  Typography
} from '@mui/material';
import { useSendEmail } from '../hooks/adminHooks';

/**
 * Email Dialog component for sending emails to customers
 * @param {Object} props - Component props
 * @param {boolean} props.open - Whether the dialog is open
 * @param {Function} props.onClose - Function to call when dialog is closed
 * @param {Object} props.recipient - Recipient user object (includes email, first_name, last_name)
 */
const EmailDialog = ({ open, onClose, recipient }) => {
  const [formData, setFormData] = useState({
    subject: '',
    message: ''
  });
  const [formErrors, setFormErrors] = useState({});
  
  // Send email mutation
  const sendEmail = useSendEmail();
  
  // Handle form changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear validation error
    if (formErrors[name]) {
      setFormErrors(prev => ({ ...prev, [name]: '' }));
    }
  };
  
  // Handle form submission
  const handleSubmit = () => {
    // Validate form
    const errors = {};
    if (!formData.subject.trim()) {
      errors.subject = 'Subject is required';
    }
    if (!formData.message.trim()) {
      errors.message = 'Message is required';
    }
    
    if (Object.keys(errors).length > 0) {
      setFormErrors(errors);
      return;
    }
    
    // Submit form
    sendEmail.mutate({
      to: recipient.email,
      name: `${recipient.first_name} ${recipient.last_name}`,
      subject: formData.subject,
      message: formData.message
    }, {
      onSuccess: () => {
        handleClose();
      }
    });
  };
  
  // Handle dialog close
  const handleClose = () => {
    // Reset form
    setFormData({
      subject: '',
      message: ''
    });
    setFormErrors({});
    
    // Close dialog
    onClose();
  };
  
  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <DialogTitle>
        Send Email to Customer
        {recipient && (
          <Typography variant="subtitle1">
            Recipient: {recipient.first_name} {recipient.last_name} ({recipient.email})
          </Typography>
        )}
      </DialogTitle>
      
      <DialogContent>
        {sendEmail.isError && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {sendEmail.error?.message || 'Failed to send email. Please try again.'}
          </Alert>
        )}
        
        <TextField
          autoFocus
          margin="dense"
          label="Subject"
          name="subject"
          fullWidth
          variant="outlined"
          value={formData.subject}
          onChange={handleChange}
          error={!!formErrors.subject}
          helperText={formErrors.subject}
          sx={{ mb: 2 }}
        />
        
        <TextField
          margin="dense"
          label="Message"
          name="message"
          fullWidth
          multiline
          rows={8}
          variant="outlined"
          value={formData.message}
          onChange={handleChange}
          error={!!formErrors.message}
          helperText={formErrors.message}
        />
      </DialogContent>
      
      <DialogActions>
        <Button onClick={handleClose}>Cancel</Button>
        <Button 
          onClick={handleSubmit} 
          variant="contained" 
          color="primary"
          disabled={sendEmail.isLoading}
        >
          {sendEmail.isLoading ? (
            <CircularProgress size={24} sx={{ mr: 1 }} />
          ) : null}
          Send Email
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default EmailDialog;