/**
 * Admin Panel Component
 * Management interface for Telegram users and broadcasts.
 */

function Admin() {
    const [isAuthenticated, setIsAuthenticated] = React.useState(false);
    const [password, setPassword] = React.useState('');
    const [activeTab, setActiveTab] = React.useState('users');
    const [users, setUsers] = React.useState([]);
    const [stats, setStats] = React.useState(null);
    const [loading, setLoading] = React.useState(false);
    const [broadcastMessage, setBroadcastMessage] = React.useState('');
    const [broadcastResult, setBroadcastResult] = React.useState(null);
    const [testNotification, setTestNotification] = React.useState('');
    const [testResult, setTestResult] = React.useState(null);
    const [lastUpdate, setLastUpdate] = React.useState(null);

    const API_BASE = '/api';

    // Check if already authenticated
    React.useEffect(() => {
        const savedPassword = sessionStorage.getItem('admin_password');
        if (savedPassword) {
            setPassword(savedPassword);
            setIsAuthenticated(true);
            fetchData(savedPassword);
        }
    }, []);

    // Auto-refresh when tab becomes visible
    React.useEffect(() => {
        const handleVisibilityChange = () => {
            if (!document.hidden && password) {
                fetchData(password, false);
            }
        };

        document.addEventListener('visibilitychange', handleVisibilityChange);
        return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
    }, [password]);

    const fetchData = async (pwd, showLoading = true) => {
        if (showLoading) setLoading(true);
        try {
            const [statsRes, usersRes] = await Promise.all([
                fetch(`${API_BASE}/admin/stats`, {
                    headers: { 'X-Admin-Password': pwd }
                }),
                fetch(`${API_BASE}/admin/users`, {
                    headers: { 'X-Admin-Password': pwd }
                })
            ]);

            const statsData = await statsRes.json();
            const usersData = await usersRes.json();

            if (statsData.status === 'ok') {
                setStats(statsData.stats);
            }
            if (usersData.status === 'ok') {
                setUsers(usersData.users);
            }
            setLastUpdate(new Date());
        } catch (err) {
            console.error('Failed to fetch admin data:', err);
        } finally {
            if (showLoading) setLoading(false);
        }
    };

    const refreshData = () => {
        if (password) {
            fetchData(password, true);
        }
    };

    const handleLogin = (pwd) => {
        setPassword(pwd);
        setIsAuthenticated(true);
        fetchData(pwd);
    };

    const handleLogout = () => {
        sessionStorage.removeItem('admin_password');
        setIsAuthenticated(false);
        setPassword('');
        setUsers([]);
        setStats(null);
    };

    const toggleUserStatus = async (telegramId) => {
        try {
            const res = await fetch(`${API_BASE}/admin/users/${telegramId}/toggle`, {
                method: 'PATCH',
                headers: { 
                    'Content-Type': 'application/json',
                    'X-Admin-Password': password
                },
                body: JSON.stringify({ password })
            });

            const data = await res.json();

            if (data.status === 'ok') {
                // Update local state
                setUsers(users.map(u => 
                    u.telegram_id === telegramId 
                        ? { ...u, is_active: data.user.is_active }
                        : u
                ));
            }
        } catch (err) {
            console.error('Failed to toggle user:', err);
        }
    };

    const sendBroadcast = async () => {
        if (!broadcastMessage.trim()) return;

        setBroadcastResult(null);
        try {
            const res = await fetch(`${API_BASE}/admin/broadcast`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'X-Admin-Password': password
                },
                body: JSON.stringify({ 
                    message: broadcastMessage,
                    password 
                })
            });

            const data = await res.json();
            setBroadcastResult(data);

            if (data.status === 'ok') {
                setBroadcastMessage('');
            }
        } catch (err) {
            setBroadcastResult({ status: 'error', message: 'Network error' });
        }
    };

    const sendTestNotification = async () => {
        if (!testNotification.trim()) return;

        setTestResult(null);
        try {
            const res = await fetch(`${API_BASE}/admin/test-notify`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'X-Admin-Password': password
                },
                body: JSON.stringify({ 
                    message: testNotification,
                    password 
                })
            });

            const data = await res.json();
            setTestResult(data);

            if (data.status === 'ok') {
                setTestNotification('');
            }
        } catch (err) {
            setTestResult({ status: 'error', message: 'Network error' });
        }
    };

    const formatNumber = (num) => {
        if (num == null) return '-';
        return new Intl.NumberFormat('en-US').format(num);
    };

    const formatDate = (dateStr) => {
        if (!dateStr) return '-';
        const date = new Date(dateStr);
        return date.toLocaleString('en-US', {
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    if (!isAuthenticated) {
        return <AdminModal onLogin={handleLogin} onCancel={() => window.location.href = '/'} />;
    }

    return (
        <div className="min-h-screen p-6">
            <div className="max-w-6xl mx-auto">
                {/* Header */}
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="text-2xl font-bold text-white">Admin Panel - SectorPulse</h1>
                        <p className="text-gray-400 text-sm">Management Console</p>
                    </div>
                    <div className="flex items-center gap-3">
                        <button
                            onClick={refreshData}
                            className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm transition-colors flex items-center gap-2"
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                            </svg>
                            Refresh
                        </button>
                        <button
                            onClick={handleLogout}
                            className="px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm transition-colors"
                        >
                            Logout
                        </button>
                    </div>
                </div>
                
                {/* Last update time */}
                {lastUpdate && (
                    <div className="text-xs text-gray-500 mb-6">
                        Last updated: {lastUpdate.toLocaleTimeString()}
                    </div>
                )}

                {/* Stats Cards */}
                {stats && (
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
                        <div className="glass rounded-xl p-4">
                            <div className="text-gray-400 text-sm mb-1">Total Users</div>
                            <div className="text-2xl font-bold text-white">{formatNumber(stats.totalUsers)}</div>
                        </div>
                        <div className="glass rounded-xl p-4">
                            <div className="text-gray-400 text-sm mb-1">With Capital</div>
                            <div className="text-2xl font-bold text-emerald-400">{formatNumber(stats.usersWithCapital)}</div>
                        </div>
                        <div className="glass rounded-xl p-4">
                            <div className="text-gray-400 text-sm mb-1">Active</div>
                            <div className="text-2xl font-bold text-blue-400">{formatNumber(stats.activeUsers)}</div>
                        </div>
                        <div className="glass rounded-xl p-4">
                            <div className="text-gray-400 text-sm mb-1">24h Notifications</div>
                            <div className="text-2xl font-bold text-purple-400">{formatNumber(stats.recentNotifications)}</div>
                        </div>
                    </div>
                )}

                {/* Tabs */}
                <div className="flex gap-2 mb-6">
                    <button
                        onClick={() => setActiveTab('users')}
                        className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                            activeTab === 'users' 
                                ? 'bg-emerald-500 text-white' 
                                : 'glass text-gray-300 hover:text-white'
                        }`}
                    >
                        Users List
                    </button>
                    <button
                        onClick={() => setActiveTab('broadcast')}
                        className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                            activeTab === 'broadcast' 
                                ? 'bg-emerald-500 text-white' 
                                : 'glass text-gray-300 hover:text-white'
                        }`}
                    >
                        Manual Broadcast
                    </button>
                    <button
                        onClick={() => setActiveTab('test')}
                        className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                            activeTab === 'test' 
                                ? 'bg-emerald-500 text-white' 
                                : 'glass text-gray-300 hover:text-white'
                        }`}
                    >
                        Test Notify
                    </button>
                </div>

                {/* Content */}
                {loading ? (
                    <div className="glass rounded-xl p-12 text-center">
                        <div className="text-gray-400">Loading...</div>
                    </div>
                ) : (
                    <>
                        {/* Users List Tab */}
                        {activeTab === 'users' && (
                            <div className="glass rounded-xl overflow-hidden">
                                <div className="overflow-x-auto">
                                    <table className="w-full">
                                        <thead className="bg-gray-800/50">
                                            <tr>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">ID</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Telegram</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">TG Name</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Email</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Name</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Capital</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Status</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Last Notified</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Bound</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Created</th>
                                                <th className="text-left px-4 py-3 text-gray-400 text-sm font-medium">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-700/50">
                                            {users.map(user => (
                                                <tr key={user.id} className="hover:bg-gray-700/20">
                                                    <td className="px-4 py-3 text-gray-300 text-sm">{user.id}</td>
                                                    <td className="px-4 py-3 text-white text-sm font-mono">{user.telegram_id}</td>
                                                    <td className="px-4 py-3 text-purple-400 text-sm">
                                                        {user.telegram_name || '-'}
                                                    </td>
                                                    <td className="px-4 py-3 text-gray-300 text-sm">
                                                        {user.user_email ? (
                                                            <span className="text-blue-400">{user.user_email}</span>
                                                        ) : (
                                                            <span className="text-gray-600">-</span>
                                                        )}
                                                    </td>
                                                    <td className="px-4 py-3 text-gray-300 text-sm">
                                                        {user.user_name || '-'}
                                                    </td>
                                                    <td className="px-4 py-3 text-emerald-400 text-sm">
                                                        {user.base_capital ? `$${formatNumber(user.base_capital)}` : '-'}
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        {user.is_active ? (
                                                            <span className="px-2 py-1 bg-emerald-500/20 text-emerald-400 rounded text-xs">Active</span>
                                                        ) : (
                                                            <span className="px-2 py-1 bg-gray-500/20 text-gray-400 rounded text-xs">Disabled</span>
                                                        )}
                                                    </td>
                                                    <td className="px-4 py-3 text-gray-400 text-sm">{formatDate(user.last_notified)}</td>
                                                    <td className="px-4 py-3">
                                                        {user.user_id ? (
                                                            <span className="px-2 py-1 bg-blue-500/20 text-blue-400 rounded text-xs">Bound</span>
                                                        ) : (
                                                            <span className="px-2 py-1 bg-gray-500/20 text-gray-500 rounded text-xs">Unbound</span>
                                                        )}
                                                    </td>
                                                    <td className="px-4 py-3 text-gray-400 text-sm">{formatDate(user.created_at)}</td>
                                                    <td className="px-4 py-3">
                                                        <button
                                                            onClick={() => toggleUserStatus(user.telegram_id)}
                                                            className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                                                                user.is_active 
                                                                    ? 'bg-red-500/20 text-red-400 hover:bg-red-500/30'
                                                                    : 'bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30'
                                                            }`}
                                                        >
                                                            {user.is_active ? 'Disable' : 'Enable'}
                                                        </button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                                {users.length === 0 && (
                                    <div className="p-12 text-center text-gray-400">
                                        No users found
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Broadcast Tab */}
                        {activeTab === 'broadcast' && (
                            <div className="glass rounded-xl p-6">
                                <h3 className="text-lg font-semibold text-white mb-4">Send Broadcast Message</h3>
                                <p className="text-gray-400 text-sm mb-4">
                                    Send a message to all users who have notifications enabled and capital configured.
                                </p>
                                
                                <div className="mb-4">
                                    <textarea
                                        value={broadcastMessage}
                                        onChange={(e) => setBroadcastMessage(e.target.value)}
                                        placeholder="Enter your broadcast message..."
                                        className="w-full px-4 py-3 bg-gray-800/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-emerald-500 h-32 resize-none"
                                    />
                                </div>

                                <div className="flex gap-3 mb-4">
                                    <button
                                        onClick={sendBroadcast}
                                        disabled={!broadcastMessage.trim()}
                                        className="px-6 py-2 bg-emerald-500 hover:bg-emerald-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
                                    >
                                        Send Broadcast
                                    </button>
                                </div>

                                {broadcastResult && (
                                    <div className={`p-4 rounded-lg ${
                                        broadcastResult.status === 'ok' 
                                            ? 'bg-emerald-500/20 border border-emerald-500/50' 
                                            : 'bg-red-500/20 border border-red-500/50'
                                    }`}>
                                        <div className={broadcastResult.status === 'ok' ? 'text-emerald-400' : 'text-red-400'}>
                                            {broadcastResult.status === 'ok' 
                                                ? `✅ Broadcast sent! Notified: ${broadcastResult.notified}, Failed: ${broadcastResult.failed}, Skipped: ${broadcastResult.skipped}`
                                                : `❌ ${broadcastResult.message}`
                                            }
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Test Notify Tab */}
                        {activeTab === 'test' && (
                            <div className="glass rounded-xl p-6">
                                <h3 className="text-lg font-semibold text-white mb-4">Send Test Notification</h3>
                                <p className="text-gray-400 text-sm mb-4">
                                    Send a test notification to all active users with capital configured.
                                </p>
                                
                                <div className="mb-4">
                                    <textarea
                                        value={testNotification}
                                        onChange={(e) => setTestNotification(e.target.value)}
                                        placeholder="Enter test message (optional, will use default if empty)..."
                                        className="w-full px-4 py-3 bg-gray-800/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-emerald-500 h-32 resize-none"
                                    />
                                </div>

                                <div className="flex gap-3 mb-4">
                                    <button
                                        onClick={sendTestNotification}
                                        className="px-6 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
                                    >
                                        Send Test to All
                                    </button>
                                </div>

                                {testResult && (
                                    <div className={`p-4 rounded-lg ${
                                        testResult.status === 'ok' 
                                            ? 'bg-emerald-500/20 border border-emerald-500/50' 
                                            : 'bg-red-500/20 border border-red-500/50'
                                    }`}>
                                        <div className={testResult.status === 'ok' ? 'text-emerald-400' : 'text-red-400'}>
                                            {testResult.status === 'ok' 
                                                ? `✅ ${testResult.message}`
                                                : `❌ ${testResult.message}`
                                            }
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}
                    </>
                )}

                {/* Back to Dashboard */}
                <div className="mt-8 text-center">
                    <a href="/" className="text-gray-400 hover:text-white text-sm transition-colors">
                        ← Back to Dashboard
                    </a>
                </div>
            </div>
        </div>
    );
}
