'use client' import { useState, useEffect } from 'react' import { Box, Paper, Typography, TextField, Button, FormControl, InputLabel, Select, MenuItem, Switch, FormControlLabel, Alert, Divider, Card, CardContent, InputAdornment, IconButton, Chip } from '@mui/material' import { Save as SaveIcon, PlayArrow as TestIcon, Visibility, VisibilityOff, Email as EmailIcon, Settings as SettingsIcon, CheckCircle, Error as ErrorIcon } from '@mui/icons-material' interface MailgunSettings { id?: string apiKey?: string domain: string region: string fromEmail: string fromName: string replyToEmail?: string isEnabled: boolean testMode: boolean webhookUrl?: string createdAt?: string updatedAt?: string } export default function MailgunSettingsPage() { const [settings, setSettings] = useState({ domain: '', region: 'US', fromEmail: '', fromName: '', isEnabled: false, testMode: true }) const [loading, setLoading] = useState(false) const [saving, setSaving] = useState(false) const [testing, setTesting] = useState(false) const [showApiKey, setShowApiKey] = useState(false) const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null) const [testEmail, setTestEmail] = useState('') const [connectionStatus, setConnectionStatus] = useState<'unknown' | 'connected' | 'error'>('unknown') useEffect(() => { loadSettings() }, []) const loadSettings = async () => { setLoading(true) try { const response = await fetch('/api/admin/mailgun', { credentials: 'include' }) if (response.ok) { const data = await response.json() if (data.success && data.data) { setSettings(data.data) if (data.data.isEnabled) { testConnection() } } } } catch (error) { console.error('Error loading settings:', error) setMessage({ type: 'error', text: 'Failed to load settings' }) } finally { setLoading(false) } } const handleSave = async () => { setSaving(true) setMessage(null) try { const method = settings.id ? 'PUT' : 'POST' const response = await fetch('/api/admin/mailgun', { method, headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify(settings) }) const data = await response.json() if (response.ok && data.success) { setSettings(data.data) setMessage({ type: 'success', text: 'Settings saved successfully' }) if (data.data.isEnabled) { testConnection() } } else { setMessage({ type: 'error', text: data.error || 'Failed to save settings' }) } } catch (error) { console.error('Error saving settings:', error) setMessage({ type: 'error', text: 'Failed to save settings' }) } finally { setSaving(false) } } const testConnection = async () => { setTesting(true) try { const response = await fetch('/api/admin/mailgun/test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ testType: 'connection' }) }) const data = await response.json() if (data.success) { setConnectionStatus('connected') setMessage({ type: 'success', text: 'Connection test successful' }) } else { setConnectionStatus('error') setMessage({ type: 'error', text: `Connection failed: ${data.error}` }) } } catch (error) { setConnectionStatus('error') setMessage({ type: 'error', text: 'Connection test failed' }) } finally { setTesting(false) } } const sendTestEmail = async () => { if (!testEmail) { setMessage({ type: 'error', text: 'Please enter a test email address' }) return } setTesting(true) try { const response = await fetch('/api/admin/mailgun/test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ testType: 'email', email: testEmail }) }) const data = await response.json() if (data.success) { setMessage({ type: 'success', text: `Test email sent successfully! ${data.messageId ? `Message ID: ${data.messageId}` : ''}` }) } else { setMessage({ type: 'error', text: `Failed to send test email: ${data.error}` }) } } catch (error) { setMessage({ type: 'error', text: 'Failed to send test email' }) } finally { setTesting(false) } } const handleChange = (field: keyof MailgunSettings, value: any) => { setSettings(prev => ({ ...prev, [field]: value })) } return ( Mailgun Settings {message && ( setMessage(null)} > {message.text} )} {/* Connection Status */} Connection Status {connectionStatus === 'connected' && ( } size="small" /> )} {connectionStatus === 'error' && ( } size="small" /> )} {connectionStatus === 'unknown' && ( )} {/* Main Settings */} Mailgun Configuration handleChange('apiKey', e.target.value)} placeholder="key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" fullWidth InputProps={{ endAdornment: ( setShowApiKey(!showApiKey)} edge="end" > {showApiKey ? : } ) }} helperText="Your Mailgun API key" /> handleChange('domain', e.target.value)} placeholder="mg.yourdomain.com" fullWidth helperText="Your Mailgun domain" /> Region Email Settings handleChange('fromEmail', e.target.value)} placeholder="noreply@yourdomain.com" fullWidth helperText="Default sender email address" /> handleChange('fromName', e.target.value)} placeholder="Biblical Guide" fullWidth helperText="Default sender name" /> handleChange('replyToEmail', e.target.value)} placeholder="support@yourdomain.com" fullWidth helperText="Default reply-to address" /> handleChange('webhookUrl', e.target.value)} placeholder="https://yourdomain.com/api/webhooks/mailgun" fullWidth helperText="URL for Mailgun webhooks (tracking, bounces, etc.)" /> handleChange('isEnabled', e.target.checked)} /> } label="Enable Mailgun" /> handleChange('testMode', e.target.checked)} /> } label="Test Mode (emails won't actually be sent)" /> {/* Test Email */} Test Email setTestEmail(e.target.value)} placeholder="test@example.com" fullWidth /> {settings.testMode && ( Test mode is enabled. Emails will be logged but not actually sent. )} {settings.updatedAt && ( Last updated: {new Date(settings.updatedAt).toLocaleString()} )} ) }