
import React, { useState, useEffect } from 'react';
import {
    Settings,
    Database,
    Mail,
    UserPlus,
    Save,
    LayoutDashboard,
    ExternalLink,
    CheckCircle,
    AlertCircle,
    Hash,
    Server,
    Package,
    Cpu,
    LogOut,
    Palette,
    CreditCard,
    Plus,
    Key,
    Trash2
} from 'lucide-react';
import { BrandingConfig } from '../types';

interface AdminViewProps {
    onLogout: () => void;
}

const API_BASE = '/api/admin';

const AdminView: React.FC<AdminViewProps> = ({ onLogout }) => {
    const [activeTab, setActiveTab] = useState<'general' | 'whmcs' | 'smtp' | 'products' | 'users' | 'virtualizor' | 'branding' | 'payments'>('general');
    const [token, setToken] = useState(localStorage.getItem('admin_token') || '');
    const [loginForm, setLoginForm] = useState({ username: '', password: '' });
    const [isLoggedIn, setIsLoggedIn] = useState(!!token);
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);

    // Settings State
    const [whmcsConfig, setWhmcsConfig] = useState({ url: '', identifier: '', secret: '' });
    const [smtpConfig, setSmtpConfig] = useState({ host: '', port: 587, user: '', pass: '', fromEmail: '' });
    const [groupIds, setGroupIds] = useState({ vps: [] as any[], dedicated: [] as any[], colocation: [] as any[], hosting: [] as any[] });
    const [virtualizorServers, setVirtualizorServers] = useState<Record<number, { ip: string; key: string; pass: string }>>({});
    const [branding, setBranding] = useState<BrandingConfig>({ appName: '', appLogo: '', footerText: '', loginTitle: '', loginSubtitle: '' });
    const [paymentConfig, setPaymentConfig] = useState<any>({
        bank_transfer: {
            enabled: true,
            accounts: []
        }
    });
    const [uddoktaPayConfig, setUddoktaPayConfig] = useState({ api_url: '', api_key: '' });
    const [showAddBankForm, setShowAddBankForm] = useState(false);
    const [newBankAccount, setNewBankAccount] = useState({ bankName: '', accountNumber: '', routingNumber: '', instructions: '' });

    // Admin Management State
    const [newAdmin, setNewAdmin] = useState({ username: '', password: '' });
    const [adminUsers, setAdminUsers] = useState<{ id: number; username: string; created_at: string }[]>([]);
    const [passwordModal, setPasswordModal] = useState<{ isOpen: boolean; userId: number | null; username: string }>({ isOpen: false, userId: null, username: '' });
    const [newPasswordInput, setNewPasswordInput] = useState('');

    useEffect(() => {
        if (isLoggedIn) {
            fetchSettings();
            if (activeTab === 'users') {
                fetchAdminUsers();
            }
        }
    }, [isLoggedIn, activeTab]);

    const fetchAdminUsers = async () => {
        try {
            const res = await fetch(`${API_BASE}/users`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await res.json();
            if (Array.isArray(data)) {
                setAdminUsers(data);
            }
        } catch (err) {
            console.error('Failed to fetch admin users', err);
        }
    };

    const fetchSettings = async () => {
        try {
            const headers = { 'Authorization': `Bearer ${token}` };

            const whmcs = await fetch(`${API_BASE}/settings/whmcs_api`, { headers }).then(r => r.json());
            const smtp = await fetch(`${API_BASE}/settings/smtp_config`, { headers }).then(r => r.json());
            let groups = await fetch(`${API_BASE}/settings/group_mapping`, { headers }).then(r => r.json());

            // Fallback to product_ids if group_mapping is not found (migration)
            if (groups.error) {
                const oldProducts = await fetch(`${API_BASE}/settings/product_ids`, { headers }).then(r => r.json());
                if (!oldProducts.error) groups = oldProducts;
            }

            const virtualizor = await fetch(`${API_BASE}/settings/virtualizor_servers`, { headers }).then(r => r.json());
            const brandingConfig = await fetch(`${API_BASE}/settings/branding`, { headers }).then(r => r.json());
            const payments = await fetch(`${API_BASE}/settings/payment_methods_config`, { headers }).then(r => r.json());
            const uddoktapay = await fetch(`${API_BASE}/settings/uddoktapay_config`, { headers }).then(r => r.json());

            if (!whmcsConfig.url && !whmcs.error) setWhmcsConfig(whmcs);
            if (!whmcs.error) setWhmcsConfig(whmcs);
            if (!smtp.error) setSmtpConfig(smtp);
            if (!groups.error) setGroupIds(groups);
            if (!virtualizor.error) setVirtualizorServers(virtualizor);
            if (!brandingConfig.error) setBranding(brandingConfig);
            if (!uddoktapay.error) setUddoktaPayConfig(uddoktapay);
            if (!payments.error) {
                // Migration logic: if it's the old format (flat object), convert to new format
                if (payments.bankName || payments.accountNumber) {
                    setPaymentConfig({
                        bank_transfer: {
                            enabled: true,
                            accounts: [{
                                id: Date.now(),
                                bankName: payments.bankName || '',
                                accountNumber: payments.accountNumber || '',
                                routingNumber: payments.routingNumber || '',
                                instructions: payments.instructions || ''
                            }]
                        }
                    });
                } else {
                    setPaymentConfig(payments);
                }
            }
        } catch (err) {
            console.error('Failed to fetch settings', err);
        }
    };

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        try {
            const res = await fetch('http://localhost:3001/api/admin/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(loginForm)
            });
            const data = await res.json();
            if (data.token) {
                localStorage.setItem('admin_token', data.token);
                setToken(data.token);
                setIsLoggedIn(true);
                setMessage({ type: 'success', text: 'Logged in as Admin' });
            } else {
                setMessage({ type: 'error', text: data.error || 'Login failed' });
            }
        } catch (err) {
            setMessage({ type: 'error', text: 'Server connection failed' });
        }
        setLoading(false);
    };

    const handleSave = async (key: string, value: any) => {
        setLoading(true);
        try {
            const res = await fetch(`${API_BASE}/settings/${key}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ value })
            });
            const data = await res.json();
            if (data.success) {
                setMessage({ type: 'success', text: 'Settings saved successfully' });
            } else {
                setMessage({ type: 'error', text: data.error || 'Failed to save' });
            }
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to save settings' });
        }
        setLoading(false);
    };

    const handleAddAdmin = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        try {
            const res = await fetch(`${API_BASE}/add`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(newAdmin)
            });
            const data = await res.json();
            if (data.success) {
                setMessage({ type: 'success', text: 'Admin user added' });
                setNewAdmin({ username: '', password: '' });
                fetchAdminUsers();
            } else {
                setMessage({ type: 'error', text: data.error || 'Failed to add admin' });
            }
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to connect' });
        }
        setLoading(false);
    };

    const handleDeleteAdmin = async (id: number) => {
        if (!confirm('Are you sure you want to delete this administrator?')) return;
        setLoading(true);
        try {
            const res = await fetch(`${API_BASE}/users/${id}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await res.json();
            if (data.success) {
                setMessage({ type: 'success', text: 'Admin deleted successfully' });
                fetchAdminUsers();
            } else {
                setMessage({ type: 'error', text: data.error || 'Failed to delete admin' });
            }
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to delete' });
        }
        setLoading(false);
    };

    const handleUpdatePassword = async () => {
        if (!passwordModal.userId || !newPasswordInput) return;
        setLoading(true);
        try {
            const res = await fetch(`${API_BASE}/users/${passwordModal.userId}/password`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ password: newPasswordInput })
            });
            const data = await res.json();
            if (data.success) {
                setMessage({ type: 'success', text: 'Password updated successfully' });
                setPasswordModal({ isOpen: false, userId: null, username: '' });
                setNewPasswordInput('');
            } else {
                setMessage({ type: 'error', text: data.error || 'Failed to update password' });
            }
        } catch (err) {
            setMessage({ type: 'error', text: 'Failed to update' });
        }
        setLoading(false);
    };

    const handleAdminLogout = () => {
        localStorage.removeItem('admin_token');
        setIsLoggedIn(false);
        setToken('');
        onLogout();
    };

    if (!isLoggedIn) {
        return (
            <div className="min-h-screen bg-[#060818] flex items-center justify-center p-6 bg-gradient-to-br from-blue-900/20 to-indigo-900/20">
                <div className="w-full max-w-md bg-white/5 backdrop-blur-xl border border-white/10 p-10 rounded-3xl shadow-2xl">
                    <div className="flex flex-col items-center mb-8">
                        <div className="w-16 h-16 bg-blue-600 rounded-2xl flex items-center justify-center mb-4 shadow-lg shadow-blue-600/20">
                            <Settings className="text-white w-8 h-8" />
                        </div>
                        <h1 className="text-3xl font-bold text-white mb-2">CloudCore Admin</h1>
                        <p className="text-gray-400 text-center">Enter your credentials to manage the dashboard</p>
                    </div>

                    <form onSubmit={handleLogin} className="space-y-6">
                        <div>
                            <label className="block text-sm font-medium text-gray-400 mb-2">Username</label>
                            <input
                                type="text"
                                required
                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                                value={loginForm.username}
                                onChange={(e) => setLoginForm({ ...loginForm, username: e.target.value })}
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-400 mb-2">Password</label>
                            <input
                                type="password"
                                required
                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                                value={loginForm.password}
                                onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })}
                            />
                        </div>
                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full bg-blue-600 hover:bg-blue-500 disabled:opacity-50 text-white font-semibold py-4 rounded-xl shadow-lg shadow-blue-600/20 transition-all"
                        >
                            {loading ? 'Authenticating...' : 'Sign In to Admin'}
                        </button>
                    </form>

                    {message && (
                        <div className={`mt-6 p-4 rounded-xl flex items-center gap-3 ${message.type === 'success' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'}`}>
                            {message.type === 'success' ? <CheckCircle className="w-5 h-5" /> : <AlertCircle className="w-5 h-5" />}
                            <span className="text-sm font-medium">{message.text}</span>
                        </div>
                    )}
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-[#060818] text-white flex">
            {/* Admin Sidebar */}
            <div className="w-72 border-r border-white/5 bg-white/[0.02] backdrop-blur-sm p-6 flex flex-col">
                <div className="flex items-center gap-3 mb-10 px-2">
                    <div className="w-10 h-10 bg-blue-600 rounded-xl flex items-center justify-center">
                        <Settings className="w-6 h-6" />
                    </div>
                    <div>
                        <h2 className="font-bold text-lg">CloudCore</h2>
                        <p className="text-[10px] text-gray-400 uppercase tracking-widest font-semibold">Admin Panel</p>
                    </div>
                </div>

                <nav className="flex-1 space-y-2">
                    <button
                        onClick={() => setActiveTab('general')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'general' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <LayoutDashboard className="w-5 h-5" />
                        <span className="font-medium">Dashboard</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('whmcs')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'whmcs' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <Database className="w-5 h-5" />
                        <span className="font-medium">WHMCS API</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('smtp')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'smtp' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <Mail className="w-5 h-5" />
                        <span className="font-medium">SMTP Config</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('products')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'products' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <Hash className="w-5 h-5" />
                        <span className="font-medium">Group Mapping</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('users')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'users' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <UserPlus className="w-5 h-5" />
                        <span className="font-medium">Admin Users</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('virtualizor')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'virtualizor' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <Server className="w-5 h-5" />
                        <span className="font-medium">Virtualizor</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('branding')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'branding' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <Palette className="w-5 h-5" />
                        <span className="font-medium">Branding</span>
                    </button>
                    <button
                        onClick={() => setActiveTab('payments')}
                        className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${activeTab === 'payments' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/20' : 'text-gray-400 hover:bg-white/5'}`}
                    >
                        <CreditCard className="w-5 h-5" />
                        <span className="font-medium">Payment Methods</span>
                    </button>
                </nav>

                <button
                    onClick={handleAdminLogout}
                    className="mt-auto flex items-center gap-3 px-4 py-3 text-red-400 hover:bg-red-400/5 rounded-xl transition-all"
                >
                    <LogOut className="w-5 h-5" />
                    <span className="font-medium">Sign Out</span>
                </button>
            </div>

            {/* Main Content */}
            <div className="flex-1 p-10 overflow-auto">
                <div className="max-w-4xl mx-auto">
                    <div className="mb-10 flex justify-between items-end">
                        <div>
                            <h1 className="text-4xl font-bold mb-2">
                                {activeTab === 'general' && 'System Overview'}
                                {activeTab === 'whmcs' && 'WHMCS API Configuration'}
                                {activeTab === 'smtp' && 'SMTP Server Settings'}
                                {activeTab === 'products' && 'Product Group Mapping'}
                                {activeTab === 'users' && 'Administrator Management'}
                                {activeTab === 'virtualizor' && 'Virtualizor Nodes Management'}
                                {activeTab === 'branding' && 'Branding & Customization'}
                                {activeTab === 'payments' && 'Payment Methods'}
                            </h1>
                            <p className="text-gray-400">Manage your system-wide configurations and security</p>
                        </div>
                    </div>

                    {message && (
                        <div className={`mb-8 p-4 rounded-2xl flex items-center justify-between gap-3 ${message.type === 'success' ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'}`}>
                            <div className="flex items-center gap-3">
                                {message.type === 'success' ? <CheckCircle className="w-5 h-5" /> : <AlertCircle className="w-5 h-5" />}
                                <span className="font-medium">{message.text}</span>
                            </div>
                            <button onClick={() => setMessage(null)} className="opacity-50 hover:opacity-100 transition-opacity">✕</button>
                        </div>
                    )}

                    <div className="bg-white/[0.03] border border-white/5 rounded-3xl p-8 backdrop-blur-xl shadow-2xl">
                        {activeTab === 'general' && (
                            <div className="grid grid-cols-2 gap-6">
                                <div className="bg-blue-600/10 p-6 rounded-2xl border border-blue-600/20">
                                    <h3 className="text-blue-400 font-semibold mb-2">Backend Status</h3>
                                    <p className="text-2xl font-bold">Operational</p>
                                    <p className="text-sm text-blue-400/60 mt-2">v1.0.0 Express Server</p>
                                </div>
                                <div className="bg-emerald-600/10 p-6 rounded-2xl border border-emerald-600/20">
                                    <h3 className="text-emerald-400 font-semibold mb-2">Database</h3>
                                    <p className="text-2xl font-bold">Connected</p>
                                    <p className="text-sm text-emerald-400/60 mt-2">SQLite (dashboard.db)</p>
                                </div>
                            </div>
                        )}

                        {activeTab === 'whmcs' && (
                            <div className="space-y-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-400 mb-2">API URL</label>
                                    <input
                                        type="text"
                                        className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                        placeholder="https://your-whmcs.com/includes/api.php"
                                        value={whmcsConfig.url}
                                        onChange={(e) => setWhmcsConfig({ ...whmcsConfig, url: e.target.value })}
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-6">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">API Identifier</label>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={whmcsConfig.identifier}
                                            onChange={(e) => setWhmcsConfig({ ...whmcsConfig, identifier: e.target.value })}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">API Secret</label>
                                        <input
                                            type="password"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={whmcsConfig.secret}
                                            onChange={(e) => setWhmcsConfig({ ...whmcsConfig, secret: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <button
                                    onClick={() => handleSave('whmcs_api', whmcsConfig)}
                                    className="bg-blue-600 hover:bg-blue-500 px-6 py-3 rounded-xl font-bold transition-all flex items-center gap-2"
                                >
                                    <Save className="w-5 h-5" />
                                    Save WHMCS Config
                                </button>
                            </div>
                        )}

                        {activeTab === 'smtp' && (
                            <div className="space-y-6">
                                <div className="grid grid-cols-3 gap-6">
                                    <div className="col-span-2">
                                        <label className="block text-sm font-medium text-gray-400 mb-2">SMTP Host</label>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={smtpConfig.host}
                                            onChange={(e) => setSmtpConfig({ ...smtpConfig, host: e.target.value })}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">Port</label>
                                        <input
                                            type="number"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={smtpConfig.port}
                                            onChange={(e) => setSmtpConfig({ ...smtpConfig, port: parseInt(e.target.value) })}
                                        />
                                    </div>
                                </div>
                                <div className="grid grid-cols-2 gap-6">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">Username</label>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={smtpConfig.user}
                                            onChange={(e) => setSmtpConfig({ ...smtpConfig, user: e.target.value })}
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">Password</label>
                                        <input
                                            type="password"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={smtpConfig.pass}
                                            onChange={(e) => setSmtpConfig({ ...smtpConfig, pass: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-400 mb-2">From Email</label>
                                    <input
                                        type="email"
                                        className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                        value={smtpConfig.fromEmail}
                                        onChange={(e) => setSmtpConfig({ ...smtpConfig, fromEmail: e.target.value })}
                                    />
                                </div>
                                <button
                                    onClick={() => handleSave('smtp_config', smtpConfig)}
                                    className="bg-blue-600 hover:bg-blue-500 px-6 py-3 rounded-xl font-bold transition-all flex items-center gap-2"
                                >
                                    <Save className="w-5 h-5" />
                                    Save SMTP Config
                                </button>
                            </div>
                        )}

                        {activeTab === 'products' && (
                            <div className="space-y-8">
                                {[
                                    { id: 'vps', label: 'VPS Group IDs', icon: Server, color: 'text-purple-400' },
                                    { id: 'dedicated', label: 'Dedicated Server Group IDs', icon: Cpu, color: 'text-orange-400' },
                                    { id: 'colocation', label: 'Colocation Group IDs', icon: Database, color: 'text-blue-400' },
                                    { id: 'hosting', label: 'Hosting Group IDs', icon: Package, color: 'text-emerald-400' }
                                ].map((cat) => (
                                    <div key={cat.id} className="bg-white/5 p-6 rounded-2xl border border-white/5">
                                        <div className="flex items-center gap-3 mb-4">
                                            <cat.icon className={`w-5 h-5 ${cat.color}`} />
                                            <h4 className="font-bold">{cat.label}</h4>
                                        </div>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            placeholder="e.g. 10, 11, 15 (Comma separated)"
                                            value={(groupIds as any)[cat.id]?.join(', ') || ''}
                                            onChange={(e) => {
                                                const ids = e.target.value.split(',').map(s => parseInt(s.trim())).filter(n => !isNaN(n));
                                                setGroupIds({ ...groupIds, [cat.id]: ids });
                                            }}
                                        />
                                    </div>
                                ))}
                                <button
                                    onClick={() => handleSave('group_mapping', groupIds)}
                                    className="bg-blue-600 hover:bg-blue-500 px-8 py-4 rounded-xl font-bold transition-all shadow-xl shadow-blue-600/20"
                                >
                                    Save All Group Mapping
                                </button>
                            </div>
                        )}


                        {activeTab === 'users' && (
                            <div className="space-y-8">
                                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                                    {/* Create New Admin */}
                                    <div className="bg-white/5 p-8 rounded-3xl border border-white/5 h-fit">
                                        <h3 className="text-xl font-bold mb-6 flex items-center gap-2">
                                            <UserPlus className="w-5 h-5 text-emerald-400" />
                                            Create New Administrator
                                        </h3>
                                        <form onSubmit={handleAddAdmin} className="space-y-4">
                                            <div>
                                                <label className="block text-sm font-medium text-gray-400 mb-2">Username</label>
                                                <input
                                                    type="text"
                                                    className="w-full bg-black/20 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-emerald-500 outline-none transition-all"
                                                    value={newAdmin.username}
                                                    onChange={(e) => setNewAdmin({ ...newAdmin, username: e.target.value })}
                                                    required
                                                    placeholder="admin_user"
                                                />
                                            </div>
                                            <div>
                                                <label className="block text-sm font-medium text-gray-400 mb-2">Password</label>
                                                <input
                                                    type="password"
                                                    className="w-full bg-black/20 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-emerald-500 outline-none transition-all"
                                                    value={newAdmin.password}
                                                    onChange={(e) => setNewAdmin({ ...newAdmin, password: e.target.value })}
                                                    required
                                                    placeholder="••••••••"
                                                />
                                            </div>
                                            <button
                                                type="submit"
                                                disabled={loading}
                                                className="w-full bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 px-6 py-3 rounded-xl font-bold transition-all flex items-center justify-center gap-2 shadow-lg shadow-emerald-600/20"
                                            >
                                                {loading ? 'Creating...' : 'Create Account'}
                                            </button>
                                        </form>
                                    </div>

                                    {/* Admin List */}
                                    <div className="space-y-4">
                                        <h3 className="text-xl font-bold mb-2">Existing Administrators</h3>
                                        {adminUsers.length === 0 ? (
                                            <div className="text-gray-500 italic">No other admins found.</div>
                                        ) : (
                                            adminUsers.map((user) => (
                                                <div key={user.id} className="bg-white/5 p-4 rounded-xl border border-white/5 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                                    <div>
                                                        <div className="font-bold text-white flex items-center gap-2">
                                                            {user.username}
                                                            <span className="text-xs font-normal text-gray-500 bg-white/10 px-2 py-0.5 rounded-full">ID: {user.id}</span>
                                                        </div>
                                                        <div className="text-xs text-gray-400 mt-1">
                                                            Created: {new Date(user.created_at).toLocaleDateString()}
                                                        </div>
                                                    </div>

                                                    <div className="flex items-center gap-2">
                                                        <button
                                                            onClick={() => setPasswordModal({ isOpen: true, userId: user.id, username: user.username })}
                                                            className="p-2 hover:bg-white/10 rounded-lg text-blue-400 transition-colors"
                                                            title="Change Password"
                                                        >
                                                            <Key className="w-4 h-4" />
                                                        </button>
                                                        <button
                                                            onClick={() => handleDeleteAdmin(user.id)}
                                                            className="p-2 hover:bg-red-500/10 rounded-lg text-red-400 transition-colors"
                                                            title="Delete User"
                                                        >
                                                            <Trash2 className="w-4 h-4" />
                                                        </button>
                                                    </div>
                                                </div>
                                            ))
                                        )}
                                    </div>
                                </div>

                                {/* Change Password Modal */}
                                {passwordModal.isOpen && (
                                    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
                                        <div className="bg-[#0f172a] border border-white/10 rounded-2xl p-6 w-full max-w-sm shadow-2xl">
                                            <h3 className="text-lg font-bold mb-4">Change Password for {passwordModal.username}</h3>
                                            <input
                                                type="password"
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none mb-4"
                                                placeholder="New Password"
                                                value={newPasswordInput}
                                                onChange={(e) => setNewPasswordInput(e.target.value)}
                                            />
                                            <div className="flex justify-end gap-3">
                                                <button
                                                    onClick={() => {
                                                        setPasswordModal({ isOpen: false, userId: null, username: '' });
                                                        setNewPasswordInput('');
                                                    }}
                                                    className="px-4 py-2 hover:bg-white/5 rounded-lg text-gray-400 transition-colors"
                                                >
                                                    Cancel
                                                </button>
                                                <button
                                                    onClick={handleUpdatePassword}
                                                    className="bg-blue-600 hover:bg-blue-500 px-4 py-2 rounded-lg text-white font-bold transition-colors"
                                                >
                                                    Update
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        )}

                        {activeTab === 'virtualizor' && (
                            <div className="space-y-8">
                                <div className="flex justify-between items-center mb-6">
                                    <h3 className="text-xl font-bold">Configured Servers</h3>
                                    <button
                                        onClick={() => {
                                            const nextId = Math.max(...Object.keys(virtualizorServers).map(Number), 0) + 1;
                                            setVirtualizorServers({ ...virtualizorServers, [nextId]: { ip: '', key: '', pass: '' } });
                                        }}
                                        className="bg-blue-600 hover:bg-blue-500 px-4 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2"
                                    >
                                        <Server className="w-4 h-4" /> Add New Node
                                    </button>
                                </div>

                                <div className="space-y-4">
                                    {Object.entries(virtualizorServers).map(([id, s]) => (
                                        <div key={id} className="bg-white/5 p-6 rounded-2xl border border-white/5 relative group transition-all hover:bg-white/10">
                                            <div className="grid grid-cols-12 gap-4">
                                                <div className="col-span-2">
                                                    <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">Server ID (WHMCS)</label>
                                                    <input
                                                        type="number"
                                                        value={id}
                                                        onChange={(e) => {
                                                            const newId = parseInt(e.target.value);
                                                            if (isNaN(newId)) return;
                                                            const next = { ...virtualizorServers };
                                                            const val = next[parseInt(id)];
                                                            delete next[parseInt(id)];
                                                            next[newId] = val;
                                                            setVirtualizorServers(next);
                                                        }}
                                                        className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-blue-400 font-bold focus:ring-1 focus:ring-blue-500 outline-none"
                                                    />
                                                </div>
                                                <div className="col-span-2">
                                                    <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">Server IP</label>
                                                    <input
                                                        type="text"
                                                        value={s.ip}
                                                        onChange={(e) => setVirtualizorServers({ ...virtualizorServers, [parseInt(id)]: { ...s, ip: e.target.value } })}
                                                        className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                    />
                                                </div>
                                                <div className="col-span-4">
                                                    <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">API Key</label>
                                                    <input
                                                        type="text"
                                                        value={s.key}
                                                        onChange={(e) => setVirtualizorServers({ ...virtualizorServers, [parseInt(id)]: { ...s, key: e.target.value } })}
                                                        className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                    />
                                                </div>
                                                <div className="col-span-3">
                                                    <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">API Pass</label>
                                                    <input
                                                        type="password"
                                                        value={s.pass}
                                                        onChange={(e) => setVirtualizorServers({ ...virtualizorServers, [parseInt(id)]: { ...s, pass: e.target.value } })}
                                                        className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                    />
                                                </div>
                                                <div className="col-span-1 flex items-end">
                                                    <button
                                                        onClick={() => {
                                                            const next = { ...virtualizorServers };
                                                            delete next[parseInt(id)];
                                                            setVirtualizorServers(next);
                                                        }}
                                                        className="text-red-400 hover:text-red-300 p-2 rounded-lg hover:bg-red-400/10 transition-all ml-auto"
                                                    >
                                                        ✕
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>

                                {Object.keys(virtualizorServers).length === 0 && (
                                    <div className="text-center py-10 opacity-30">
                                        <Server className="w-12 h-12 mx-auto mb-3" />
                                        <p>No Virtualizor nodes configured</p>
                                    </div>
                                )}

                                <div className="pt-4">
                                    <button
                                        onClick={() => handleSave('virtualizor_servers', virtualizorServers)}
                                        className="bg-blue-600 hover:bg-blue-500 px-8 py-3 rounded-xl font-bold transition-all shadow-xl shadow-blue-600/20 flex items-center gap-2"
                                    >
                                        <Save className="w-5 h-5" /> Save Virtualizor Config
                                    </button>
                                </div>
                            </div>

                        )}



                        {activeTab === 'branding' && (
                            <div className="space-y-8">
                                <div className="space-y-6 border-b border-white/5 pb-8">
                                    <h3 className="text-xl font-bold mb-4">General Branding</h3>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">Application Name</label>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={branding.appName}
                                            onChange={(e) => setBranding({ ...branding, appName: e.target.value })}
                                        />
                                    </div>
                                    <div className="grid grid-cols-2 gap-6">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-400 mb-2">Company Name</label>
                                            <input
                                                type="text"
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                                value={branding.companyName || ''}
                                                onChange={(e) => setBranding({ ...branding, companyName: e.target.value })}
                                                placeholder="e.g. GotMyHost"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-400 mb-2">Company Address</label>
                                            <textarea
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none min-h-[50px] resize-none"
                                                value={branding.companyAddress || ''}
                                                onChange={(e) => setBranding({ ...branding, companyAddress: e.target.value })}
                                                placeholder="e.g. Dhaka, Bangladesh"
                                            />
                                        </div>
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">Logo URL</label>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={branding.appLogo}
                                            onChange={(e) => setBranding({ ...branding, appLogo: e.target.value })}
                                            placeholder="https://example.com/logo.png"
                                        />
                                        {branding.appLogo && (
                                            <div className="mt-4 p-4 bg-white/5 rounded-xl flex items-center justify-center">
                                                <img src={branding.appLogo} alt="Preview" className="h-10 object-contain" />
                                            </div>
                                        )}
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-400 mb-2">Footer Copyright Text</label>
                                        <input
                                            type="text"
                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                            value={branding.footerText}
                                            onChange={(e) => setBranding({ ...branding, footerText: e.target.value })}
                                        />
                                    </div>
                                    <div className="grid grid-cols-2 gap-6">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-400 mb-2">Login Page Title</label>
                                            <input
                                                type="text"
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                                value={branding.loginTitle}
                                                onChange={(e) => setBranding({ ...branding, loginTitle: e.target.value })}
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-400 mb-2">Login Page Subtitle</label>
                                            <input
                                                type="text"
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-blue-500 outline-none"
                                                value={branding.loginSubtitle}
                                                onChange={(e) => setBranding({ ...branding, loginSubtitle: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => handleSave('branding', branding)}
                                        className="bg-blue-600 hover:bg-blue-500 px-8 py-3 rounded-xl font-bold transition-all shadow-xl shadow-blue-600/20 flex items-center gap-2"
                                    >
                                        <Save className="w-5 h-5" /> Save Branding Settings
                                    </button>
                                </div>

                                {/* Login Slider Section */}
                                <div className="space-y-6">
                                    <div className="flex justify-between items-center">
                                        <h3 className="text-xl font-bold">Login Page Slider</h3>
                                        <button
                                            onClick={() => {
                                                const newSlide = { id: Date.now(), image: '', title: '', subtitle: '' };
                                                const currentSlides = (branding as any).loginSlides || [];
                                                handleSave('login_slider', [...currentSlides, newSlide]);
                                                // Optimistic update
                                                setBranding({ ...branding, loginSlides: [...currentSlides, newSlide] } as any);
                                            }}
                                            className="bg-emerald-600 hover:bg-emerald-500 px-4 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2"
                                        >
                                            <Plus className="w-4 h-4" /> Add Slide
                                        </button>
                                    </div>

                                    <div className="space-y-4">
                                        {((branding as any).loginSlides || []).map((slide: any, index: number) => (
                                            <div key={slide.id} className="bg-white/5 p-6 rounded-2xl border border-white/5 relative group">
                                                <div className="grid grid-cols-12 gap-4">
                                                    <div className="col-span-4">
                                                        <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">Image URL</label>
                                                        <input
                                                            type="text"
                                                            value={slide.image}
                                                            onChange={(e) => {
                                                                const newSlides = [...((branding as any).loginSlides || [])];
                                                                newSlides[index].image = e.target.value;
                                                                setBranding({ ...branding, loginSlides: newSlides } as any);
                                                            }}
                                                            className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                            placeholder="https://..."
                                                        />
                                                        {slide.image && (
                                                            <img src={slide.image} alt="Preview" className="mt-2 h-20 w-full object-cover rounded-lg opacity-50" />
                                                        )}
                                                    </div>
                                                    <div className="col-span-3">
                                                        <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">Title</label>
                                                        <input
                                                            type="text"
                                                            value={slide.title}
                                                            onChange={(e) => {
                                                                const newSlides = [...((branding as any).loginSlides || [])];
                                                                newSlides[index].title = e.target.value;
                                                                setBranding({ ...branding, loginSlides: newSlides } as any);
                                                            }}
                                                            className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                            placeholder="Main Headline"
                                                        />
                                                    </div>
                                                    <div className="col-span-4">
                                                        <label className="block text-[10px] text-gray-500 uppercase font-bold mb-1">Subtitle</label>
                                                        <input
                                                            type="text"
                                                            value={slide.subtitle}
                                                            onChange={(e) => {
                                                                const newSlides = [...((branding as any).loginSlides || [])];
                                                                newSlides[index].subtitle = e.target.value;
                                                                setBranding({ ...branding, loginSlides: newSlides } as any);
                                                            }}
                                                            className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                            placeholder="Subtext description..."
                                                        />
                                                    </div>
                                                    <div className="col-span-1 flex items-start pt-6">
                                                        <button
                                                            onClick={() => {
                                                                const newSlides = ((branding as any).loginSlides || []).filter((_: any, i: number) => i !== index);
                                                                handleSave('login_slider', newSlides);
                                                                setBranding({ ...branding, loginSlides: newSlides } as any);
                                                            }}
                                                            className="text-red-400 hover:text-red-300 p-2 rounded-lg hover:bg-red-400/10 transition-all ml-auto"
                                                        >
                                                            <Trash2 size={16} />
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                        {(!((branding as any).loginSlides) || (branding as any).loginSlides.length === 0) && (
                                            <div className="text-center py-10 opacity-30 border-2 border-dashed border-white/10 rounded-2xl">
                                                <Palette className="w-12 h-12 mx-auto mb-3" />
                                                <p>No slides configured. Default static image will be used.</p>
                                            </div>
                                        )}
                                    </div>

                                    {((branding as any).loginSlides && (branding as any).loginSlides.length > 0) && (
                                        <button
                                            onClick={() => handleSave('login_slider', (branding as any).loginSlides)}
                                            className="bg-blue-600 hover:bg-blue-500 px-8 py-3 rounded-xl font-bold transition-all shadow-xl shadow-blue-600/20 flex items-center gap-2"
                                        >
                                            <Save className="w-5 h-5" /> Save Slider Config
                                        </button>
                                    )}
                                </div>
                            </div>
                        )}
                        {activeTab === 'payments' && (
                            <div className="space-y-8">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className={`p-6 rounded-3xl border transition-all cursor-pointer ${paymentConfig.bank_transfer?.enabled ? 'bg-blue-600/10 border-blue-600/20' : 'bg-white/5 border-white/10 opacity-60'}`}>
                                        <div className="flex items-center justify-between mb-4">
                                            <div className="flex items-center gap-3">
                                                <div className="p-3 bg-blue-600 rounded-2xl">
                                                    <CreditCard size={24} />
                                                </div>
                                                <div>
                                                    <h3 className="font-bold text-lg">Bank Transfer</h3>
                                                    <p className="text-xs text-gray-400">Manual verification</p>
                                                </div>
                                            </div>
                                            <label className="relative inline-flex items-center cursor-pointer">
                                                <input
                                                    type="checkbox"
                                                    className="sr-only peer"
                                                    checked={paymentConfig.bank_transfer?.enabled}
                                                    onChange={(e) => setPaymentConfig({
                                                        ...paymentConfig,
                                                        bank_transfer: { ...paymentConfig.bank_transfer, enabled: e.target.checked }
                                                    })}
                                                />
                                                <div className="w-11 h-6 bg-white/10 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                            </label>
                                        </div>

                                        <div className="space-y-4">
                                            <div className="flex items-center justify-between">
                                                <span className="text-sm font-medium text-gray-400">Configured Accounts</span>
                                                <span className="px-2 py-1 bg-blue-600/20 text-blue-400 text-[10px] font-bold rounded-lg uppercase">
                                                    {paymentConfig.bank_transfer?.accounts?.length || 0} Accounts
                                                </span>
                                            </div>

                                            <div className="space-y-2 max-h-48 overflow-y-auto pr-2 custom-scrollbar">
                                                {paymentConfig.bank_transfer?.accounts?.map((acc: any, idx: number) => (
                                                    <div key={acc.id || idx} className="p-3 bg-white/5 rounded-xl border border-white/5 flex items-center justify-between group">
                                                        <div className="min-w-0">
                                                            <p className="text-sm font-bold truncate">{acc.bankName}</p>
                                                            <p className="text-[10px] text-gray-500 font-mono truncate">{acc.accountNumber}</p>
                                                        </div>
                                                        <button
                                                            onClick={() => {
                                                                const newAccs = paymentConfig.bank_transfer.accounts.filter((_: any, i: number) => i !== idx);
                                                                setPaymentConfig({
                                                                    ...paymentConfig,
                                                                    bank_transfer: { ...paymentConfig.bank_transfer, accounts: newAccs }
                                                                });
                                                            }}
                                                            className="p-2 text-red-400 opacity-0 group-hover:opacity-100 transition-all hover:bg-red-400/10 rounded-lg"
                                                        >
                                                            <Trash2 size={16} />
                                                        </button>
                                                    </div>
                                                ))}
                                                {(!paymentConfig.bank_transfer?.accounts || paymentConfig.bank_transfer.accounts.length === 0) && !showAddBankForm && (
                                                    <p className="text-center py-4 text-xs text-gray-500 italic">No accounts added yet</p>
                                                )}
                                            </div>

                                            {showAddBankForm ? (
                                                <div className="p-4 bg-white/5 rounded-2xl border border-blue-600/30 space-y-4 animate-in slide-in-from-top-2 duration-200">
                                                    <div className="grid grid-cols-1 gap-3">
                                                        <input
                                                            type="text"
                                                            placeholder="Bank Name"
                                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                            value={newBankAccount.bankName}
                                                            onChange={(e) => setNewBankAccount({ ...newBankAccount, bankName: e.target.value })}
                                                        />
                                                        <div className="grid grid-cols-2 gap-3">
                                                            <input
                                                                type="text"
                                                                placeholder="Account Number"
                                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                                value={newBankAccount.accountNumber}
                                                                onChange={(e) => setNewBankAccount({ ...newBankAccount, accountNumber: e.target.value })}
                                                            />
                                                            <input
                                                                type="text"
                                                                placeholder="Routing / SWIFT"
                                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                                value={newBankAccount.routingNumber}
                                                                onChange={(e) => setNewBankAccount({ ...newBankAccount, routingNumber: e.target.value })}
                                                            />
                                                        </div>
                                                        <textarea
                                                            placeholder="Instructions"
                                                            rows={2}
                                                            className="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:ring-1 focus:ring-blue-500 outline-none"
                                                            value={newBankAccount.instructions}
                                                            onChange={(e) => setNewBankAccount({ ...newBankAccount, instructions: e.target.value })}
                                                        />
                                                    </div>
                                                    <div className="flex gap-2">
                                                        <button
                                                            onClick={() => {
                                                                if (newBankAccount.bankName && newBankAccount.accountNumber) {
                                                                    setPaymentConfig({
                                                                        ...paymentConfig,
                                                                        bank_transfer: {
                                                                            ...paymentConfig.bank_transfer,
                                                                            accounts: [...(paymentConfig.bank_transfer.accounts || []), { ...newBankAccount, id: Date.now() }]
                                                                        }
                                                                    });
                                                                    setNewBankAccount({ bankName: '', accountNumber: '', routingNumber: '', instructions: '' });
                                                                    setShowAddBankForm(false);
                                                                }
                                                            }}
                                                            className="flex-1 py-2 bg-blue-600 rounded-xl text-[10px] font-bold"
                                                        >
                                                            Add Account
                                                        </button>
                                                        <button
                                                            onClick={() => setShowAddBankForm(false)}
                                                            className="px-4 py-2 bg-white/5 rounded-xl text-[10px] font-bold text-gray-400"
                                                        >
                                                            Cancel
                                                        </button>
                                                    </div>
                                                </div>
                                            ) : (
                                                <button
                                                    onClick={() => setShowAddBankForm(true)}
                                                    className="w-full py-3 border-2 border-dashed border-white/10 rounded-xl text-xs font-bold text-gray-400 hover:border-blue-500/50 hover:text-blue-400 transition-all flex items-center justify-center gap-2"
                                                >
                                                    <Plus size={14} /> Add Bank Account
                                                </button>
                                            )}
                                        </div>
                                    </div>

                                    {/* Placeholder for other methods or spacing */}
                                    <div className="p-6 rounded-3xl border border-white/10 bg-white/5 opacity-40 grayscale flex flex-col items-center justify-center text-center">
                                        <div className="p-4 bg-white/10 rounded-full mb-3 text-gray-400">
                                            <CreditCard size={32} />
                                        </div>
                                        <h3 className="font-bold">Other Gateway</h3>
                                        <p className="text-xs text-gray-500">Coming Soon</p>
                                    </div>
                                </div>

                                {/* UddoktaPay Configuration Section */}
                                <div className="mt-8 bg-white/5 p-8 rounded-3xl border border-white/10">
                                    <div className="flex items-center gap-4 mb-6">
                                        <div className="p-3 bg-emerald-600 rounded-2xl">
                                            <ExternalLink size={24} />
                                        </div>
                                        <div>
                                            <h3 className="text-xl font-bold">UddoktaPay Settings</h3>
                                            <p className="text-sm text-gray-400">Configure your UddoktaPay API credentials for automated payments</p>
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                                        <div>
                                            <label className="block text-sm font-medium text-gray-400 mb-2">API Base URL</label>
                                            <input
                                                type="text"
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-emerald-500 outline-none transition-all"
                                                placeholder="https://sandbox.uddoktapay.com/"
                                                value={uddoktaPayConfig.api_url}
                                                onChange={(e) => setUddoktaPayConfig({ ...uddoktaPayConfig, api_url: e.target.value })}
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-sm font-medium text-gray-400 mb-2">API Key</label>
                                            <input
                                                type="password"
                                                className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white focus:ring-2 focus:ring-emerald-500 outline-none transition-all"
                                                placeholder="Enter your API Key"
                                                value={uddoktaPayConfig.api_key}
                                                onChange={(e) => setUddoktaPayConfig({ ...uddoktaPayConfig, api_key: e.target.value })}
                                            />
                                        </div>
                                    </div>

                                    <button
                                        onClick={() => handleSave('uddoktapay_config', uddoktaPayConfig)}
                                        className="bg-emerald-600 hover:bg-emerald-500 px-6 py-3 rounded-xl font-bold transition-all flex items-center gap-2 shadow-lg shadow-emerald-600/20"
                                    >
                                        <Save size={18} />
                                        Save UddoktaPay Config
                                    </button>
                                </div>

                                <div className="flex justify-end pt-6 border-t border-white/5">
                                    <button
                                        onClick={() => handleSave('payment_methods_config', paymentConfig)}
                                        className="bg-blue-600 hover:bg-blue-500 px-8 py-4 rounded-2xl font-bold transition-all shadow-xl shadow-blue-600/30 flex items-center gap-3"
                                    >
                                        <Save className="w-5 h-5" />
                                        Save All Changes
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>

    );
};

export default AdminView;
