import { useEffect, useState } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Button } from '@/Components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Separator } from '@/Components/ui/separator'; 
import { Send } from 'lucide-react'; 

export default function SmtpSettings() {
    const [loading, setLoading] = useState(false);
    const [testLoading, setTestLoading] = useState(false); 
    const [testEmail, setTestEmail] = useState(''); 

    const [formData, setFormData] = useState({
        smtp_host: '',
        smtp_port: '',
        smtp_username: '',
        smtp_password: '',
        smtp_encryption: 'tls',
        smtp_from_address: '',
        smtp_from_name: '',
    });

    useEffect(() => {
        axios.get('/api/admin/settings/smtp')
            .then(response => {
                if(response.data.smtp_host !== undefined) {
                    setFormData(prev => ({ ...prev, ...response.data }));
                }
            })
            .catch(error => {
                console.error(error);
                toast.error("Failed to load settings.");
            });
    }, []);

    const handleChange = (e) => {
        setFormData({ ...formData, [e.target.id]: e.target.value });
    };

    const handleSelectChange = (value) => {
        setFormData({ ...formData, smtp_encryption: value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const res = await axios.post('/api/admin/settings/smtp', formData);
            // Use backend message if available
            toast.success(res.data.message || "SMTP Settings Saved");
        } catch (error) {
            console.error(error);
            toast.error("Failed to save configuration.");
        } finally {
            setLoading(false);
        }
    };

    // --- Test Email Handler ---
    const handleTestEmail = async (e) => {
        e.preventDefault();
        if (!testEmail) {
            toast.error("Please enter an email address.");
            return;
        }

        setTestLoading(true);
        try {
            // First save settings to ensure we test the latest data
            await axios.post('/api/admin/settings/smtp', formData);
            
            // Then send test
            await axios.post('/api/admin/settings/smtp/test', { email: testEmail });
            
            toast.success("Test Email Sent!", {
                description: `Check the inbox for ${testEmail}`
            });
        } catch (error) {
            console.error(error);
            // Show the actual SMTP error message for debugging
            toast.error("SMTP Connection Failed", {
                description: error.response?.data?.message || "Check your credentials.",
                duration: 8000, // Show longer for debugging
            });
        } finally {
            setTestLoading(false);
        }
    };

    return (
        <div className="space-y-6">
            <Head title="SMTP Settings" />
            
            {/* Configuration Card */}
            <Card>
                <CardHeader>
                    <CardTitle>SMTP Configuration</CardTitle>
                    <CardDescription>Configure how the system sends emails.</CardDescription>
                </CardHeader>
                <CardContent>
                    <form id="smtp-form" onSubmit={handleSubmit} className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="smtp_host">Host</Label>
                                <Input id="smtp_host" value={formData.smtp_host} onChange={handleChange} placeholder="smtp.gmail.com" />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="smtp_port">Port</Label>
                                <Input id="smtp_port" value={formData.smtp_port} onChange={handleChange} placeholder="587" />
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="smtp_username">Username</Label>
                                <Input id="smtp_username" value={formData.smtp_username} onChange={handleChange} />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="smtp_password">Password</Label>
                                <Input id="smtp_password" type="password" value={formData.smtp_password} onChange={handleChange} placeholder="****" />
                            </div>
                        </div>
                        
                        <div className="space-y-2">
                            <Label>Encryption</Label>
                            <Select onValueChange={handleSelectChange} value={formData.smtp_encryption}>
                                <SelectTrigger>
                                    <SelectValue placeholder="Select encryption" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="tls">TLS</SelectItem>
                                    <SelectItem value="ssl">SSL</SelectItem>
                                    <SelectItem value="null">None</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="smtp_from_address">From Address</Label>
                                <Input id="smtp_from_address" value={formData.smtp_from_address} onChange={handleChange} placeholder="no-reply@domain.com" />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="smtp_from_name">From Name</Label>
                                <Input id="smtp_from_name" value={formData.smtp_from_name} onChange={handleChange} placeholder="My App Name" />
                            </div>
                        </div>
                    </form>
                </CardContent>
                <CardFooter>
                     <Button type="submit" form="smtp-form" disabled={loading}>
                        {loading ? 'Saving...' : 'Save Configuration'}
                    </Button>
                </CardFooter>
            </Card>

            {/* Test Connection Card */}
            <Card>
                <CardHeader>
                    <CardTitle>Test Connection</CardTitle>
                    <CardDescription>
                        Send a test email to verify your settings are correct.
                    </CardDescription>
                </CardHeader>
                <CardContent className="flex gap-4 items-end">
                    <div className="flex-1 space-y-2">
                        <Label htmlFor="test_email">Target Email</Label>
                        <Input 
                            id="test_email" 
                            placeholder="your.email@example.com" 
                            value={testEmail}
                            onChange={(e) => setTestEmail(e.target.value)}
                        />
                    </div>
                    <Button variant="secondary" onClick={handleTestEmail} disabled={testLoading || loading}>
                        <Send className="w-4 h-4 mr-2" />
                        {testLoading ? 'Sending...' : 'Send Test Email'}
                    </Button>
                </CardContent>
            </Card>
        </div>
    );
}

SmtpSettings.layout = (page) => (
    <AdminLayout>
        <SettingsLayout children={page} />
    </AdminLayout>
);