import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm, Link } from '@inertiajs/react';
import { Save, Mail, ArrowLeft, Server, ShieldCheck, AtSign, Globe, History, Settings2, CheckCircle2, XCircle, Search, Cpu, Key, Layers } from 'lucide-react';
import { useState } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/Components/ui/select';

interface EmailLog {
    id: number;
    recipient: string;
    subject: string;
    mailable: string;
    status: 'sent' | 'failed';
    error: string | null;
    created_at: string;
}

interface Props {
    settings: {
        mail_driver: 'smtp' | 'api';
        mail_host: string;
        mail_port: number;
        mail_username: string;
        mail_password: string;
        mail_encryption: string;
        mail_api_key: string;
        mail_from_address: string;
        mail_from_name: string;
        booking_notification_email: string;
    };
    logs: {
        data: EmailLog[];
        links: any[];
    };
}

export default function EmailCenter({ settings, logs }: Props) {
    const [activeTab, setActiveTab] = useState<'logs' | 'settings'>('logs');
    
    const { data, setData, patch, processing, errors } = useForm({
        mail_driver: settings.mail_driver,
        mail_host: settings.mail_host,
        mail_port: settings.mail_port,
        mail_username: settings.mail_username,
        mail_password: settings.mail_password,
        mail_encryption: settings.mail_encryption,
        mail_api_key: settings.mail_api_key,
        mail_from_address: settings.mail_from_address,
        mail_from_name: settings.mail_from_name,
        booking_notification_email: settings.booking_notification_email,
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        patch(route('admin.settings.notifications.update'), {
            preserveScroll: true,
        });
    }

    return (
        <AdminLayout>
            <Head title="Email Center" />

            <div className="mb-8">
                <Link 
                    href={route('admin.settings.index')}
                    className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] hover:text-ink transition-colors mb-4"
                >
                    <ArrowLeft className="h-3 w-3" />
                    Back to Settings
                </Link>
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                            Email Center
                        </h1>
                        <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                            Monitor communication logs and manage your delivery infrastructure.
                        </p>
                    </div>

                    {/* Tabs */}
                    <div className="flex p-1 bg-[#F0EDE8] rounded-xl self-start">
                        <button 
                            onClick={() => setActiveTab('logs')}
                            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-[13px] font-semibold transition-all ${
                                activeTab === 'logs' ? 'bg-white text-ink shadow-sm' : 'text-[#8C92AC] hover:text-ink'
                            }`}
                        >
                            <History className="h-4 w-4" />
                            Email Logs
                        </button>
                        <button 
                            onClick={() => setActiveTab('settings')}
                            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-[13px] font-semibold transition-all ${
                                activeTab === 'settings' ? 'bg-white text-ink shadow-sm' : 'text-[#8C92AC] hover:text-ink'
                            }`}
                        >
                            <Settings2 className="h-4 w-4" />
                            Configuration
                        </button>
                    </div>
                </div>
            </div>

            {activeTab === 'logs' ? (
                <div className="space-y-4">
                    {/* Search/Filter Bar */}
                    <div className="bg-white rounded-xl border border-[#E8E6DF] p-4 flex flex-col sm:flex-row gap-4 items-center shadow-sm">
                        <div className="relative flex-1 w-full">
                            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-[#8C92AC]" />
                            <input 
                                type="text"
                                placeholder="Search by recipient or subject..."
                                className="w-full pl-10 pr-4 py-2 bg-[#FAFAF8] border border-[#F0EDE8] rounded-lg text-[13px] outline-none focus:border-accent"
                            />
                        </div>
                        <div className="flex gap-2 w-full sm:w-auto">
                            <div className="w-full sm:w-32">
                                <Select defaultValue="All Status">
                                    <SelectTrigger className="h-[38px] bg-[#FAFAF8] border-[#F0EDE8] rounded-lg text-[13px] text-ink font-medium focus:border-accent transition-colors">
                                        <SelectValue placeholder="All Status" />
                                    </SelectTrigger>
                                    <SelectContent className="bg-white border-[#F0EDE8] rounded-xl shadow-lg">
                                        <SelectItem value="All Status" className="text-[13px]">All Status</SelectItem>
                                        <SelectItem value="Sent" className="text-[13px]">Sent</SelectItem>
                                        <SelectItem value="Failed" className="text-[13px]">Failed</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                    </div>

                    {/* Logs Table */}
                    <div className="bg-white rounded-xl border border-[#E8E6DF] overflow-hidden shadow-sm">
                        <div className="overflow-x-auto custom-scrollbar">
                            <table className="w-full text-left border-collapse min-w-[800px]">
                                <thead>
                                    <tr className="bg-[#FAFAF8] border-b border-[#F0EDE8]">
                                        <th className="px-6 py-4 text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider">Recipient</th>
                                        <th className="px-6 py-4 text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider">Subject</th>
                                        <th className="px-6 py-4 text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider text-center">Status</th>
                                        <th className="px-6 py-4 text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider">Date & Time</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-[#F0EDE8]">
                                    {logs.data.map((log) => (
                                        <tr key={log.id} className="hover:bg-[#FAFAF8] transition-colors group">
                                            <td className="px-6 py-4">
                                                <div className="text-[13px] font-medium text-ink">{log.recipient}</div>
                                                <div className="text-[11px] text-[#8C92AC]">{log.mailable}</div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="text-[13px] text-ink line-clamp-1">{log.subject}</div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="flex justify-center">
                                                    {log.status === 'sent' ? (
                                                        <span className="flex items-center gap-1.5 px-2 py-1 bg-emerald-50 text-emerald-600 rounded-full text-[10px] font-bold uppercase tracking-wider">
                                                            <CheckCircle2 className="h-3 w-3" />
                                                            Sent
                                                        </span>
                                                    ) : (
                                                        <span className="flex items-center gap-1.5 px-2 py-1 bg-red-50 text-red-600 rounded-full text-[10px] font-bold uppercase tracking-wider">
                                                            <XCircle className="h-3 w-3" />
                                                            Failed
                                                        </span>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="text-[13px] text-ink">
                                                    {new Date(log.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                                                </div>
                                                <div className="text-[11px] text-[#8C92AC]">
                                                    {new Date(log.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                    {logs.data.length === 0 && (
                                        <tr>
                                            <td colSpan={4} className="px-6 py-12 text-center text-[13px] text-[#8C92AC] italic">
                                                No email logs found.
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            ) : (
                <form onSubmit={submit} className="max-w-4xl space-y-6 pb-20">
                    
                    {/* Delivery Method Selector */}
                    <div className="bg-white rounded-xl border border-[#E8E6DF] overflow-hidden shadow-sm">
                        <div className="px-6 py-4 border-b border-[#F0EDE8] bg-[#FAFAF8] flex items-center justify-between">
                            <h2 className="text-[14px] font-semibold text-ink flex items-center gap-2">
                                <Layers className="h-4 w-4 text-[#8C92AC]" />
                                Delivery Strategy
                            </h2>
                            <div className="flex p-1 bg-[#F0EDE8] rounded-lg">
                                <button 
                                    type="button"
                                    onClick={() => setData('mail_driver', 'api')}
                                    className={`relative px-4 py-1.5 rounded-md text-[12px] font-bold transition-all ${
                                        data.mail_driver === 'api' 
                                            ? 'bg-white text-ink shadow-sm' 
                                            : 'text-[#8C92AC] hover:text-ink'
                                    }`}
                                >
                                    Brevo API
                                    <span className="absolute -top-2 -right-2 px-1.5 py-0.5 bg-accent text-white text-[8px] rounded-full uppercase tracking-tighter">
                                        Rec
                                    </span>
                                </button>
                                <button 
                                    type="button"
                                    onClick={() => setData('mail_driver', 'smtp')}
                                    className={`px-4 py-1.5 rounded-md text-[12px] font-bold transition-all ${
                                        data.mail_driver === 'smtp' 
                                            ? 'bg-white text-ink shadow-sm' 
                                            : 'text-[#8C92AC] hover:text-ink'
                                    }`}
                                >
                                    Standard SMTP
                                </button>
                            </div>
                        </div>
                    </div>

                    {data.mail_driver === 'smtp' ? (
                        <div className="bg-white rounded-xl border border-[#E8E6DF] overflow-hidden shadow-sm animate-in fade-in slide-in-from-top-2">
                            <div className="px-6 py-4 border-b border-[#F0EDE8] bg-[#FAFAF8]">
                                <h2 className="text-[14px] font-semibold text-ink flex items-center gap-2">
                                    <Server className="h-4 w-4 text-[#8C92AC]" />
                                    SMTP Server Configuration
                                </h2>
                            </div>
                            <div className="p-6 space-y-6">
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                                    <div>
                                        <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            Outgoing Host
                                        </label>
                                        <input 
                                            type="text" 
                                            name="mail_host"
                                            id="mail_host"
                                            autoComplete="off"
                                            value={data.mail_host}
                                            onChange={e => setData('mail_host', e.target.value)}
                                            className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                            placeholder="e.g., mail.yourdomain.com"
                                        />
                                    </div>
                                    <div>
                                        <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            Port
                                        </label>
                                        <input 
                                            type="number" 
                                            name="mail_port"
                                            id="mail_port"
                                            autoComplete="off"
                                            value={data.mail_port}
                                            onChange={e => setData('mail_port', parseInt(e.target.value))}
                                            className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                            placeholder="465 (SSL) or 587 (TLS)"
                                        />
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                                    <div>
                                        <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            Encryption Protocol
                                        </label>
                                    <div className="w-full">
                                        <Select 
                                            value={data.mail_encryption} 
                                            onValueChange={(val) => setData('mail_encryption', val)}
                                        >
                                            <SelectTrigger className="w-full h-[41px] bg-white border-[#E8E6DF] rounded-lg text-[13px] font-medium text-ink focus:ring-2 focus:ring-accent/10 focus:border-accent transition-all">
                                                <SelectValue placeholder="Select Encryption" />
                                            </SelectTrigger>
                                            <SelectContent className="bg-white border-[#E8E6DF] rounded-xl shadow-xl">
                                                <SelectItem value="tls" className="text-[13px] focus:bg-[#F5F3EF] focus:text-ink">TLS (Modern / Port 587)</SelectItem>
                                                <SelectItem value="ssl" className="text-[13px] focus:bg-[#F5F3EF] focus:text-ink">SSL (Legacy / Port 465)</SelectItem>
                                                <SelectItem value="none" className="text-[13px] focus:bg-[#F5F3EF] focus:text-ink">None (Insecure)</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </div>
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                                    <div>
                                        <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            SMTP Username / Email
                                        </label>
                                        <div className="relative">
                                            <AtSign className="absolute left-3.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[#C0BDBA]" />
                                            <input 
                                                type="text" 
                                                name="mail_username"
                                                id="mail_username"
                                                autoComplete="off"
                                                value={data.mail_username}
                                                onChange={e => setData('mail_username', e.target.value)}
                                                className="w-full pl-10 pr-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                                placeholder="e.g., info@yourdomain.com"
                                            />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            SMTP Password
                                        </label>
                                        <div className="relative">
                                            <ShieldCheck className="absolute left-3.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[#C0BDBA]" />
                                            <input 
                                                type="password" 
                                                name="mail_password"
                                                id="mail_password"
                                                autoComplete="new-password"
                                                value={data.mail_password}
                                                onChange={e => setData('mail_password', e.target.value)}
                                                className="w-full pl-10 pr-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                                placeholder="••••••••••••"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div className="bg-white rounded-xl border border-[#E8E6DF] overflow-hidden shadow-sm animate-in fade-in slide-in-from-top-2">
                            <div className="px-6 py-4 border-b border-[#F0EDE8] bg-[#FAFAF8]">
                                <h2 className="text-[14px] font-semibold text-ink flex items-center gap-2">
                                    <Key className="h-4 w-4 text-[#8C92AC]" />
                                    Brevo API Authentication
                                </h2>
                            </div>
                            <div className="p-6">
                                <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                    Brevo API Key (v3)
                                </label>
                                <div className="relative">
                                    <ShieldCheck className="absolute left-3.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[#C0BDBA]" />
                                    <input 
                                        type="password" 
                                        name="mail_api_key"
                                        id="mail_api_key"
                                        autoComplete="off"
                                        value={data.mail_api_key}
                                        onChange={e => setData('mail_api_key', e.target.value)}
                                        className="w-full pl-10 pr-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                        placeholder="xkeysib-..."
                                    />
                                </div>
                                <p className="mt-3 text-[12px] text-[#8C92AC] leading-relaxed">
                                    Recommended for Brevo users. This bypasses SMTP port blocking issues. Find this in your Brevo Dashboard under <strong>SMTP & API</strong>.
                                </p>
                            </div>
                        </div>
                    )}

                    {/* Sender Identity Section */}
                    <div className="bg-white rounded-xl border border-[#E8E6DF] overflow-hidden shadow-sm">
                        <div className="px-6 py-4 border-b border-[#F0EDE8] bg-[#FAFAF8]">
                            <h2 className="text-[14px] font-semibold text-ink flex items-center gap-2">
                                <Globe className="h-4 w-4 text-[#8C92AC]" />
                                Sender Identity
                            </h2>
                        </div>
                        <div className="p-6 grid grid-cols-1 sm:grid-cols-2 gap-6">
                            <div>
                                <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                    "From" Email Address
                                </label>
                                <input 
                                    type="email" 
                                    name="mail_from_address"
                                    id="mail_from_address"
                                    autoComplete="off"
                                    value={data.mail_from_address}
                                    onChange={e => setData('mail_from_address', e.target.value)}
                                    className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                    placeholder="hello@altivatesolutions.com"
                                />
                            </div>
                            <div>
                                <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                    "From" Sender Name
                                </label>
                                <input 
                                    type="text" 
                                    name="mail_from_name"
                                    id="mail_from_name"
                                    autoComplete="off"
                                    value={data.mail_from_name}
                                    onChange={e => setData('mail_from_name', e.target.value)}
                                    className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                    placeholder="e.g., Altivate"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Administrative Alerts Section */}
                    <div className="bg-white rounded-xl border border-[#E8E6DF] overflow-hidden shadow-sm">
                        <div className="px-6 py-4 border-b border-[#F0EDE8] bg-[#FAFAF8]">
                            <h2 className="text-[14px] font-semibold text-ink flex items-center gap-2">
                                <Mail className="h-4 w-4 text-[#8C92AC]" />
                                Administrative Alerts
                            </h2>
                        </div>
                        <div className="p-6">
                            <label className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                Notification Recipient
                            </label>
                            <input 
                                type="email" 
                                name="booking_notification_email"
                                id="booking_notification_email"
                                autoComplete="off"
                                value={data.booking_notification_email}
                                onChange={e => setData('booking_notification_email', e.target.value)}
                                className="w-full max-w-md px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-accent/10 focus:border-accent"
                                placeholder="admin@altivatesolutions.com"
                            />
                        </div>
                    </div>

                    {/* Test Email Section */}
                    <div className="bg-amber-50/50 rounded-xl border border-amber-200/60 overflow-hidden shadow-sm">
                        <div className="px-6 py-4 border-b border-amber-200/60 bg-amber-100/20">
                            <h2 className="text-[13px] font-bold text-amber-800 flex items-center gap-2 uppercase tracking-widest">
                                <CheckCircle2 className="h-4 w-4" />
                                Infrastructure Test
                            </h2>
                        </div>
                        <div className="p-6">
                            <div className="flex flex-col sm:flex-row gap-3">
                                <input 
                                    id="test_email_input"
                                    name="test_email_input"
                                    type="email" 
                                    autoComplete="off"
                                    placeholder="Enter recipient email..."
                                    className="flex-1 px-4 py-2.5 bg-white border border-amber-200 rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-amber-500/20"
                                />
                                <button 
                                    type="button"
                                    onClick={() => {
                                        const email = (document.getElementById('test_email_input') as HTMLInputElement).value;
                                        if (email) {
                                            const testForm = {
                                                email: email
                                            };
                                            // Using Inertia directly for the test to avoid interfering with the main form state
                                            import('@inertiajs/react').then(({ router }) => {
                                                router.post(route('admin.settings.email-center.test'), testForm, {
                                                    preserveScroll: true,
                                                    onSuccess: () => {
                                                        (document.getElementById('test_email_input') as HTMLInputElement).value = '';
                                                    }
                                                });
                                            });
                                        }
                                    }}
                                    className="px-6 py-2.5 bg-amber-600 text-white rounded-lg text-[13px] font-bold hover:bg-amber-700 transition-colors shadow-sm active:scale-95"
                                >
                                    Send Test Email
                                </button>
                            </div>
                            <p className="mt-2.5 text-[11px] text-amber-700/80">
                                Verify your {data.mail_driver === 'api' ? 'API' : 'SMTP'} connection by sending a branded test message to any address.
                            </p>
                        </div>
                    </div>

                    {/* Save Button */}
                    <div className="flex justify-end pt-4">
                        <button 
                            type="submit" 
                            disabled={processing}
                            className="px-8 py-3 bg-ink text-white rounded-xl text-[14px] font-semibold flex items-center gap-2 hover:bg-primary transition-all shadow-sm active:scale-95 disabled:opacity-50"
                        >
                            <Save className="h-4 w-4" />
                            {processing ? 'Saving Changes...' : 'Save Configuration'}
                        </button>
                    </div>
                </form>
            )}
        </AdminLayout>
    );
}
