'use client';

import { useState, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import AppLayout from '@/src/components/layout/AppLayout';
import {
    Mail,
    Send,
    FileText,
    History,
    Settings,
    TestTube,
    Users,
    Clock,
    CheckCircle,
    AlertCircle,
    Loader2,
    XCircle,
    Eye
} from 'lucide-react';

import { Search } from 'lucide-react';

interface OverdueCustomer {
    id: string;
    name: string;
    email: string;
    domain: string;
    amount: number;
    daysOverdue: number;
}

function SendEmailContent() {
    const [selectedTemplate, setSelectedTemplate] = useState<string>('');
    const [selectedRecipients, setSelectedRecipients] = useState<string[]>([]);
    const [isSending, setIsSending] = useState(false);
    const [sendProgress, setSendProgress] = useState(0);
    const [showPreview, setShowPreview] = useState(false);
    const [overdueCustomers, setOverdueCustomers] = useState<OverdueCustomer[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [searchQuery, setSearchQuery] = useState('');

    // טעינת לקוחות בפיגור מה-DB
    useEffect(() => {
        const fetchOverdueCustomers = async () => {
            try {
                setIsLoading(true);
                const response = await fetch('/api/phones');

                if (!response.ok) {
                    throw new Error('Failed to fetch phones');
                }

                const data = await response.json();

                // בדיקה שיש נתונים
                const phonesArray = Array.isArray(data) ? data : (data.phones || []);

                if (!Array.isArray(phonesArray) || phonesArray.length === 0) {
                    console.warn('No phones data received');
                    setOverdueCustomers([]);
                    return;
                }

                // סינון לקוחות בפיגור בלבד
                const today = new Date();
                const overdue = phonesArray
                    .filter((phone: any) => {
                        if (!phone || !phone.nextPayment) return false;

                        const nextPayment = new Date(phone.nextPayment);
                        const isOverdue = nextPayment < today;
                        const notPaid = !['paid', 'free', 'delete_backup', 'delete_no_backup'].includes(phone.status);
                        return isOverdue && notPaid;
                    })
                    .map((phone: any) => {
                        const nextPayment = new Date(phone.nextPayment);
                        const daysOverdue = Math.floor((today.getTime() - nextPayment.getTime()) / (1000 * 60 * 60 * 24));

                        return {
                            id: phone.id.toString(),
                            name: phone.owner || 'ללא שם',
                            email: phone.email || `${(phone.owner || 'customer').toLowerCase().replace(/\s+/g, '')}@example.com`,
                            domain: phone.domain || 'ללא דומיין',
                            amount: parseFloat(phone.amount) || 0,
                            daysOverdue: daysOverdue
                        };
                    });

                setOverdueCustomers(overdue);
            } catch (error) {
                console.error('Error fetching overdue customers:', error);
                setOverdueCustomers([]);
            } finally {
                setIsLoading(false);
            }
        };

        fetchOverdueCustomers();
    }, []);

    const templates = [
        { id: '1', name: 'תזכורת תשלום סטנדרטית', subject: 'תזכורת תשלום אחסון עבור {domain}' },
        { id: '2', name: 'הודעת איחור תשלום', subject: 'הודעה דחופה - איחור בתשלום אחסון' },
        { id: '3', name: 'תודה על התשלום', subject: 'אישור קבלת תשלום אחסון' },
    ];

    // סינון לקוחות לפי חיפוש
    const filteredCustomers = overdueCustomers.filter(customer =>
        customer.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        customer.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
        customer.domain.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const handleSelectAll = () => {
        if (selectedRecipients.length === filteredCustomers.length && filteredCustomers.length > 0) {
            setSelectedRecipients([]);
        } else {
            setSelectedRecipients(filteredCustomers.map(c => c.id));
        }
    };

    const handleSendEmails = async () => {
        if (!selectedTemplate || selectedRecipients.length === 0) {
            alert('אנא בחר תבנית ונמענים');
            return;
        }

        setIsSending(true);
        setSendProgress(0);

        // סימולציה של שליחה
        for (let i = 0; i < selectedRecipients.length; i++) {
            await new Promise(resolve => setTimeout(resolve, 1000));
            setSendProgress(((i + 1) / selectedRecipients.length) * 100);
        }

        alert(`נשלחו ${selectedRecipients.length} אימיילים בהצלחה!`);
        setIsSending(false);
        setSendProgress(0);
        setSelectedRecipients([]);
    };

    return (
        <div className="space-y-6">
            {/* Template Selection */}
            <Card className="p-6">
                <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                    <FileText className="w-5 h-5 text-blue-600" />
                    בחר תבנית אימייל
                </h3>
                <select
                    value={selectedTemplate}
                    onChange={(e) => setSelectedTemplate(e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                    <option value="">-- בחר תבנית --</option>
                    {templates.map(template => (
                        <option key={template.id} value={template.id}>
                            {template.name} - {template.subject}
                        </option>
                    ))}
                </select>
            </Card>

            {/* Recipients Selection */}
            <Card className="p-6">
                <div className="flex justify-between items-center mb-4">
                    <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                        <Users className="w-5 h-5 text-blue-600" />
                        בחר נמענים ({selectedRecipients.length} נבחרו)
                    </h3>
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={handleSelectAll}
                        disabled={isLoading || filteredCustomers.length === 0}
                    >
                        {selectedRecipients.length === filteredCustomers.length && filteredCustomers.length > 0 ? 'בטל בחירה' : 'בחר הכל'}
                    </Button>
                </div>

                {/* Search Field */}
                <div className="relative mb-4">
                    <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                        type="text"
                        placeholder="חפש לפי שם, מייל או דומיין..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pr-10 p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    />
                </div>

                {isLoading ? (
                    <div className="flex items-center justify-center py-8">
                        <Loader2 className="w-8 h-8 animate-spin text-blue-600" />
                        <span className="mr-3 text-gray-600">טוען לקוחות בפיגור...</span>
                    </div>
                ) : filteredCustomers.length === 0 ? (
                    <div className="text-center py-8">
                        <Users className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                        <p className="text-gray-600 text-lg">
                            {searchQuery ? 'לא נמצאו לקוחות התואמים לחיפוש' : 'אין לקוחות בפיגור כרגע'}
                        </p>
                        {!searchQuery && (
                            <p className="text-gray-500 text-sm mt-2">כל הלקוחות עדכניים בתשלומים! 🎉</p>
                        )}
                    </div>
                ) : (
                    <div className="space-y-2">
                        {filteredCustomers.map(customer => (
                            <label
                                key={customer.id}
                                className="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer"
                            >
                                <input
                                    type="checkbox"
                                    checked={selectedRecipients.includes(customer.id)}
                                    onChange={(e) => {
                                        if (e.target.checked) {
                                            setSelectedRecipients([...selectedRecipients, customer.id]);
                                        } else {
                                            setSelectedRecipients(selectedRecipients.filter(id => id !== customer.id));
                                        }
                                    }}
                                    className="ml-4 h-5 w-5 text-blue-600 rounded focus:ring-blue-500"
                                />
                                <div className="flex-1">
                                    <div className="flex justify-between items-center">
                                        <div>
                                            <p className="font-semibold text-gray-900">{customer.name}</p>
                                            <p className="text-sm text-gray-600">{customer.email}</p>
                                        </div>
                                        <div className="text-left">
                                            <p className="text-sm font-medium text-red-600">₪{customer.amount}</p>
                                            <p className="text-xs text-gray-500">איחור: {customer.daysOverdue} ימים</p>
                                        </div>
                                    </div>
                                </div>
                            </label>
                        ))}
                    </div>
                )}
            </Card>

            {/* Preview & Send */}
            {selectedTemplate && selectedRecipients.length > 0 && (
                <Card className="p-6">
                    <div className="flex justify-between items-center mb-4">
                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                            <Eye className="w-5 h-5 text-blue-600" />
                            סיכום שליחה
                        </h3>
                        <div className="flex gap-3">
                            <Button
                                variant="outline"
                                onClick={() => setShowPreview(!showPreview)}
                            >
                                {showPreview ? 'הסתר תצוגה מקדימה' : 'הצג תצוגה מקדימה'}
                            </Button>
                            <Button
                                onClick={handleSendEmails}
                                disabled={isSending}
                                className="bg-green-600 hover:bg-green-700"
                            >
                                {isSending ? (
                                    <>
                                        <Loader2 className="w-4 h-4 ml-2 animate-spin" />
                                        שולח...
                                    </>
                                ) : (
                                    <>
                                        <Send className="w-4 h-4 ml-2" />
                                        שלח {selectedRecipients.length} אימיילים
                                    </>
                                )}
                            </Button>
                        </div>
                    </div>

                    {isSending && (
                        <div className="mb-4">
                            <div className="flex justify-between text-sm text-gray-600 mb-2">
                                <span>מתקדם...</span>
                                <span>{Math.round(sendProgress)}%</span>
                            </div>
                            <div className="w-full bg-gray-200 rounded-full h-3">
                                <div
                                    className="bg-green-600 h-3 rounded-full transition-all duration-300"
                                    style={{ width: `${sendProgress}%` }}
                                />
                            </div>
                        </div>
                    )}

                    {showPreview && (
                        <div className="mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <h4 className="font-semibold text-gray-900 mb-2">תצוגה מקדימה:</h4>
                            <div className="text-sm text-gray-700">
                                <p><strong>תבנית:</strong> {templates.find(t => t.id === selectedTemplate)?.name}</p>
                                <p><strong>נמענים:</strong> {selectedRecipients.length} לקוחות</p>
                                <p><strong>דוגמה לנושא:</strong> תזכורת תשלום עבור example.com</p>
                            </div>
                        </div>
                    )}
                </Card>
            )}
        </div>
    );
}

function TestSMTPContent() {
    const [isTesting, setIsTesting] = useState(false);
    const [testResult, setTestResult] = useState<{
        success: boolean;
        message?: string;
        error?: string;
    } | null>(null);

    const testConnection = async () => {
        setIsTesting(true);
        setTestResult(null);

        try {
            const response = await fetch('/api/emails/send');
            const result = await response.json();

            setTestResult(result);
        } catch (error) {
            setTestResult({
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error'
            });
        } finally {
            setIsTesting(false);
        }
    };

    return (
        <Card className="p-8">
            <div className="text-center">
                <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
                    <TestTube className="w-8 h-8 text-blue-600" />
                </div>

                <h3 className="text-2xl font-semibold text-gray-900 mb-4">
                    בדיקת חיבור SMTP
                </h3>

                <p className="text-gray-600 mb-8 max-w-2xl mx-auto">
                    לחץ על הכפתור למטה כדי לבדוק את חיבור ה-SMTP שלך.
                    הבדיקה תאמת שהגדרות השרת שלך נכונות ושאתה יכול לשלוח אימיילים.
                </p>

                <Button
                    onClick={testConnection}
                    disabled={isTesting}
                    className="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 text-lg"
                >
                    {isTesting ? (
                        <>
                            <Loader2 className="w-5 h-5 ml-2 animate-spin" />
                            בודק חיבור...
                        </>
                    ) : (
                        <>
                            <TestTube className="w-5 h-5 ml-2" />
                            בדוק חיבור SMTP
                        </>
                    )}
                </Button>

                {/* Test Result */}
                {testResult && (
                    <div className="mt-8">
                        <Card className={`p-6 ${testResult.success ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
                            <div className="flex items-center justify-center mb-4">
                                {testResult.success ? (
                                    <CheckCircle className="w-8 h-8 text-green-600" />
                                ) : (
                                    <XCircle className="w-8 h-8 text-red-600" />
                                )}
                            </div>

                            <h4 className={`text-xl font-semibold mb-2 ${testResult.success ? 'text-green-800' : 'text-red-800'}`}>
                                {testResult.success ? 'החיבור הצליח!' : 'החיבור נכשל'}
                            </h4>

                            <p className={`text-lg ${testResult.success ? 'text-green-700' : 'text-red-700'}`}>
                                {testResult.success ? testResult.message : testResult.error}
                            </p>
                        </Card>
                    </div>
                )}

                {/* Configuration Help */}
                <div className="mt-12 text-right">
                    <h4 className="text-lg font-semibold text-gray-900 mb-4">הגדרות SMTP נדרשות</h4>
                    <div className="bg-gray-100 rounded-lg p-6 text-sm">
                        <p className="text-gray-700 mb-2">
                            כדי לבדוק את החיבור, וודא שהגדרת את המשתנים הבאים בקובץ .env.local:
                        </p>
                        <div className="bg-gray-800 text-green-400 p-4 rounded mt-4 font-mono text-xs">
                            <div>SMTP_HOST=mail.yourdomain.com</div>
                            <div>SMTP_PORT=465</div>
                            <div>SMTP_SECURE=true</div>
                            <div>SMTP_USER=noreply@yourdomain.com</div>
                            <div>SMTP_PASSWORD=your_password_here</div>
                            <div>SMTP_FROM_NAME=Your Company Name</div>
                            <div>SMTP_FROM_EMAIL=noreply@yourdomain.com</div>
                        </div>
                    </div>
                </div>
            </div>
        </Card>
    );
}

export default function EmailsPage() {
    const [activeTab, setActiveTab] = useState('overview');

    const emailStats = {
        totalSent: 1247,
        pending: 23,
        delivered: 1156,
        failed: 68,
        openRate: 68.5,
        clickRate: 12.3
    };

    const recentTemplates = [
        { id: 1, name: 'תזכורת תשלום סטנדרטית', lastUsed: '2025-01-15', status: 'active' },
        { id: 2, name: 'הודעת איחור תשלום', lastUsed: '2025-01-14', status: 'active' },
        { id: 3, name: 'תודה על התשלום', lastUsed: '2025-01-13', status: 'active' },
    ];

    const recentEmails = [
        { id: 1, recipient: 'info@example.com', subject: 'תזכורת תשלום', status: 'sent', sentAt: '2025-01-15 10:30' },
        { id: 2, recipient: 'sales@company.co.il', subject: 'הודעת איחור', status: 'delivered', sentAt: '2025-01-15 09:15' },
        { id: 3, recipient: 'admin@domain.com', subject: 'תודה על התשלום', status: 'opened', sentAt: '2025-01-14 16:45' },
    ];

    const tabs = [
        { id: 'overview', label: 'סקירה כללית', icon: Mail },
        { id: 'templates', label: 'תבניות', icon: FileText },
        { id: 'send', label: 'שליחה', icon: Send },
        { id: 'history', label: 'היסטוריה', icon: History },
        { id: 'settings', label: 'הגדרות', icon: Settings },
        { id: 'test', label: 'בדיקת חיבור', icon: TestTube },
    ];

    return (
        <AppLayout>
            <div className="max-w-7xl mx-auto">
                {/* Header */}
                <div className="mb-8">
                    <h1 className="text-3xl font-bold text-gray-900 mb-2">מערכת ניהול מיילים</h1>
                    <p className="text-gray-600">שליחת תזכורות תשלום וניהול תבניות אימייל</p>
                </div>

                {/* Tabs */}
                <div className="mb-8">
                    <div className="border-b border-gray-200">
                        <nav className="-mb-px flex space-x-8 space-x-reverse">
                            {tabs.map((tab) => (
                                <button
                                    key={tab.id}
                                    onClick={() => setActiveTab(tab.id)}
                                    className={`py-2 px-1 border-b-2 font-medium text-sm flex items-center gap-2 ${activeTab === tab.id
                                        ? 'border-blue-500 text-blue-600'
                                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                                        }`}
                                >
                                    <tab.icon className="w-4 h-4" />
                                    {tab.label}
                                </button>
                            ))}
                        </nav>
                    </div>
                </div>

                {/* Content based on active tab */}
                {activeTab === 'overview' && (
                    <div className="space-y-6">
                        {/* Stats Cards */}
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                            <Card className="p-6">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-600">סה"כ נשלחו</p>
                                        <p className="text-2xl font-bold text-gray-900">{emailStats.totalSent.toLocaleString()}</p>
                                    </div>
                                    <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                                        <Mail className="w-6 h-6 text-blue-600" />
                                    </div>
                                </div>
                            </Card>

                            <Card className="p-6">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-600">ממתינים</p>
                                        <p className="text-2xl font-bold text-yellow-600">{emailStats.pending}</p>
                                    </div>
                                    <div className="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center">
                                        <Clock className="w-6 h-6 text-yellow-600" />
                                    </div>
                                </div>
                            </Card>

                            <Card className="p-6">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-600">נמסרו</p>
                                        <p className="text-2xl font-bold text-green-600">{emailStats.delivered}</p>
                                    </div>
                                    <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                                        <CheckCircle className="w-6 h-6 text-green-600" />
                                    </div>
                                </div>
                            </Card>

                            <Card className="p-6">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-600">נכשלו</p>
                                        <p className="text-2xl font-bold text-red-600">{emailStats.failed}</p>
                                    </div>
                                    <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                                        <AlertCircle className="w-6 h-6 text-red-600" />
                                    </div>
                                </div>
                            </Card>
                        </div>

                        {/* Performance Metrics */}
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <Card className="p-6">
                                <h3 className="text-lg font-semibold text-gray-900 mb-4">ביצועים</h3>
                                <div className="space-y-4">
                                    <div className="flex justify-between items-center">
                                        <span className="text-sm text-gray-600">שיעור פתיחה</span>
                                        <span className="text-lg font-semibold text-green-600">{emailStats.openRate}%</span>
                                    </div>
                                    <div className="flex justify-between items-center">
                                        <span className="text-sm text-gray-600">שיעור לחיצה</span>
                                        <span className="text-lg font-semibold text-blue-600">{emailStats.clickRate}%</span>
                                    </div>
                                </div>
                            </Card>

                            <Card className="p-6">
                                <h3 className="text-lg font-semibold text-gray-900 mb-4">תבניות אחרונות</h3>
                                <div className="space-y-3">
                                    {recentTemplates.map((template) => (
                                        <div key={template.id} className="flex justify-between items-center py-2 border-b border-gray-100 last:border-b-0">
                                            <div>
                                                <p className="text-sm font-medium text-gray-900">{template.name}</p>
                                                <p className="text-xs text-gray-500">שימוש אחרון: {template.lastUsed}</p>
                                            </div>
                                            <span className="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
                                                פעיל
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            </Card>
                        </div>

                        {/* Recent Emails */}
                        <Card className="p-6">
                            <h3 className="text-lg font-semibold text-gray-900 mb-4">אימיילים אחרונים</h3>
                            <div className="overflow-x-auto">
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">נמען</th>
                                            <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">נושא</th>
                                            <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">סטטוס</th>
                                            <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">נשלח ב</th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {recentEmails.map((email) => (
                                            <tr key={email.id}>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{email.recipient}</td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{email.subject}</td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    <span className={`px-2 py-1 text-xs rounded-full ${email.status === 'sent' ? 'bg-blue-100 text-blue-800' :
                                                        email.status === 'delivered' ? 'bg-green-100 text-green-800' :
                                                            email.status === 'opened' ? 'bg-purple-100 text-purple-800' :
                                                                'bg-gray-100 text-gray-800'
                                                        }`}>
                                                        {email.status === 'sent' ? 'נשלח' :
                                                            email.status === 'delivered' ? 'נמסר' :
                                                                email.status === 'opened' ? 'נפתח' : email.status}
                                                    </span>
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{email.sentAt}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </Card>
                    </div>
                )}

                {activeTab === 'templates' && (
                    <Card className="p-6">
                        <div className="flex justify-between items-center mb-6">
                            <h3 className="text-lg font-semibold text-gray-900">ניהול תבניות</h3>
                            <Button
                                onClick={() => window.location.href = '/emails/templates'}
                                className="bg-blue-600 hover:bg-blue-700"
                            >
                                <FileText className="w-4 h-4 ml-2" />
                                נהל תבניות
                            </Button>
                        </div>
                        <p className="text-gray-600">כאן תוכל לנהל את תבניות האימייל שלך</p>
                    </Card>
                )}

                {activeTab === 'send' && (
                    <SendEmailContent />
                )}

                {activeTab === 'history' && (
                    <Card className="p-6">
                        <h3 className="text-lg font-semibold text-gray-900 mb-6">היסטוריית שליחות</h3>
                        <p className="text-gray-600">כאן תוכל לראות את כל האימיילים שנשלחו</p>
                    </Card>
                )}

                {activeTab === 'settings' && (
                    <Card className="p-6">
                        <div className="text-center">
                            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
                                <Settings className="w-8 h-8 text-blue-600" />
                            </div>

                            <h3 className="text-2xl font-semibold text-gray-900 mb-4">
                                הגדרות SMTP
                            </h3>

                            <p className="text-gray-600 mb-8 max-w-2xl mx-auto">
                                כאן תוכל להגדיר את חיבור ה-SMTP שלך, לבדוק את החיבור ולנהל את כל ההגדרות הנדרשות לשליחת אימיילים.
                            </p>

                            <div className="space-y-4">
                                <div className="bg-gray-100 rounded-lg p-4 text-right">
                                    <h4 className="font-semibold text-gray-900 mb-2">הגדרות נוכחיות:</h4>
                                    <div className="text-sm text-gray-600 space-y-1">
                                        <p><strong>שרת:</strong> mail.tsm.co.il</p>
                                        <p><strong>פורט:</strong> 465 (SSL)</p>
                                        <p><strong>משתמש:</strong> sales@tsm.co.il</p>
                                        <p><strong>מאובטח:</strong> כן</p>
                                    </div>
                                </div>

                                <Button
                                    onClick={() => window.open('/emails/settings', '_blank')}
                                    className="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 text-lg"
                                >
                                    <Settings className="w-5 h-5 ml-2" />
                                    פתח הגדרות SMTP
                                </Button>
                            </div>
                        </div>
                    </Card>
                )}

                {activeTab === 'test' && (
                    <TestSMTPContent />
                )}
            </div>
        </AppLayout>
    );
}
