import React, { useState } from 'react';
import { Head, useForm } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/cp/Layouts/AdminLayout';
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 { Mail, Send, Server, Loader2, KeyRound, ShieldAlert } from 'lucide-react'; 

export default function Smtp({ smtpSettings }) {
    const [testLoading, setTestLoading] = useState(false); 
    const [testEmail, setTestEmail] = useState(''); 

    const { data, setData, post, processing, errors } = useForm({
        smtp_host: smtpSettings?.smtp_host || '',
        smtp_port: smtpSettings?.smtp_port || '',
        smtp_username: smtpSettings?.smtp_username || '',
        smtp_password: smtpSettings?.smtp_password || '',
        smtp_encryption: smtpSettings?.smtp_encryption || 'tls',
        smtp_from_address: smtpSettings?.smtp_from_address || '',
        smtp_from_name: smtpSettings?.smtp_from_name || '',
    });

    const handleSubmit = (e) => {
        e.preventDefault();
        post(route('cp.settings.smtp.update'), {
            preserveScroll: true,
            onSuccess: () => toast.success("SMTP Configuration saved and .env updated successfully!"),
            onError: () => toast.error("Failed to save configuration. Check inputs.")
        });
    };

    // --- Test Email Handler (Uses Axios to catch raw SMTP exceptions cleanly) ---
    const handleTestEmail = async (e) => {
        e.preventDefault();
        if (!testEmail) {
            return toast.error("Please enter a destination email address.");
        }

        setTestLoading(true);
        toast.info("Attempting to send email... Please wait.", { duration: 5000 });

        try {
            // We test against the server using Axios
            const res = await axios.post(route('cp.settings.smtp.test'), { email: testEmail });
            toast.success("Success!", { description: res.data.message });
            setTestEmail(''); // clear input on success
        } catch (error) {
            console.error(error);
            // Display the exact SMTP error from Laravel for easy debugging
            toast.error("SMTP Connection Failed", {
                description: error.response?.data?.message || "Check your credentials.",
                duration: 8000, 
            });
        } finally {
            setTestLoading(false);
        }
    };

    return (
        <AdminLayout>
            <Head title="SMTP & Email Settings" />

            <div className="max-w-4xl mx-auto space-y-6">
                <div className="flex items-center gap-3 mb-6">
                    <Mail className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">SMTP & Mail Server</h2>
                        <p className="text-muted-foreground">Configure the mailer so your system can send password resets and order notifications.</p>
                    </div>
                </div>

                <div className="grid grid-cols-1 gap-6">
                    
                    {/* Configuration Card */}
                    <Card className="border-border/50 shadow-sm">
                        <form onSubmit={handleSubmit}>
                            <CardHeader className="bg-muted/10 border-b pb-4">
                                <CardTitle className="flex items-center gap-2">
                                    <Server className="w-5 h-5 text-primary" /> Server Details
                                </CardTitle>
                                <CardDescription>These settings will automatically write to your application's .env file.</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-6 pt-6">
                                
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="space-y-2">
                                        <Label htmlFor="smtp_host">SMTP Host <span className="text-red-500">*</span></Label>
                                        <Input id="smtp_host" value={data.smtp_host} onChange={e => setData('smtp_host', e.target.value)} placeholder="smtp.mailtrap.io" className={errors.smtp_host ? "border-destructive" : ""} />
                                        {errors.smtp_host && <p className="text-xs text-destructive">{errors.smtp_host}</p>}
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="smtp_port">SMTP Port <span className="text-red-500">*</span></Label>
                                        <Input id="smtp_port" value={data.smtp_port} onChange={e => setData('smtp_port', e.target.value)} placeholder="2525" className={errors.smtp_port ? "border-destructive" : ""} />
                                        {errors.smtp_port && <p className="text-xs text-destructive">{errors.smtp_port}</p>}
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-4 border rounded-xl bg-muted/20">
                                    <div className="space-y-2">
                                        <Label htmlFor="smtp_username" className="flex items-center gap-2"><KeyRound className="w-4 h-4 text-muted-foreground"/> Username</Label>
                                        <Input id="smtp_username" value={data.smtp_username} onChange={e => setData('smtp_username', e.target.value)} placeholder="api_key_or_username" className="bg-background" />
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="smtp_password" className="flex items-center gap-2"><ShieldAlert className="w-4 h-4 text-muted-foreground"/> Password</Label>
                                        <Input id="smtp_password" type="password" value={data.smtp_password} onChange={e => setData('smtp_password', e.target.value)} placeholder="••••••••" className="bg-background" />
                                    </div>
                                </div>
                                
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                    <div className="space-y-2">
                                        <Label>Encryption</Label>
                                        <Select onValueChange={v => setData('smtp_encryption', v)} value={data.smtp_encryption}>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Select encryption" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="tls">TLS (Recommended)</SelectItem>
                                                <SelectItem value="ssl">SSL</SelectItem>
                                                <SelectItem value="null">None</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="smtp_from_address">Sender Email <span className="text-red-500">*</span></Label>
                                        <Input id="smtp_from_address" value={data.smtp_from_address} onChange={e => setData('smtp_from_address', e.target.value)} placeholder="noreply@yourdomain.com" />
                                        {errors.smtp_from_address && <p className="text-xs text-destructive">{errors.smtp_from_address}</p>}
                                    </div>
                                    <div className="space-y-2">
                                        <Label htmlFor="smtp_from_name">Sender Name <span className="text-red-500">*</span></Label>
                                        <Input id="smtp_from_name" value={data.smtp_from_name} onChange={e => setData('smtp_from_name', e.target.value)} placeholder="My Marketplace" />
                                        {errors.smtp_from_name && <p className="text-xs text-destructive">{errors.smtp_from_name}</p>}
                                    </div>
                                </div>
                            </CardContent>
                            <CardFooter className="bg-muted/10 border-t py-4 justify-end">
                                <Button type="submit" disabled={processing} className="w-full sm:w-auto">
                                    {processing ? <Loader2 className="animate-spin w-4 h-4 mr-2" /> : null}
                                    {processing ? 'Saving...' : 'Save Configuration'}
                                </Button>
                            </CardFooter>
                        </form>
                    </Card>

                    {/* Test Connection Card */}
                    <Card className="border-blue-500/20 shadow-sm bg-blue-500/5">
                        <CardHeader>
                            <CardTitle className="text-blue-700 dark:text-blue-500 flex items-center gap-2">
                                <Send className="w-5 h-5" /> Test Connection
                            </CardTitle>
                            <CardDescription>
                                Verify your settings are correct before relying on them. (Ensure you save settings first).
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="flex flex-col sm:flex-row gap-4 items-end">
                            <div className="flex-1 w-full space-y-2">
                                <Label htmlFor="test_email" className="text-blue-900 dark:text-blue-400">Target Email Address</Label>
                                <Input 
                                    id="test_email" 
                                    placeholder="Enter your personal email to test..." 
                                    value={testEmail}
                                    onChange={(e) => setTestEmail(e.target.value)}
                                    className="bg-background"
                                />
                            </div>
                            <Button 
                                variant="default" 
                                onClick={handleTestEmail} 
                                disabled={testLoading || processing}
                                className="w-full sm:w-auto bg-blue-600 hover:bg-blue-700 text-white gap-2"
                            >
                                {testLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                                {testLoading ? 'Testing...' : 'Send Test Email'}
                            </Button>
                        </CardContent>
                    </Card>

                </div>
            </div>
        </AdminLayout>
    );
}