import React, { useState, useEffect } from 'react';
import { ModelConfig, ModelType, AppSettings, KnowledgeGroup } from '../../types';
import { useLanguage } from '../../contexts/LanguageContext';
import { X, Plus, Trash2, Edit2, Save, Cpu, Box, Loader2, User, Shield, Key, LogOut, Globe, Settings as SettingsIcon, ToggleLeft, ToggleRight, Database, Sparkles, ChevronRight, Lock, Building2, BookOpen, UserCircle, HardDrive, LayoutGrid } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { userService } from '../../services/userService';
import { settingsService } from '../../services/settingsService';
import { userSettingService } from '../../services/userSettingService';
import { knowledgeGroupService } from '../../services/knowledgeGroupService';

import { useConfirm } from '../../contexts/ConfirmContext';
import { useToast } from '../../contexts/ToastContext';

interface SettingsViewProps {
    // Model Props
    models: ModelConfig[];
    authToken: string | null;
    onUpdateModels: (action: 'create' | 'update' | 'delete', model: ModelConfig) => Promise<void>;
    isAdmin?: boolean;  // Added isAdmin prop
    currentUser?: any;  // Added current user prop
    initialTab?: TabType;
}

type TabType = 'general' | 'user' | 'model' | 'tenants' | 'knowledge_base' | 'import_tasks';

export const SettingsView: React.FC<SettingsViewProps> = ({
    models,
    authToken,
    onUpdateModels,
    isAdmin = false,
    currentUser,
    initialTab = 'general',
}) => {
    const { t, language, setLanguage } = useLanguage();
    const { confirm } = useConfirm();
    const { showError, showSuccess } = useToast();
    const [activeTab, setActiveTab] = useState<TabType>('general');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // --- Model Manager State ---
    const [editingId, setEditingId] = useState<string | null>(null);
    const [modelFormData, setModelFormData] = useState<Partial<ModelConfig>>({
        type: ModelType.LLM,
        baseUrl: 'http://localhost:11434/v1',
        modelId: 'llama3',
        name: '',
        dimensions: 1536,
        apiKey: '',
        maxInputTokens: 8191,
        maxBatchSize: 2048
    });

    // --- User Management State ---
    interface UserType {
        id: string;
        username: string;
        isAdmin: boolean;
        role?: string;
        tenantId?: string;
        createdAt: string;
        tenantMembers?: Array<{ tenantId: string; role: string; tenant?: { id: string; name: string } }>;
    }
    const [users, setUsers] = useState<UserType[]>([]);
    const [isUserLoading, setIsUserLoading] = useState(false);
    const [userPage, setUserPage] = useState(1);
    const USER_PAGE_SIZE = 20;
    const [showAddUser, setShowAddUser] = useState(false);
    const [newUser, setNewUser] = useState({ username: '', password: '', role: 'USER' });
    const [userSuccess, setUserSuccess] = useState('');

    // --- Change Password State ---
    const [passwordForm, setPasswordForm] = useState({ current: '', new: '', confirm: '' });
    const [passwordSuccess, setPasswordSuccess] = useState('');

    // --- App Settings State ---
    const [appSettings, setAppSettings] = useState<AppSettings | null>(null);
    const [knowledgeGroups, setKnowledgeGroups] = useState<KnowledgeGroup[]>([]);
    const [isSettingsLoading, setIsSettingsLoading] = useState(false);
    const [enabledModelIds, setEnabledModelIds] = useState<string[]>([]);

    // --- Tenant Admin Binding Search State ---
    const [bindingTenantId, setBindingTenantId] = useState<string | null>(null);
    const [userSearchQuery, setUserSearchQuery] = useState('');

    // --- Manage Members Modal State ---
    const [managingMembersTenantId, setManagingMembersTenantId] = useState<string | null>(null);
    const [tenantMembers, setTenantMembers] = useState<any[]>([]);
    const [memberUserSearch, setMemberUserSearch] = useState('');
    const [isMembersLoading, setIsMembersLoading] = useState(false);

    useEffect(() => {
        if (initialTab) {
            setActiveTab(initialTab);
        }
    }, [initialTab]);

    // Fetch user list (if users tab is active)
    // Data fetching on tab change
    useEffect(() => {
        if (activeTab === 'user') {
            fetchUsers();
        } else if (activeTab === 'general') {
            fetchSettingsAndGroups();
        } else if (activeTab === 'tenants' && currentUser?.role === 'SUPER_ADMIN') {
            fetchTenantsData();
            fetchUsers(); // Ensure users are loaded for admin binding
        }

        // Independent check for KB/Model settings to avoid being blocked by the branches above
        if ((activeTab === 'knowledge_base' || activeTab === 'model') &&
            (currentUser?.role === 'TENANT_ADMIN' || currentUser?.role === 'SUPER_ADMIN' || isAdmin)) {
            fetchKnowledgeBaseSettings();
        }
    }, [activeTab, currentUser, authToken, isAdmin]);

    const [kbSettings, setKbSettings] = useState<any>(null);
    const [localKbSettings, setLocalKbSettings] = useState<any>(null);
    const [isSavingKbSettings, setIsSavingKbSettings] = useState(false);
    const fetchKnowledgeBaseSettings = async () => {
        if (!authToken) return;
        setIsLoading(true);
        try {
            const res = await fetch('/api/v1/admin/settings', {
                headers: { 'Authorization': `Bearer ${authToken}` }
            });
            if (res.ok) {
                const data = await res.json();
                setKbSettings(data);
                setLocalKbSettings(data);
                if (data.enabledModelIds) {
                    setEnabledModelIds(data.enabledModelIds);
                } else {
                    setEnabledModelIds([]);
                }
            }
        } catch (error) {
            console.error(error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleUpdateKbSettings = (key: string, value: any) => {
        setLocalKbSettings((prev: any) => ({ ...prev, [key]: value }));
    };

    const handleSaveKbSettings = async () => {
        if (!authToken || !localKbSettings) return;
        setIsSavingKbSettings(true);
        try {
            const res = await fetch('/api/v1/admin/settings', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
                body: JSON.stringify(localKbSettings)
            });
            if (res.ok) {
                setKbSettings(localKbSettings);
                showSuccess(t('kbSettingsSaved'));
            } else {
                showError(t('failedToSaveSettings'));
            }
        } catch (error) {
            showError(t('actionFailed'));
        } finally {
            setIsSavingKbSettings(false);
        }
    };

    const handleCancelKbSettings = () => {
        setLocalKbSettings(kbSettings);
    };

    const fetchSettingsAndGroups = async () => {
        if (!authToken) return;
        setIsSettingsLoading(true);
        try {
            const [settings, groups] = await Promise.all([
                userSettingService.get(authToken),
                knowledgeGroupService.getGroups()
            ]);
            setAppSettings(settings);
            setKnowledgeGroups(groups);
        } catch (error) {
            console.error('Failed to fetch settings or groups:', error);
        } finally {
            setIsSettingsLoading(false);
        }
    };

    // --- General tab handlers ---


    const handleChangePassword = async (e: React.FormEvent) => {
        e.preventDefault();
        setError(null);
        setPasswordSuccess('');

        if (passwordForm.new !== passwordForm.confirm) {
            setError(t('passwordMismatch'));
            return;
        }
        if (passwordForm.new.length < 6) {
            setError(t('newPasswordMinLength'));
            return;
        }

        setIsLoading(true);
        try {
            await userService.changePassword(passwordForm.current, passwordForm.new);
            setPasswordSuccess(t('passwordChangeSuccess'));
            setPasswordForm({ current: '', new: '', confirm: '' });
        } catch (err: any) {
            setError(err.message || t('passwordChangeFailed'));
        } finally {
            setIsLoading(false);
        }
    };


    // --- Users tab handlers ---
    const fetchUsers = async () => {
        setIsUserLoading(true);
        try {
            const userList = await userService.getUsers();
            setUsers(userList);
        } catch (error: any) {
            setError(error.message || t('getUserListFailed'));
        } finally {
            setIsUserLoading(false);
        }
    };

    const handleCreateUser = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        setUserSuccess('');

        if (newUser.password.length < 6) {
            setError(t('passwordMinLength'));
            return;
        }

        try {
            await userService.createUser(newUser.username, newUser.password, newUser.role);
            setUserSuccess(t('userCreatedSuccess'));
            setNewUser({ username: '', password: '', role: 'USER' });
            setShowAddUser(false);
            fetchUsers();
        } catch (error: any) {
            setError(error.message || t('createUserFailed'));
        }
    };

    const [passwordChangeUserData, setPasswordChangeUserData] = useState<{ userId: string, newPassword: string } | null>(null);

    // --- Edit Role State ---
    const [roleChangeUserData, setRoleChangeUserData] = useState<{ userId: string, newRole: string } | null>(null);

    const handleToggleUserAdmin = async (userId: string, newAdminStatus: boolean) => {
        try {
            await userService.updateUser(userId, newAdminStatus);
            // Re-fetch user list
            fetchUsers();
            setUserSuccess(newAdminStatus ? t('userPromotedToAdmin') : t('userDemotedFromAdmin'));
        } catch (error: any) {
            setError(error.message || t('updateUserFailed'));
        }
    };

    const handleUserPasswordChange = async () => {
        if (!passwordChangeUserData || !passwordChangeUserData.newPassword) return;

        try {
            // Update user password
            await userService.updateUserInfo(passwordChangeUserData.userId, { password: passwordChangeUserData.newPassword });
            setUserSuccess(t('passwordChangeSuccess'));
            setPasswordChangeUserData(null);
            fetchUsers(); // Refresh the user list
        } catch (error: any) {
            setError(error.message || t('passwordChangeFailed'));
        }
    };

    // --- Tenants Management State (Migrated) ---
    const [stats, setStats] = useState({ tenants: 0, users: 0 });
    const [tenants, setTenants] = useState<any[]>([]);
    const [tenantAdmins, setTenantAdmins] = useState<any[]>([]);
    const [isTenantsLoading, setIsTenantsLoading] = useState(false);
    const [showCreateTenant, setShowCreateTenant] = useState(false);
    const [editingTenant, setEditingTenant] = useState<any | null>(null);
    const [newTenant, setNewTenant] = useState({ name: '', domain: '', adminUserId: '' });

    const fetchTenantMembers = async (tenantId: string) => {
        setIsMembersLoading(true);
        try {
            const headers = { 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' };
            const res = await fetch(`/api/v1/tenants/${tenantId}/members`, { headers });
            if (res.ok) {
                setTenantMembers(await res.json());
            }
        } catch (e) {
            console.error(e);
        } finally {
            setIsMembersLoading(false);
        }
    };

    const handleAddMember = async (tenantId: string, userId: string) => {
        try {
            const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' };
            const res = await fetch(`/api/v1/tenants/${tenantId}/members`, {
                method: 'POST',
                headers,
                body: JSON.stringify({ userId, role: 'USER' }),
            });
            if (res.ok) {
                showSuccess(t('userAddedToOrganization')); // Need to add this key? No, used generic success
                showSuccess(t('confirm')); // Using t('confirm') for now or generic
                fetchTenantMembers(tenantId);
                fetchTenantsData();
                fetchUsers();
            } else {
                const errData = await res.json().catch(() => ({}));
                showError(errData.message || 'Failed to add member');
            }
        } catch (e) {
            showError('Error adding member');
        }
    };

    const handleRemoveMember = async (tenantId: string, userId: string) => {
        try {
            const headers = { 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' };
            const res = await fetch(`/api/v1/tenants/${tenantId}/members/${userId}`, {
                method: 'DELETE',
                headers,
            });
            if (res.ok || res.status === 204) {
                showSuccess('User removed from organization');
                fetchTenantMembers(tenantId);
                fetchTenantsData();
                fetchUsers();
            } else {
                showError('Failed to remove member');
            }
        } catch (e) {
            showError('Error removing member');
        }
    };

    const fetchTenantsData = async () => {
        setIsTenantsLoading(true);
        try {
            const headers = { 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' };
            const [tenRes, admRes] = await Promise.all([
                fetch('/api/v1/tenants', { headers }),
                fetch('/api/v1/admin/users', { headers })
            ]);
            if (tenRes.ok) {
                const data: any[] = await tenRes.json();
                // Fetch settings for each tenant in parallel and merge as settings_obj
                const withSettings = await Promise.all(
                    data.map(async (t) => {
                        try {
                            const sRes = await fetch(`/api/tenants/${t.id}/settings`, { headers });
                            const settings_obj = sRes.ok ? await sRes.json() : null;
                            return { ...t, settings_obj };
                        } catch {
                            return { ...t, settings_obj: null };
                        }
                    })
                );
                setTenants(withSettings);
                setStats(s => ({ ...s, tenants: withSettings.length }));
            }
            if (admRes.ok) {
                const data = await admRes.json();
                setTenantAdmins(data.filter((u: any) => u.role === 'TENANT_ADMIN' || u.role === 'SUPER_ADMIN'));
                setStats(s => ({ ...s, users: data.length }));
            }
        } catch (e) {
            console.error(e);
        } finally {
            setIsTenantsLoading(false);
        }
    };

    const handleCreateTenant = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            if (editingTenant) {
                const res = await fetch(`/api/v1/tenants/${editingTenant.id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' },
                    body: JSON.stringify({ name: newTenant.name, domain: newTenant.domain })
                });
                if (res.ok) {
                    setEditingTenant(null);
                    setNewTenant({ name: '', domain: '', adminUserId: '' });
                    fetchTenantsData();
                    showSuccess('Tenant updated successfully');
                } else {
                    showError('Failed to update tenant');
                }
            } else {
                const res = await fetch('/api/v1/tenants', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' },
                    body: JSON.stringify(newTenant)
                });
                if (res.ok) {
                    setShowCreateTenant(false);
                    setNewTenant({ name: '', domain: '', adminUserId: '' });
                    fetchTenantsData();
                    showSuccess('Tenant created successfully');
                } else {
                    showError('Failed to create tenant');
                }
            }
        } catch (e) {
            showError('Error processing tenant');
        }
    };

    const handleDeleteTenant = async (tenantId: string) => {
        if (!(await confirm('Are you sure you want to delete this tenant? All associated data will be removed.'))) return;
        try {
            const res = await fetch(`/api/v1/tenants/${tenantId}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' }
            });
            if (res.ok) {
                showSuccess('Tenant deleted successfully');
                fetchTenantsData();
            } else {
                showError('Failed to delete tenant');
            }
        } catch (e) {
            showError('Error deleting tenant');
        }
    };

    const handleBindAdmin = async (tenantId: string, userId: string): Promise<boolean> => {
        if (!userId) return false;
        try {
            const res = await fetch(`/api/v1/tenants/${tenantId}/admin`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' },
                body: JSON.stringify({ userId })
            });
            if (res.ok) {
                showSuccess('Admin bound successfully');
                // Refresh tenants data and users to ensure all states are in sync
                await Promise.all([
                    fetchTenantsData(),
                    fetchUsers()
                ]);
                return true;
            } else {
                showError('Failed to bind admin');
                return false;
            }
        } catch (e) {
            showError('Error binding admin');
            return false;
        }
    };

    const handleToggleNotebookFeature = async (tenantId: string, currentEnabled: boolean) => {
        try {
            const res = await fetch(`/api/tenants/${tenantId}/settings`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}`, 'x-api-key': authToken || '' },
                body: JSON.stringify({ isNotebookEnabled: !currentEnabled })
            });
            if (res.ok) {
                showSuccess('Feature updated successfully');
                fetchTenantsData();
            } else {
                showError('Failed to update feature');
            }
        } catch (e) {
            showError('Failed to update feature');
        }
    };

    const handleUserRoleChange = async () => {
        if (!roleChangeUserData) return;
        try {
            await userService.updateUserInfo(roleChangeUserData.userId, { role: roleChangeUserData.newRole });
            showSuccess(t('featureUpdated'));
            setRoleChangeUserData(null);
            fetchUsers();
        } catch (error: any) {
            showError(error.response?.data?.message || 'Failed to update user role.');
        }
    };

    const handleDeleteUser = async (userId: string) => {
        if (!confirm(t('confirmDeleteUser') || "Are you sure you want to delete this user?")) return;
        try {
            await userService.deleteUser(userId);
            showSuccess(t('userDeletedSuccessfully'));
            fetchUsers();
        } catch (error: any) {
            showError(error.message || t('deleteUserFailed'));
        }
    };

    // --- Models tab handlers ---
    const handleSaveModel = async () => {
        if (!authToken) {
            setError(t('mmErrorNotAuthenticated'));
            return;
        }
        setError(null);

        if (!modelFormData.name?.trim()) { setError(t('mmErrorNameRequired')); return; }
        if (!modelFormData.modelId?.trim()) { setError(t('mmErrorModelIdRequired')); return; }
        if (!modelFormData.baseUrl?.trim()) { setError(t('mmErrorBaseUrlRequired')); return; }

        setIsLoading(true);
        try {
            const saveData = { ...modelFormData } as ModelConfig;
            await onUpdateModels(editingId === 'new' ? 'create' : 'update', saveData);
            setEditingId(null);
        } catch (err: any) {
            setError(err.message || t('errorGeneric'));
        } finally {
            setIsLoading(false);
        }
    };

    const handleToggleModel = async (model: ModelConfig) => {
        if (currentUser?.role === 'TENANT_ADMIN') {
            const newEnabledIds = enabledModelIds.includes(model.id)
                ? enabledModelIds.filter(id => id !== model.id)
                : [...enabledModelIds, model.id];

            try {
                await fetch('/api/v1/admin/settings', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
                    body: JSON.stringify({ enabledModelIds: newEnabledIds })
                });
                setEnabledModelIds(newEnabledIds);
                // Keep localKbSettings in sync to prevent overwrite on save in KB tab
                setLocalKbSettings(prev => prev ? { ...prev, enabledModelIds: newEnabledIds } : prev);
                setKbSettings(prev => prev ? { ...prev, enabledModelIds: newEnabledIds } : prev);
                showSuccess('Settings updated successfully');
            } catch (error) {
                console.error(error);
                showError(t('errorGeneric'));
            }
            return;
        }

        try {
            await onUpdateModels('update', { ...model, isEnabled: !model.isEnabled });
        } catch (error) {
            console.error('Failed to toggle model:', error);
        }
    };

    const handleDeleteModel = async (id: string) => {
        if (await confirm(t('confirmClear'))) {
            await onUpdateModels('delete', { id } as ModelConfig);
        }
    };

    const getTypeLabel = (type: ModelType) => {
        switch (type) {
            case ModelType.LLM: return t('typeLLM');
            case ModelType.EMBEDDING: return t('typeEmbedding');
            case ModelType.RERANK: return t('typeRerank');
        }
    };

    // --- Rendering functions ---

    const renderGeneralTab = () => (
        <div className="space-y-8 animate-in slide-in-from-right duration-300 max-w-2xl">

            {/* Change password section */}
            <section className="bg-white p-6 rounded-lg border border-slate-200 shadow-sm">
                <h3 className="text-sm font-medium text-slate-800 mb-4 flex items-center gap-2">
                    <Key className="w-4 h-4 text-blue-500" />
                    {t('changePassword')}
                </h3>
                <form onSubmit={handleChangePassword} className="space-y-4 max-w-sm">
                    <div>
                        <input
                            type="password"
                            placeholder={t('currentPassword')}
                            value={passwordForm.current}
                            onChange={e => setPasswordForm({ ...passwordForm, current: e.target.value })}
                            className="w-full px-3 py-2 text-sm border border-slate-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
                            required
                        />
                    </div>
                    <div>
                        <input
                            type="password"
                            placeholder={t('newPassword')}
                            value={passwordForm.new}
                            onChange={e => setPasswordForm({ ...passwordForm, new: e.target.value })}
                            className="w-full px-3 py-2 text-sm border border-slate-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
                            required
                        />
                    </div>
                    <div>
                        <input
                            type="password"
                            placeholder={t('confirmPassword')}
                            value={passwordForm.confirm}
                            onChange={e => setPasswordForm({ ...passwordForm, confirm: e.target.value })}
                            className="w-full px-3 py-2 text-sm border border-slate-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none"
                            required
                        />
                    </div>
                    {passwordSuccess && <p className="text-xs text-green-600">{passwordSuccess}</p>}

                    <button
                        type="submit"
                        disabled={isLoading}
                        className="w-full py-2 bg-slate-800 text-white rounded-md text-sm hover:bg-slate-900 transition-colors disabled:opacity-50"
                    >
                        {isLoading ? <Loader2 className="w-4 h-4 animate-spin mx-auto" /> : t('confirmChange')}
                    </button>
                </form>
            </section>



            {/* Language settings section */}
            <section className="bg-white p-6 rounded-lg border border-slate-200 shadow-sm">
                <h3 className="text-sm font-medium text-slate-800 mb-4 flex items-center gap-2">
                    <Globe className="w-4 h-4 text-blue-500" />
                    {t('languageSettings')}
                </h3>
                <div className="space-y-4 max-w-sm">
                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">
                            {t('switchLanguage')}
                        </label>
                        <select
                            value={language}
                            onChange={(e) => setLanguage(e.target.value as any)}
                            className="w-full px-3 py-2 text-sm border border-slate-300 rounded-md focus:ring-2 focus:ring-blue-500 outline-none bg-white"
                        >
                            <option value="en">English</option>
                            <option value="zh">Chinese (Chinese)</option>
                            <option value="ja">Japanese (Japanese)</option>
                        </select>
                    </div>
                </div>
            </section>

        </div >
    );

    const renderUserTab = () => (
        <div className="space-y-6 w-full">
            <div className="flex justify-between items-center mb-6">
                <div>
                    <h3 className="text-sm font-black text-slate-500 uppercase tracking-[0.15em] mb-1">{t('userList')}</h3>
                    <p className="text-xs text-slate-400 font-medium">{t('sidebarDesc')}</p>
                </div>
                {currentUser?.role === 'SUPER_ADMIN' && (
                    <button
                        onClick={() => setShowAddUser(!showAddUser)}
                        className="flex items-center gap-2 px-6 py-2.5 bg-indigo-600 text-white text-sm font-bold rounded-2xl hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all active:scale-95"
                    >
                        <Plus className="w-4 h-4" />
                        {t('addUser')}
                    </button>
                )}
            </div>

            {showAddUser && (
                <motion.form
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    onSubmit={handleCreateUser}
                    className="bg-white/80 backdrop-blur-md p-8 rounded-3xl border border-slate-200/50 shadow-xl mb-8 space-y-5"
                >
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <input
                            type="text"
                            placeholder={t('usernamePlaceholder')}
                            value={newUser.username}
                            onChange={e => setNewUser({ ...newUser, username: e.target.value })}
                            className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
                            required
                        />
                        <input
                            type="password"
                            placeholder={t('passwordPlaceholder')}
                            value={newUser.password}
                            onChange={e => setNewUser({ ...newUser, password: e.target.value })}
                            className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
                            required
                        />
                    </div>
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3 bg-slate-50 px-4 py-2 rounded-xl border border-slate-200/50">
                            <Shield className={`w-4 h-4 ${currentUser?.role === 'SUPER_ADMIN' ? 'text-red-500' : 'text-indigo-500'}`} />
                            {currentUser?.role === 'SUPER_ADMIN' ? (
                                <select
                                    className="bg-transparent text-xs font-bold text-slate-600 uppercase tracking-widest outline-none cursor-pointer"
                                    value={newUser.role}
                                    onChange={e => setNewUser({ ...newUser, role: e.target.value })}
                                >
                                    <option value="TENANT_ADMIN">{t('roleTenantAdmin')}</option>
                                    <option value="USER">{t('roleRegularUser')}</option>
                                </select>
                            ) : (
                                <span className="text-xs font-bold text-slate-600 uppercase tracking-widest">
                                    {t('creatingRegularUser')}
                                </span>
                            )}
                        </div>
                        <div className="flex gap-3">
                            <button type="button" onClick={() => setShowAddUser(false)} className="px-5 py-2 text-xs font-bold text-slate-500 hover:text-slate-700">{t('cancel')}</button>
                            <button type="submit" className="px-8 py-2 bg-slate-900 text-white rounded-xl text-xs font-black uppercase tracking-widest hover:bg-indigo-600 transition-all shadow-lg shadow-slate-100">{t('create')}</button>
                        </div>
                    </div>
                </motion.form>
            )}

            {passwordChangeUserData && (
                <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center z-[100] p-6">
                    <motion.div
                        initial={{ scale: 0.95, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-white rounded-3xl p-10 w-full max-w-md shadow-2xl border border-white/20"
                    >
                        <div className="flex items-center justify-between mb-8">
                            <h3 className="text-xl font-black text-slate-900 tracking-tight">{t('changeUserPassword')}</h3>
                            <button onClick={() => setPasswordChangeUserData(null)} className="p-2 hover:bg-slate-100 rounded-xl transition-all">
                                <X size={20} className="text-slate-400" />
                            </button>
                        </div>

                        <form onSubmit={(e) => { e.preventDefault(); handleUserPasswordChange(); }} className="space-y-6">
                            <div>
                                <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 px-1">
                                    {t('newPassword')}
                                </label>
                                <input
                                    type="password"
                                    value={passwordChangeUserData.newPassword}
                                    onChange={(e) => setPasswordChangeUserData({ ...passwordChangeUserData, newPassword: e.target.value })}
                                    className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-[14px] font-medium transition-all focus:outline-none focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50"
                                    placeholder={t('enterNewPassword')}
                                    required
                                />
                            </div>

                            <div className="flex gap-4 pt-4">
                                <button type="button" onClick={() => setPasswordChangeUserData(null)} className="flex-1 py-3.5 text-slate-500 font-bold text-sm">{t('cancel')}</button>
                                <button type="submit" className="flex-1 py-3.5 bg-slate-900 text-white rounded-2xl font-black uppercase tracking-widest text-xs hover:bg-indigo-600 shadow-xl shadow-slate-100 transition-all">{t('confirmChange')}</button>
                            </div>
                        </form>
                    </motion.div>
                </div>
            )}

            {/* Edit Role Modal */}
            {roleChangeUserData && (
                <div className="fixed inset-0 z-[110] flex items-center justify-center bg-slate-900/40 backdrop-blur-sm p-4">
                    <motion.div
                        initial={{ scale: 0.95, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-white rounded-3xl p-10 w-full max-w-md shadow-2xl border border-white/20"
                    >
                        <div className="flex items-center justify-between mb-8">
                            <h3 className="text-xl font-black text-slate-900 tracking-tight">{t('editUserRole')}</h3>
                            <button onClick={() => setRoleChangeUserData(null)} className="p-2 hover:bg-slate-100 rounded-xl transition-all">
                                <X size={20} className="text-slate-400" />
                            </button>
                        </div>

                        <form onSubmit={(e) => { e.preventDefault(); handleUserRoleChange(); }} className="space-y-6">
                            <div>
                                <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 px-1">
                                    {t('targetRole')}
                                </label>
                                <select
                                    value={roleChangeUserData.newRole}
                                    onChange={(e) => setRoleChangeUserData({ ...roleChangeUserData, newRole: e.target.value })}
                                    className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-[14px] font-medium transition-all focus:outline-none focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50"
                                >
                                    <option value="TENANT_ADMIN">{t('roleTenantAdmin')}</option>
                                    <option value="USER">{t('roleRegularUser')}</option>
                                </select>
                            </div>

                            <div className="flex gap-4 pt-4">
                                <button type="button" onClick={() => setRoleChangeUserData(null)} className="flex-1 py-3.5 text-slate-500 font-bold text-sm">{t('cancel')}</button>
                                <button type="submit" className="flex-1 py-3.5 bg-slate-900 text-white rounded-2xl font-black uppercase tracking-widest text-xs hover:bg-indigo-600 shadow-xl shadow-slate-100 transition-all">{t('confirmChange')}</button>
                            </div>
                        </form>
                    </motion.div>
                </div>
            )}

            <div className="grid grid-cols-1 gap-4 overflow-y-auto pr-2 scrollbar-hide">
                <AnimatePresence>
                    {users.slice((userPage - 1) * USER_PAGE_SIZE, userPage * USER_PAGE_SIZE).map((user, index) => {
                        let IconComponent = User;
                        let iconColors = 'bg-slate-50 text-slate-400';
                        if (user.role === 'SUPER_ADMIN') {
                            IconComponent = Shield;
                            iconColors = 'bg-red-50 text-red-600';
                        } else if (user.isAdmin || user.role === 'TENANT_ADMIN') {
                            IconComponent = Shield;
                            iconColors = 'bg-indigo-50 text-indigo-600';
                        }

                        return (
                            <motion.div
                                key={user.id}
                                initial={{ opacity: 0, x: -10 }}
                                animate={{ opacity: 1, x: 0 }}
                                transition={{ delay: index * 0.05 }}
                                className="flex items-center justify-between p-5 bg-white/70 backdrop-blur-md border border-slate-200/50 rounded-2xl shadow-sm hover:shadow-md hover:border-indigo-200/50 transition-all group"
                            >
                                <div className="flex items-center gap-4 flex-1 min-w-0">
                                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${iconColors}`}>
                                        <IconComponent size={22} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 flex-wrap">
                                            <p className="font-black text-slate-900">{user.username}</p>
                                            {(user.role === 'SUPER_ADMIN' || user.isAdmin) && <span className={`text-[9px] font-black px-1.5 py-0.5 rounded-md uppercase tracking-wider ${user.role === 'SUPER_ADMIN' ? 'bg-red-100 text-red-700' : 'bg-indigo-100 text-indigo-700'}`}>{user.role === 'SUPER_ADMIN' ? 'SUPER' : 'ADMIN'}</span>}
                                        </div>
                                        <p className="text-[10px] font-bold text-slate-400 mt-0.5 uppercase tracking-widest">{t('createdAt')}: {new Date(user.createdAt).toLocaleDateString()}</p>
                                        {user.tenantMembers && user.tenantMembers.length > 0 && (
                                            <div className="flex flex-wrap gap-1 mt-1.5">
                                                {user.tenantMembers
                                                    .filter((m: any) => m.tenant?.name !== 'Default')
                                                    .map((m: any) => (
                                                        <span
                                                            key={m.tenantId}
                                                            className="inline-flex items-center gap-1 px-2 py-0.5 bg-emerald-50 text-emerald-700 text-[9px] font-black rounded-md uppercase tracking-wider border border-emerald-100"
                                                        >
                                                            <Building2 size={8} />
                                                            {m.tenant?.name || m.tenantId}
                                                        </span>
                                                    ))}
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-all">
                                    {user.username !== 'admin' && (
                                        <>
                                            {currentUser?.role === 'SUPER_ADMIN' && user.role !== 'SUPER_ADMIN' && (
                                                <button
                                                    onClick={(e) => {
                                                        e.preventDefault();
                                                        e.stopPropagation();
                                                        setRoleChangeUserData({ userId: user.id, newRole: user.role && user.role !== 'USER' ? user.role : (user.isAdmin ? 'TENANT_ADMIN' : 'USER') });
                                                    }}
                                                    className="p-2.5 rounded-xl text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-all cursor-pointer relative z-10"
                                                    title={t('editCategory')} // Using editCategory as generic edit for now or need editRole
                                                >
                                                    <Edit2 className="w-4.5 h-4.5" />
                                                </button>
                                            )}
                                            <button
                                                onClick={() => setPasswordChangeUserData({ userId: user.id, newPassword: '' })}
                                                className="p-2.5 rounded-xl text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition-all"
                                                title={t('changeUserPassword')}
                                            >
                                                <Key className="w-4.5 h-4.5" />
                                            </button>
                                            {user.id !== currentUser?.id && (
                                                <button
                                                    onClick={() => handleDeleteUser(user.id)}
                                                    className="p-2.5 rounded-xl text-slate-400 hover:text-red-500 hover:bg-red-50 transition-all"
                                                    title={t('deleteUser')}
                                                >
                                                    <Trash2 className="w-4.5 h-4.5" />
                                                </button>
                                            )}
                                        </>
                                    )}
                                </div>
                            </motion.div>
                        );
                    })}
                </AnimatePresence>
            </div>

            {/* User list pagination - show whenever there are users */}
            {users.length > 0 && (
                <div className="flex items-center justify-center gap-3 pt-4 border-t border-slate-100 mt-4">
                    <button
                        onClick={() => setUserPage(p => Math.max(1, p - 1))}
                        disabled={userPage === 1}
                        className="px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-xl hover:bg-slate-50 disabled:opacity-30 transition-all"
                    >
                        {t('previous')}
                    </button>
                    <span className="text-xs font-semibold text-slate-500">
                        {t('showingRange',
                            (userPage - 1) * USER_PAGE_SIZE + 1,
                            Math.min(userPage * USER_PAGE_SIZE, users.length),
                            users.length
                        )}
                    </span>
                    <button
                        onClick={() => setUserPage(p => Math.min(Math.ceil(users.length / USER_PAGE_SIZE), p + 1))}
                        disabled={userPage === Math.ceil(users.length / USER_PAGE_SIZE)}
                        className="px-4 py-2 text-xs font-bold text-slate-600 border border-slate-200 rounded-xl hover:bg-slate-50 disabled:opacity-30 transition-all"
                    >
                        {t('next')}
                    </button>
                </div>
            )}
        </div>
    );

    const renderTenantsTab = () => (
        <div className="w-full space-y-8 animate-in fade-in duration-500">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="p-6 bg-white border border-slate-200 rounded-3xl shadow-sm">
                    <div className="flex items-center gap-3 mb-2 text-blue-600">
                        <Building2 size={20} />
                        <span className="text-xs font-black uppercase tracking-widest">{t('totalTenants')}</span>
                    </div>
                    <p className="text-3xl font-black text-slate-900">{stats.tenants}</p>
                </div>
                <div className="p-6 bg-white border border-slate-200 rounded-3xl shadow-sm">
                    <div className="flex items-center gap-3 mb-2 text-indigo-600">
                        <User size={20} />
                        <span className="text-xs font-black uppercase tracking-widest">{t('systemUsers')}</span>
                    </div>
                    <p className="text-3xl font-black text-slate-900">{stats.users}</p>
                </div>
                <div className="p-6 bg-emerald-50 border border-emerald-100 rounded-3xl shadow-sm">
                    <div className="flex items-center gap-3 mb-2 text-emerald-600">
                        <Sparkles size={20} />
                        <span className="text-xs font-black uppercase tracking-widest">{t('systemHealth')}</span>
                    </div>
                    <p className="text-xl font-bold text-emerald-700">{t('operational')}</p>
                </div>
            </div>

            <div className="bg-white border border-slate-200 rounded-3xl shadow-xl overflow-hidden">
                <div className="p-6 border-b border-slate-100 flex items-center justify-between">
                    <div>
                        <h3 className="font-black text-slate-900 text-lg tracking-tight">{t('orgManagement')}</h3>
                        <p className="text-xs font-medium text-slate-400">{t('globalTenantControl')}</p>
                    </div>
                    <button onClick={() => setShowCreateTenant(true)} className="flex items-center gap-2 px-4 py-2 bg-slate-900 text-white text-xs font-bold rounded-xl hover:bg-slate-700 transition-all">
                        <Plus size={16} /> {t('newTenant')}
                    </button>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full text-left">
                        <thead className="bg-slate-50/50 text-[10px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">
                            <tr>
                                <th className="px-6 py-4">{t('name')}</th>
                                <th className="px-6 py-4">{t('domainOptional')}</th>
                                <th className="px-6 py-4">{t('admin')}</th>
                                <th className="px-6 py-4">{t('userList')}</th>
                                <th className="px-6 py-4">{t('tabSettings')}</th>
                                <th className="px-6 py-4">{t('createdAt')}</th>
                                <th className="px-6 py-4 text-right">{t('actions')}</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {tenants.map(t => (
                                <tr key={t.id} className="hover:bg-slate-50/50 transition-colors group">
                                    <td className="px-6 py-4 text-sm font-bold text-slate-900">{t.name}</td>
                                    <td className="px-6 py-4 text-xs font-mono text-slate-500">{t.domain || '-'}</td>
                                    <td className="px-6 py-4 text-xs">
                                        {(() => {
                                            // Search admin in tenant members - the source of truth for multi-tenancy
                                            const adminMember = t.members?.find((m: any) => m.role === 'TENANT_ADMIN' || m.role === 'SUPER_ADMIN');
                                            const adminUser = adminMember?.user;

                                            if (adminUser) {
                                                return (
                                                    <div className="flex items-center gap-1.5 text-slate-600 font-medium">
                                                        <div className="w-5 h-5 rounded-full bg-indigo-50 flex items-center justify-center">
                                                            <User className="w-3 h-3 text-indigo-500" />
                                                        </div>
                                                        {adminUser.username}
                                                        {t.name !== 'Default' && (
                                                            <button
                                                                onClick={() => {
                                                                    setBindingTenantId(t.id);
                                                                    setUserSearchQuery('');
                                                                    fetchUsers();
                                                                }}
                                                                className="ml-2 p-1 hover:bg-indigo-50 text-slate-400 hover:text-indigo-600 rounded transition-all"
                                                                title="Change Admin"
                                                            >
                                                                <Edit2 size={12} />
                                                            </button>
                                                        )}
                                                    </div>
                                                );
                                            } else {
                                                return (
                                                    <div className="flex items-center gap-2">
                                                        {t.name !== 'Default' ? (
                                                            <button
                                                                onClick={() => {
                                                                    setBindingTenantId(t.id);
                                                                    setUserSearchQuery('');
                                                                    fetchUsers();
                                                                }}
                                                                className="px-3 py-1.5 bg-indigo-50 text-indigo-600 hover:bg-indigo-100 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all"
                                                            >
                                                                Bind Admin
                                                            </button>
                                                        ) : (
                                                            <span className="text-[10px] text-slate-400 italic">System Restricted</span>
                                                        )}
                                                        <span className="text-[10px] text-slate-400 italic">None</span>
                                                    </div>
                                                );
                                            }
                                        })()}
                                    </td>
                                    <td className="px-6 py-4 text-xs">
                                        {/* Members count + manage button */}
                                        <div className="flex items-center gap-2">
                                            <span className="font-bold text-slate-700">
                                                {(t.members || []).filter((m: any) => m.role !== 'SUPER_ADMIN').length}
                                            </span>
                                            <span className="text-slate-400">users</span>
                                            {t.name !== 'Default' && (
                                                <button
                                                    onClick={() => {
                                                        setManagingMembersTenantId(t.id);
                                                        setMemberUserSearch('');
                                                        fetchTenantMembers(t.id);
                                                        fetchUsers();
                                                    }}
                                                    className="ml-1 px-2.5 py-1 bg-emerald-50 text-emerald-700 hover:bg-emerald-100 rounded-lg text-[10px] font-black uppercase tracking-widest transition-all"
                                                >
                                                    Manage
                                                </button>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4">
                                        <div className="flex items-center gap-2">
                                            <span title="Notebook Feature"><BookOpen size={14} className={t.settings_obj?.isNotebookEnabled !== false ? 'text-indigo-500' : 'text-slate-300'} /></span>
                                            {t.name !== 'Default' ? (
                                                <button
                                                    onClick={() => handleToggleNotebookFeature(t.id, t.settings_obj?.isNotebookEnabled !== false)}
                                                    title={t.settings_obj?.isNotebookEnabled !== false ? 'Disable Notebook' : 'Enable Notebook'}
                                                    className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${t.settings_obj?.isNotebookEnabled !== false ? 'bg-indigo-500' : 'bg-slate-200'}`}
                                                >
                                                    <span className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${t.settings_obj?.isNotebookEnabled !== false ? 'translate-x-4' : 'translate-x-0'}`} />
                                                </button>
                                            ) : (
                                                <div className="relative inline-flex h-5 w-9 rounded-full bg-slate-100 border-2 border-transparent cursor-not-allowed" title="Fixed">
                                                    <span className="pointer-events-none inline-block h-4 w-4 translate-x-0 transform rounded-full bg-white shadow ring-0" />
                                                </div>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 text-xs text-slate-400">{new Date(t.createdAt).toLocaleDateString()}</td>
                                    <td className="px-6 py-4 text-right">
                                        {t.name !== 'Default' && (
                                            <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-all">
                                                <button
                                                    onClick={() => {
                                                        setEditingTenant(t);
                                                        setNewTenant({ name: t.name, domain: t.domain || '', adminUserId: '' });
                                                    }}
                                                    className="p-1.5 hover:bg-slate-100 text-slate-400 hover:text-indigo-600 rounded-lg transition-all"
                                                    title="Edit Tenant"
                                                >
                                                    <Edit2 size={14} />
                                                </button>
                                                <button
                                                    onClick={() => handleDeleteTenant(t.id)}
                                                    className="p-1.5 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-lg transition-all"
                                                    title="Delete Tenant"
                                                >
                                                    <Trash2 size={14} />
                                                </button>
                                            </div>
                                        )}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>

            {(showCreateTenant || editingTenant) && (
                <div className="fixed inset-0 z-[120] bg-slate-900/40 backdrop-blur-sm flex items-center justify-center p-4">
                    <motion.div initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="bg-white rounded-3xl p-8 w-full max-w-md shadow-2xl">
                        <h3 className="text-xl font-black text-slate-900 mb-6">{editingTenant ? 'Edit Organization' : 'Create New Tenant'}</h3>
                        <form onSubmit={handleCreateTenant} className="space-y-5">
                            <input className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm" placeholder="Tenant Name" value={newTenant.name} onChange={e => setNewTenant({ ...newTenant, name: e.target.value })} required />
                            <input className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm" placeholder="Domain (optional)" value={newTenant.domain} onChange={e => setNewTenant({ ...newTenant, domain: e.target.value })} />

                            {!editingTenant && (
                                <div className="space-y-2">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">Assign Initial Admin</label>
                                    <select
                                        className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm outline-none focus:ring-2 focus:ring-indigo-500/20 transition-all"
                                        value={newTenant.adminUserId}
                                        onChange={e => setNewTenant({ ...newTenant, adminUserId: e.target.value })}
                                    >
                                        <option value="">Select a user (optional)</option>
                                        {users.filter(u => u.role === 'TENANT_ADMIN').map(u => (
                                            <option key={u.id} value={u.id}>{u.username}</option>
                                        ))}
                                    </select>
                                    <p className="text-[10px] text-slate-400 px-1 italic">Selecting a user will promote them to Tenant Admin for this organization.</p>
                                </div>
                            )}

                            <div className="flex gap-4 pt-2">
                                <button type="button" onClick={() => { setShowCreateTenant(false); setEditingTenant(null); }} className="flex-1 py-3 text-slate-500 font-bold text-sm">Cancel</button>
                                <button type="submit" className="flex-1 py-3 bg-slate-900 text-white rounded-2xl font-black uppercase tracking-widest text-xs hover:bg-indigo-600">{editingTenant ? 'Save Changes' : 'Create'}</button>
                            </div>
                        </form>
                    </motion.div>
                </div>
            )}

            {/* Bind Admin Search Modal */}
            <AnimatePresence>
                {bindingTenantId && (
                    <div className="fixed inset-0 z-[130] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-4">
                        <motion.div
                            initial={{ scale: 0.9, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            exit={{ scale: 0.9, opacity: 0 }}
                            className="bg-white rounded-[2.5rem] p-8 w-full max-w-lg shadow-2xl border border-white/20 overflow-hidden relative"
                        >
                            <div className="absolute top-0 right-0 p-6">
                                <button onClick={() => setBindingTenantId(null)} className="p-2 hover:bg-slate-100 rounded-2xl transition-all">
                                    <X size={20} className="text-slate-400" />
                                </button>
                            </div>

                            <div className="mb-8">
                                <h3 className="text-2xl font-black text-slate-900 tracking-tight mb-2">Bind Tenant Admin</h3>
                                <p className="text-sm text-slate-500 font-medium">Search and select a user to manage <span className="text-indigo-600 font-bold">{tenants.find(t => t.id === bindingTenantId)?.name}</span></p>
                            </div>

                            <div className="relative mb-6">
                                <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                                    <Globe size={18} />
                                </div>
                                <input
                                    autoFocus
                                    className="w-full pl-12 pr-4 py-4 bg-slate-50 border border-slate-200 rounded-3xl text-sm font-medium focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
                                    placeholder="Search users by name..."
                                    value={userSearchQuery}
                                    onChange={e => setUserSearchQuery(e.target.value)}
                                />
                            </div>

                            <div className="max-h-[350px] overflow-y-auto pr-2 flex flex-col gap-3 scrollbar-hide">
                                {users
                                    .filter(u =>
                                        (u.role === 'TENANT_ADMIN' || u.isAdmin) &&
                                        u.role !== 'SUPER_ADMIN' &&
                                        u.username.toLowerCase().includes(userSearchQuery.toLowerCase())
                                    )
                                    .map(u => (
                                        <button
                                            key={u.id}
                                            onClick={async () => {
                                                const success = await handleBindAdmin(bindingTenantId, u.id);
                                                if (success) setBindingTenantId(null);
                                            }}
                                            className="w-full flex items-center justify-between p-4 bg-slate-50/50 hover:bg-indigo-50 border border-slate-200/50 hover:border-indigo-200 rounded-[1.5rem] transition-all group"
                                        >
                                            <div className="flex items-center gap-3">
                                                <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center text-slate-400 group-hover:text-indigo-600 group-hover:shadow-sm transition-all">
                                                    <User size={18} />
                                                </div>
                                                <div className="text-left">
                                                    <p className="text-sm font-black text-slate-900">{u.username}</p>
                                                    <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{u.role || 'User'}</p>
                                                </div>
                                            </div>
                                            <ChevronRight size={16} className="text-slate-300 group-hover:text-indigo-400 group-hover:translate-x-1 transition-all" />
                                        </button>
                                    ))}

                                {users.filter(u =>
                                    (u.role === 'TENANT_ADMIN' || u.isAdmin) &&
                                    u.role !== 'SUPER_ADMIN' &&
                                    u.username.toLowerCase().includes(userSearchQuery.toLowerCase())
                                ).length === 0 && (
                                        <div className="py-12 text-center opacity-40">
                                            <User size={40} className="mx-auto mb-3" />
                                            <p className="text-xs font-bold uppercase tracking-widest">No unassigned users found</p>
                                        </div>
                                    )}
                            </div>

                            <div className="mt-8 pt-6 border-t border-slate-100 flex justify-end">
                                <button onClick={() => setBindingTenantId(null)} className="px-6 py-3 text-sm font-bold text-slate-500 hover:text-slate-700 transition-all">
                                    Cancel
                                </button>
                            </div>
                        </motion.div>
                    </div>
                )}
            </AnimatePresence>

            {/* Manage Members Modal */}
            <AnimatePresence>
                {managingMembersTenantId && (() => {
                    const tenant = tenants.find(t => t.id === managingMembersTenantId);
                    const memberUserIds = new Set(tenantMembers.map((m: any) => m.userId));
                    const availableUsers = users.filter(u =>
                        !memberUserIds.has(u.id) &&
                        u.role !== 'SUPER_ADMIN' &&
                        u.username.toLowerCase().includes(memberUserSearch.toLowerCase())
                    );
                    return (
                        <div className="fixed inset-0 z-[140] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-4">
                            <motion.div
                                initial={{ scale: 0.9, opacity: 0 }}
                                animate={{ scale: 1, opacity: 1 }}
                                exit={{ scale: 0.9, opacity: 0 }}
                                className="bg-white rounded-[2.5rem] p-8 w-full max-w-2xl shadow-2xl border border-white/20 overflow-hidden relative max-h-[90vh] flex flex-col"
                            >
                                <div className="flex items-start justify-between mb-6">
                                    <div>
                                        <h3 className="text-2xl font-black text-slate-900 tracking-tight mb-1">Manage Members</h3>
                                        <p className="text-sm text-slate-500 font-medium">
                                            Organization: <span className="text-emerald-600 font-bold">{tenant?.name}</span>
                                        </p>
                                    </div>
                                    <button
                                        onClick={() => { setManagingMembersTenantId(null); setTenantMembers([]); }}
                                        className="p-2 hover:bg-slate-100 rounded-2xl transition-all"
                                    >
                                        <X size={20} className="text-slate-400" />
                                    </button>
                                </div>

                                <div className="flex-1 overflow-y-auto flex flex-col gap-6 pr-1 scrollbar-hide">
                                    {/* Current Members Section */}
                                    <div>
                                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3">
                                            Current Members ({tenantMembers.length})
                                        </h4>
                                        {isMembersLoading ? (
                                            <div className="flex items-center justify-center py-8 opacity-40">
                                                <Loader2 size={24} className="animate-spin" />
                                            </div>
                                        ) : tenantMembers.length === 0 ? (
                                            <div className="py-6 text-center bg-slate-50 rounded-2xl opacity-50">
                                                <User size={28} className="mx-auto mb-2 text-slate-400" />
                                                <p className="text-xs font-bold uppercase tracking-widest text-slate-400">No members yet</p>
                                            </div>
                                        ) : (
                                            <div className="space-y-2">
                                                {tenantMembers.map((m: any) => (
                                                    <div key={m.id || m.userId} className="flex items-center justify-between p-4 bg-slate-50 rounded-2xl border border-slate-200/60">
                                                        <div className="flex items-center gap-3">
                                                            <div className="w-9 h-9 rounded-xl bg-white border border-slate-200 flex items-center justify-center">
                                                                <User size={16} className="text-slate-400" />
                                                            </div>
                                                            <div>
                                                                <p className="text-sm font-black text-slate-900">{m.user?.username || m.userId}</p>
                                                                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{m.role}</p>
                                                            </div>
                                                        </div>
                                                        <button
                                                            onClick={() => handleRemoveMember(managingMembersTenantId, m.userId)}
                                                            className="p-2 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-xl transition-all"
                                                            title="Remove member"
                                                        >
                                                            <Trash2 size={14} />
                                                        </button>
                                                    </div>
                                                ))}
                                            </div>
                                        )}
                                    </div>

                                    {/* Add Users Section */}
                                    <div>
                                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3">Add Users</h4>
                                        <div className="relative mb-3">
                                            <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                                                <User size={16} />
                                            </div>
                                            <input
                                                className="w-full pl-10 pr-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium focus:ring-4 focus:ring-emerald-500/10 focus:border-emerald-500/50 outline-none transition-all"
                                                placeholder="Search users by name..."
                                                value={memberUserSearch}
                                                onChange={e => setMemberUserSearch(e.target.value)}
                                            />
                                        </div>
                                        {availableUsers.length === 0 ? (
                                            <div className="py-6 text-center bg-slate-50 rounded-2xl opacity-50">
                                                <p className="text-xs font-bold uppercase tracking-widest text-slate-400">
                                                    {memberUserSearch ? 'No matching users' : 'All users already added'}
                                                </p>
                                            </div>
                                        ) : (
                                            <div className="space-y-2 max-h-[220px] overflow-y-auto scrollbar-hide">
                                                {availableUsers.map(u => (
                                                    <button
                                                        key={u.id}
                                                        onClick={() => handleAddMember(managingMembersTenantId, u.id)}
                                                        className="w-full flex items-center justify-between p-4 bg-slate-50/50 hover:bg-emerald-50 border border-slate-200/50 hover:border-emerald-200 rounded-2xl transition-all group"
                                                    >
                                                        <div className="flex items-center gap-3">
                                                            <div className="w-9 h-9 rounded-xl bg-white border border-slate-200 flex items-center justify-center group-hover:text-emerald-600 transition-all">
                                                                <User size={16} className="text-slate-400 group-hover:text-emerald-600" />
                                                            </div>
                                                            <div className="text-left">
                                                                <p className="text-sm font-black text-slate-900">{u.username}</p>
                                                                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{u.role || 'User'}</p>
                                                            </div>
                                                        </div>
                                                        <div className="flex items-center gap-1.5 px-3 py-1 bg-emerald-50 group-hover:bg-emerald-100 text-emerald-700 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all">
                                                            <Plus size={12} />
                                                            Add
                                                        </div>
                                                    </button>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                </div>

                                <div className="pt-6 border-t border-slate-100 flex justify-end mt-4">
                                    <button
                                        onClick={() => { setManagingMembersTenantId(null); setTenantMembers([]); }}
                                        className="px-6 py-3 text-sm font-bold text-slate-500 hover:text-slate-700 transition-all"
                                    >
                                        Done
                                    </button>
                                </div>
                            </motion.div>
                        </div>
                    );
                })()}
            </AnimatePresence>
        </div>
    );
    const renderKnowledgeBaseTab = () => (
        <div className="space-y-8 animate-in slide-in-from-right duration-300 w-full max-w-5xl pb-10">
            {localKbSettings && (
                <>
                    {/* Save/Cancel Bar */}
                    <div className="flex justify-end gap-3 sticky top-0 z-20 py-4 bg-white/50 backdrop-blur-sm border-b border-slate-100 mb-6">
                        <button
                            onClick={handleCancelKbSettings}
                            disabled={isSavingKbSettings || JSON.stringify(localKbSettings) === JSON.stringify(kbSettings)}
                            className="px-6 py-2 text-sm font-bold text-slate-500 hover:text-slate-700 disabled:opacity-30"
                        >
                            {t('cancel')}
                        </button>
                        <button
                            onClick={handleSaveKbSettings}
                            disabled={isSavingKbSettings || JSON.stringify(localKbSettings) === JSON.stringify(kbSettings)}
                            className="flex items-center gap-2 px-8 py-2 bg-indigo-600 text-white text-sm font-black uppercase tracking-widest rounded-2xl hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all active:scale-95 disabled:opacity-50"
                        >
                            {isSavingKbSettings ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
                            {t('saveChanges')}
                        </button>
                    </div>

                    {/* Model Configuration */}
                    <section className="bg-white/80 backdrop-blur-md p-8 rounded-3xl border border-slate-200/50 shadow-sm space-y-6">
                        <div className="flex items-center gap-3 text-slate-900 font-black uppercase tracking-widest text-[11px] border-b border-slate-100 pb-4">
                            <div className="w-8 h-8 rounded-xl bg-indigo-50 flex items-center justify-center text-indigo-600">
                                <Cpu size={16} />
                            </div>
                            {t('modelConfiguration')}
                        </div>
                        <div className="grid grid-cols-1 gap-6">
                            <div>
                                <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 px-1">{t('defaultLLMModel')}</label>
                                <select
                                    value={localKbSettings.selectedLLMId || ''}
                                    onChange={(e) => handleUpdateKbSettings('selectedLLMId', e.target.value)}
                                    className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium outline-none focus:ring-4 focus:ring-indigo-500/10 transition-all cursor-pointer appearance-none"
                                >
                                    <option value="">{t('selectLLM')}</option>
                                    {models.filter(m => m.type === ModelType.LLM).map(m => (
                                        <option key={m.id} value={m.id}>{m.name} ({m.modelId})</option>
                                    ))}
                                </select>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 px-1">{t('embeddingModel')}</label>
                                    <select
                                        value={localKbSettings.selectedEmbeddingId || ''}
                                        onChange={(e) => handleUpdateKbSettings('selectedEmbeddingId', e.target.value)}
                                        className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium outline-none focus:ring-4 focus:ring-indigo-500/10 transition-all"
                                    >
                                        <option value="">{t('selectEmbedding')}</option>
                                        {models.filter(m => m.type === ModelType.EMBEDDING).map(m => (
                                            <option key={m.id} value={m.id}>{m.name}</option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 px-1">{t('rerankModel')}</label>
                                    <select
                                        value={localKbSettings.selectedRerankId || ''}
                                        onChange={(e) => handleUpdateKbSettings('selectedRerankId', e.target.value)}
                                        className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium outline-none focus:ring-4 focus:ring-indigo-500/10 transition-all"
                                    >
                                        <option value="">{t('none')}</option>
                                        {models.filter(m => m.type === ModelType.RERANK).map(m => (
                                            <option key={m.id} value={m.id}>{m.name}</option>
                                        ))}
                                    </select>
                                </div>
                            </div>
                        </div>
                    </section>

                    {/* Indexing & Chunking Configuration */}
                    <section className="bg-white/80 backdrop-blur-md p-8 rounded-3xl border border-slate-200/50 shadow-sm space-y-6">
                        <div className="flex items-center gap-3 text-slate-900 font-black uppercase tracking-widest text-[11px] border-b border-slate-100 pb-4">
                            <div className="w-8 h-8 rounded-xl bg-orange-50 flex items-center justify-center text-orange-600">
                                <BookOpen size={16} />
                            </div>
                            {t('indexingChunkingConfig')}
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                            <div>
                                <div className="flex justify-between mb-3 px-1">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t('chunkSize')}</label>
                                    <span className="text-sm font-black text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-lg">{localKbSettings.chunkSize || 1000}</span>
                                </div>
                                <input
                                    type="range"
                                    min="100"
                                    max="8192"
                                    step="100"
                                    value={localKbSettings.chunkSize || 1000}
                                    onChange={(e) => handleUpdateKbSettings('chunkSize', parseInt(e.target.value))}
                                    className="w-full h-2 bg-slate-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                />
                            </div>
                            <div>
                                <div className="flex justify-between mb-3 px-1">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t('chunkOverlap')}</label>
                                    <span className="text-sm font-black text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-lg">{localKbSettings.chunkOverlap || 100}</span>
                                </div>
                                <input
                                    type="range"
                                    min="0"
                                    max="2048"
                                    step="10"
                                    value={localKbSettings.chunkOverlap || 100}
                                    onChange={(e) => handleUpdateKbSettings('chunkOverlap', parseInt(e.target.value))}
                                    className="w-full h-2 bg-slate-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                />
                            </div>
                        </div>
                    </section >

                    {/* Chat Hyperparameters */}
                    < section className="bg-white/80 backdrop-blur-md p-8 rounded-3xl border border-slate-200/50 shadow-sm space-y-6" >
                        <div className="flex items-center gap-3 text-slate-900 font-black uppercase tracking-widest text-[11px] border-b border-slate-100 pb-4">
                            <div className="w-8 h-8 rounded-xl bg-pink-50 flex items-center justify-center text-pink-600">
                                <Sparkles size={16} />
                            </div>
                            {t('chatHyperparameters')}
                        </div>
                        <div className="space-y-8">
                            <div>
                                <div className="flex justify-between mb-3 px-1">
                                    <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t('temperature')}</label>
                                    <span className="text-sm font-black text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-lg">{localKbSettings.temperature}</span>
                                </div>
                                <input
                                    type="range"
                                    min="0"
                                    max="1"
                                    step="0.1"
                                    value={localKbSettings.temperature || 0.7}
                                    onChange={(e) => handleUpdateKbSettings('temperature', parseFloat(e.target.value))}
                                    className="w-full h-2 bg-slate-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                />
                                <div className="flex justify-between mt-2 px-1 text-[9px] font-bold text-slate-300 uppercase tracking-tighter">
                                    <span>{t('precise')}</span>
                                    <span>{t('creative')}</span>
                                </div>
                            </div>
                            <div>
                                <label className="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 px-1">{t('maxResponseTokens')}</label>
                                <input
                                    type="number"
                                    value={localKbSettings.maxTokens || 2000}
                                    onChange={(e) => handleUpdateKbSettings('maxTokens', parseInt(e.target.value))}
                                    className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium outline-none focus:ring-4 focus:ring-indigo-500/10 transition-all"
                                />
                            </div>
                        </div>
                    </section >

                    {/* Retrieval & Search Settings */}
                    < section className="bg-white/80 backdrop-blur-md p-8 rounded-3xl border border-slate-200/50 shadow-sm space-y-6" >
                        <div className="flex items-center gap-3 text-slate-900 font-black uppercase tracking-widest text-[11px] border-b border-slate-100 pb-4">
                            <div className="w-8 h-8 rounded-xl bg-emerald-50 flex items-center justify-center text-emerald-600">
                                <Database size={16} />
                            </div>
                            {t('retrievalSearchSettings')}
                        </div>
                        <div className="space-y-8">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                <div>
                                    <div className="flex justify-between mb-3 px-1">
                                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t('topK')}</label>
                                        <span className="text-sm font-black text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-lg">{localKbSettings.topK}</span>
                                    </div>
                                    <input
                                        type="range"
                                        min="1"
                                        max="50"
                                        step="1"
                                        value={localKbSettings.topK || 10}
                                        onChange={(e) => handleUpdateKbSettings('topK', parseInt(e.target.value))}
                                        className="w-full h-2 bg-slate-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                    />
                                </div>
                                <div>
                                    <div className="flex justify-between mb-3 px-1">
                                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{t('similarityThreshold')}</label>
                                        <span className="text-sm font-black text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-lg">{localKbSettings.similarityThreshold}</span>
                                    </div>
                                    <input
                                        type="range"
                                        min="0"
                                        max="1"
                                        step="0.05"
                                        value={localKbSettings.similarityThreshold || 0.5}
                                        onChange={(e) => handleUpdateKbSettings('similarityThreshold', parseFloat(e.target.value))}
                                        className="w-full h-2 bg-slate-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                    />
                                </div>
                            </div>

                            <div className="space-y-4 pt-4 border-t border-slate-100">
                                <div className="flex items-center justify-between p-5 bg-slate-50/50 rounded-2xl border border-slate-200/30 transition-all hover:bg-white hover:border-indigo-100">
                                    <div>
                                        <div className="text-sm font-bold text-slate-800">{t('enableHybridSearch')}</div>
                                        <div className="text-[10px] text-slate-400 font-medium">{t('hybridSearchDesc')}</div>
                                    </div>
                                    <button
                                        onClick={() => handleUpdateKbSettings('enableFullTextSearch', !localKbSettings.enableFullTextSearch)}
                                        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-all duration-300 ${localKbSettings.enableFullTextSearch ? 'bg-indigo-600 shadow-md shadow-indigo-100' : 'bg-slate-300'}`}
                                    >
                                        <span className={`${localKbSettings.enableFullTextSearch ? 'translate-x-6' : 'translate-x-1'} inline-block h-4 w-4 transform rounded-full bg-white transition-transform`} />
                                    </button>
                                </div>

                                {localKbSettings.enableFullTextSearch && (
                                    <motion.div
                                        initial={{ opacity: 0, y: -10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        className="p-5 bg-indigo-50/30 rounded-2xl border border-indigo-100/50 space-y-4"
                                    >
                                        <div className="flex justify-between mb-2 px-1">
                                            <label className="text-[10px] font-black text-indigo-400 uppercase tracking-widest">{t('hybridWeight')}</label>
                                            <span className="text-sm font-black text-indigo-600">{localKbSettings.hybridVectorWeight || 0.5}</span>
                                        </div>
                                        <input
                                            type="range"
                                            min="0"
                                            max="1"
                                            step="0.05"
                                            value={localKbSettings.hybridVectorWeight || 0.5}
                                            onChange={(e) => handleUpdateKbSettings('hybridVectorWeight', parseFloat(e.target.value))}
                                            className="w-full h-2 bg-indigo-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                        />
                                        <div className="flex justify-between mt-1 px-1 text-[9px] font-bold text-indigo-300 uppercase">
                                            <span>{t('pureText')}</span>
                                            <span>{t('pureVector')}</span>
                                        </div>
                                    </motion.div>
                                )}

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="flex items-center justify-between p-5 bg-slate-50/50 rounded-2xl border border-slate-200/30 transition-all hover:bg-white hover:border-indigo-100">
                                        <div>
                                            <div className="text-sm font-bold text-slate-800">{t('enableQueryExpansion')}</div>
                                            <div className="text-[10px] text-slate-400 font-medium">{t('queryExpansionDesc')}</div>
                                        </div>
                                        <button
                                            onClick={() => handleUpdateKbSettings('enableQueryExpansion', !localKbSettings.enableQueryExpansion)}
                                            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-all duration-300 ${localKbSettings.enableQueryExpansion ? 'bg-indigo-600 shadow-md shadow-indigo-100' : 'bg-slate-300'}`}
                                        >
                                            <span className={`${localKbSettings.enableQueryExpansion ? 'translate-x-6' : 'translate-x-1'} inline-block h-4 w-4 transform rounded-full bg-white transition-transform`} />
                                        </button>
                                    </div>

                                    <div className="flex items-center justify-between p-5 bg-slate-50/50 rounded-2xl border border-slate-200/30 transition-all hover:bg-white hover:border-indigo-100">
                                        <div>
                                            <div className="text-sm font-bold text-slate-800">{t('enableHyDE')}</div>
                                            <div className="text-[10px] text-slate-400 font-medium">{t('hydeDesc')}</div>
                                        </div>
                                        <button
                                            onClick={() => handleUpdateKbSettings('enableHyDE', !localKbSettings.enableHyDE)}
                                            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-all duration-300 ${localKbSettings.enableHyDE ? 'bg-indigo-600 shadow-md shadow-indigo-100' : 'bg-slate-300'}`}
                                        >
                                            <span className={`${localKbSettings.enableHyDE ? 'translate-x-6' : 'translate-x-1'} inline-block h-4 w-4 transform rounded-full bg-white transition-transform`} />
                                        </button>
                                    </div>
                                </div>

                                <div className="flex items-center justify-between p-5 bg-slate-50/50 rounded-2xl border border-slate-200/30 transition-all hover:bg-white hover:border-indigo-100">
                                    <div>
                                        <div className="text-sm font-bold text-slate-800">{t('enableReranking')}</div>
                                        <div className="text-[10px] text-slate-400 font-medium">{t('rerankingDesc')}</div>
                                    </div>
                                    <button
                                        onClick={() => handleUpdateKbSettings('enableRerank', !localKbSettings.enableRerank)}
                                        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-all duration-300 ${localKbSettings.enableRerank ? 'bg-indigo-600 shadow-md shadow-indigo-100' : 'bg-slate-300'}`}
                                    >
                                        <span className={`${localKbSettings.enableRerank ? 'translate-x-6' : 'translate-x-1'} inline-block h-4 w-4 transform rounded-full bg-white transition-transform`} />
                                    </button>
                                </div>

                                {localKbSettings.enableRerank && (
                                    <motion.div
                                        initial={{ opacity: 0, y: -10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        className="p-5 bg-indigo-50/30 rounded-2xl border border-indigo-100/50 space-y-4"
                                    >
                                        <div className="flex justify-between mb-2 px-1">
                                            <label className="text-[10px] font-black text-indigo-400 uppercase tracking-widest">{t('rerankSimilarityThreshold')}</label>
                                            <span className="text-sm font-black text-indigo-600">{localKbSettings.rerankSimilarityThreshold || 0.5}</span>
                                        </div>
                                        <input
                                            type="range"
                                            min="0"
                                            max="1"
                                            step="0.05"
                                            value={localKbSettings.rerankSimilarityThreshold || 0.5}
                                            onChange={(e) => handleUpdateKbSettings('rerankSimilarityThreshold', parseFloat(e.target.value))}
                                            className="w-full h-2 bg-indigo-100 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                        />
                                        <div className="flex justify-between mt-1 px-1 text-[9px] font-bold text-indigo-300 uppercase">
                                            <span>{t('broad')}</span>
                                            <span>{t('strict')}</span>
                                        </div>
                                    </motion.div>
                                )}
                            </div>
                        </div>
                    </section>
                </>
            )}
        </div>
    );

    const renderModelTab = () => (
        <div className="w-full space-y-6">
            <div className="flex justify-between items-center mb-6">
                <div>
                    <h3 className="text-sm font-black text-slate-500 uppercase tracking-[0.15em] mb-1">{t('mmTitle')}</h3>
                    <p className="text-xs text-slate-400 font-medium">{t('sidebarDesc')}</p>
                </div>
                {!editingId && currentUser?.role === 'SUPER_ADMIN' && (
                    <button
                        onClick={() => { setEditingId('new'); setModelFormData({ type: ModelType.LLM, baseUrl: 'http://localhost:11434/v1', modelId: 'llama3', name: '', dimensions: 1536 }); }}
                        className="flex items-center gap-2 px-6 py-2.5 bg-indigo-600 text-white text-sm font-bold rounded-2xl hover:bg-indigo-700 shadow-lg shadow-indigo-100 transition-all active:scale-95"
                    >
                        <Plus className="w-4 h-4" />
                        {t('mmAddBtn')}
                    </button>
                )}
            </div>

            {editingId ? (
                <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="bg-white/90 backdrop-blur-md p-10 rounded-3xl border border-slate-200/50 shadow-xl space-y-8"
                >
                    <div className="flex items-center gap-4 mb-2">
                        <div className="w-12 h-12 rounded-2xl bg-indigo-50 flex items-center justify-center text-indigo-600">
                            <Cpu className="w-6 h-6" />
                        </div>
                        <h3 className="text-xl font-black text-slate-900 tracking-tight">{editingId === 'new' ? t('mmAddBtn') : t('mmEdit')}</h3>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('mmFormName')} *</label>
                            <input className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all" value={modelFormData.name || ''} onChange={e => setModelFormData({ ...modelFormData, name: e.target.value })} disabled={isLoading} />
                        </div>
                        <div className="space-y-2">
                            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('mmFormModelId')} *</label>
                            <input className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-mono focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all" value={modelFormData.modelId || ''} onChange={e => setModelFormData({ ...modelFormData, modelId: e.target.value })} disabled={isLoading} />
                        </div>
                    </div>

                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('mmFormType')} *</label>
                        <select className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-medium focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all appearance-none" value={modelFormData.type} onChange={e => setModelFormData({ ...modelFormData, type: e.target.value as ModelType })} disabled={isLoading}>
                            <option value={ModelType.LLM}>{t('typeLLM')}</option>
                            <option value={ModelType.EMBEDDING}>{t('typeEmbedding')}</option>
                            <option value={ModelType.RERANK}>{t('typeRerank')}</option>
                            <option value={ModelType.VISION}>{t('typeVision')}</option>
                        </select>
                    </div>

                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('mmFormBaseUrl')} *</label>
                        <input className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-mono focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all" value={modelFormData.baseUrl || ''} onChange={e => setModelFormData({ ...modelFormData, baseUrl: e.target.value })} disabled={isLoading} />
                    </div>

                    <div className="space-y-2">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('mmFormApiKey')}</label>
                        <input
                            type="password"
                            className="w-full px-4 py-3.5 bg-slate-50 border border-slate-200 rounded-2xl text-sm font-mono focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500/50 outline-none transition-all"
                            value={modelFormData.apiKey || ''}
                            onChange={e => setModelFormData({ ...modelFormData, apiKey: e.target.value })}
                            disabled={isLoading}
                            placeholder={t('mmFormApiKeyPlaceholder')}
                        />
                    </div>

                    {modelFormData.type === ModelType.EMBEDDING && (
                        <div className="grid grid-cols-2 gap-6 p-6 bg-slate-50 rounded-3xl border border-slate-200/50">
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('maxInput')}</label>
                                <input type="number" className="w-full px-4 py-3 bg-white border border-slate-200 rounded-xl text-sm font-bold" value={modelFormData.maxInputTokens || 8191} onChange={e => setModelFormData({ ...modelFormData, maxInputTokens: parseInt(e.target.value) })} />
                            </div>
                            <div className="space-y-2">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">{t('dimensions')}</label>
                                <input type="number" className="w-full px-4 py-3 bg-white border border-slate-200 rounded-xl text-sm font-bold" value={modelFormData.dimensions || 1536} onChange={e => setModelFormData({ ...modelFormData, dimensions: parseInt(e.target.value) })} />
                            </div>
                        </div>
                    )}

                    <div className="flex justify-end gap-3 pt-4">
                        <button onClick={() => { setEditingId(null); setError(null); }} className="px-6 py-3 text-sm font-bold text-slate-500 hover:text-slate-700">{t('mmCancel')}</button>
                        <button onClick={handleSaveModel} className="px-10 py-3 bg-indigo-600 text-white rounded-2xl font-black uppercase tracking-widest text-xs shadow-xl shadow-indigo-100 transition-all active:scale-95 flex items-center gap-2" disabled={isLoading}>
                            {isLoading && <Loader2 className="w-4 h-4 animate-spin" />}
                            {t('mmSave')}
                        </button>
                    </div>
                </motion.div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-5 overflow-y-auto pr-2 pb-6 scrollbar-hide">
                    <AnimatePresence>
                        {models.map((model, index) => (
                            <motion.div
                                key={model.id}
                                initial={{ opacity: 0, scale: 0.95 }}
                                animate={{ opacity: 1, scale: 1 }}
                                transition={{ delay: index * 0.05 }}
                                className="bg-white/70 backdrop-blur-md border border-slate-200/50 rounded-[2rem] p-6 flex flex-col justify-between group hover:shadow-xl hover:shadow-indigo-500/5 hover:border-indigo-500/30 transition-all duration-300 relative overflow-hidden"
                            >
                                {/* Subtle background pattern/glow */}
                                <div className="absolute -top-12 -right-12 w-32 h-32 bg-indigo-500/5 rounded-full blur-3xl group-hover:bg-indigo-500/10 transition-all duration-500" />

                                <div className="relative z-10">
                                    <div className="flex items-start justify-between mb-5">
                                        <div className={`w-14 h-14 rounded-2xl flex items-center justify-center transition-all duration-500 ${model.isEnabled !== false ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-100 rotate-0 group-hover:rotate-6' : 'bg-slate-100 text-slate-400 opacity-60'}`}>
                                            <Cpu size={26} strokeWidth={2.5} />
                                        </div>
                                        <div className="flex gap-1 items-center bg-slate-50 p-1 rounded-xl border border-slate-100/50">
                                            <button
                                                onClick={() => handleToggleModel(model)}
                                                className={`p-1.5 rounded-lg transition-all ${((currentUser?.role === 'SUPER_ADMIN' ? !!model.isEnabled : enabledModelIds.includes(model.id))) ? 'text-indigo-600 bg-white shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}
                                                title={((currentUser?.role === 'SUPER_ADMIN' ? !!model.isEnabled : enabledModelIds.includes(model.id))) ? t('modelEnabled') : t('modelDisabled')}
                                            >
                                                {((currentUser?.role === 'SUPER_ADMIN' ? !!model.isEnabled : enabledModelIds.includes(model.id))) ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}
                                            </button>
                                        </div>
                                    </div>

                                    <div className="space-y-1 mb-6">
                                        <div className="flex items-center gap-2.5">
                                            <h4 className="font-black text-slate-900 text-lg tracking-tight truncate">{model.name}</h4>
                                        </div>
                                        <div className="flex items-center gap-2">
                                            <span className="text-[9px] font-black bg-indigo-50 text-indigo-600 px-2 py-0.5 rounded-lg uppercase tracking-wider border border-indigo-100/50">
                                                {getTypeLabel(model.type)}
                                            </span>
                                            {model.isDefault && (
                                                <span className="text-[9px] font-black bg-amber-50 text-amber-600 px-2 py-0.5 rounded-lg uppercase tracking-wider border border-amber-100/50 flex items-center gap-1">
                                                    <Sparkles size={8} /> {t('defaultBadge')}
                                                </span>
                                            )}
                                        </div>
                                        <p className="text-[11px] font-mono text-slate-400 mt-2 truncate bg-slate-50 px-2 py-1 rounded-lg border border-slate-100/50 inline-block max-w-full">
                                            {model.modelId}
                                        </p>
                                    </div>

                                    {/* Additional info grid */}
                                    <div className="grid grid-cols-2 gap-3 mb-6">
                                        {model.type === ModelType.EMBEDDING && (
                                            <>
                                                <div className="bg-slate-50/50 p-2.5 rounded-2xl border border-slate-100/50">
                                                    <span className="block text-[8px] font-black text-slate-400 uppercase tracking-widest mb-0.5">{t('dims')}</span>
                                                    <span className="text-xs font-bold text-slate-700">{model.dimensions || '-'}</span>
                                                </div>
                                                <div className="bg-slate-50/50 p-2.5 rounded-2xl border border-slate-100/50">
                                                    <span className="block text-[8px] font-black text-slate-400 uppercase tracking-widest mb-0.5">{t('ctx')}</span>
                                                    <span className="text-xs font-bold text-slate-700">{model.maxInputTokens || '-'}</span>
                                                </div>
                                            </>
                                        )}
                                        {model.type === ModelType.LLM && (
                                            <div className="col-span-2 bg-slate-50/50 p-2.5 rounded-2xl border border-slate-100/50 flex items-center justify-between">
                                                <span className="text-[8px] font-black text-slate-400 uppercase tracking-widest">{t('baseApi')}</span>
                                                <span className="text-[9px] font-mono font-medium text-slate-600 max-w-[140px] truncate">{model.baseUrl}</span>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                <div className="flex items-center justify-between pt-4 border-t border-slate-100/50 relative z-10">
                                    <div className="flex items-center gap-1 text-[10px] font-bold text-slate-400">
                                        <SettingsIcon size={12} />
                                        {t('configured')}
                                    </div>
                                    <div className="flex gap-2">
                                        {currentUser?.role === 'SUPER_ADMIN' && (
                                            <>
                                                <button
                                                    onClick={() => { setEditingId(model.id); setModelFormData({ ...model }); }}
                                                    className="w-9 h-9 flex items-center justify-center rounded-xl bg-slate-50 text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 hover:shadow-sm transition-all"
                                                >
                                                    <Edit2 size={15} />
                                                </button>
                                                <button
                                                    onClick={() => handleDeleteModel(model.id)}
                                                    className="w-9 h-9 flex items-center justify-center rounded-xl bg-slate-50 text-slate-400 hover:text-red-500 hover:bg-red-50 hover:shadow-sm transition-all"
                                                >
                                                    <Trash2 size={15} />
                                                </button>
                                            </>
                                        )}
                                    </div>
                                </div>
                            </motion.div>
                        ))}
                    </AnimatePresence>

                    {models.length === 0 && (
                        <div className="bg-white/50 border-2 border-dashed border-slate-200 rounded-3xl p-16 text-center">
                            <Cpu className="w-12 h-12 text-slate-200 mx-auto mb-4" />
                            <p className="text-slate-400 font-bold uppercase tracking-widest text-xs">{t('mmEmpty')}</p>
                        </div>
                    )}
                </div>
            )}
        </div>
    );

    return (
        <div className="flex h-full bg-[#FCFDFF] overflow-hidden relative">
            {/* Settings Sidebar */}
            <div className="w-64 bg-slate-50/50 border-r border-slate-200/60 flex flex-col shrink-0 z-20">
                <div className="p-6 pb-2">
                    <h2 className="text-lg font-bold text-slate-900 tracking-tight">{t('tabSettings')}</h2>
                </div>
                <div className="flex-1 overflow-y-auto p-3 space-y-1">
                    <button
                        onClick={() => setActiveTab('general')}
                        className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${activeTab === 'general' ? 'bg-white text-indigo-600 shadow-sm border border-slate-200/60' : 'text-slate-600 hover:bg-slate-100'
                            }`}
                    >
                        <SettingsIcon size={18} />
                        {t('generalSettings')}
                    </button>
                    {(currentUser?.role === 'TENANT_ADMIN' || currentUser?.role === 'SUPER_ADMIN' || isAdmin) && (
                        <>
                            <button
                                onClick={() => setActiveTab('user')}
                                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${activeTab === 'user' ? 'bg-white text-indigo-600 shadow-sm border border-slate-200/60' : 'text-slate-600 hover:bg-slate-100'
                                    }`}
                            >
                                <UserCircle size={18} />
                                {t('userManagement')}
                            </button>
                            <button
                                onClick={() => setActiveTab('model')}
                                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${activeTab === 'model' ? 'bg-white text-indigo-600 shadow-sm border border-slate-200/60' : 'text-slate-600 hover:bg-slate-100'
                                    }`}
                            >
                                <HardDrive size={18} />
                                {t('modelManagement')}
                            </button>
                            <button
                                onClick={() => setActiveTab('knowledge_base')}
                                className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${activeTab === 'knowledge_base' ? 'bg-white text-indigo-600 shadow-sm border border-slate-200/60' : 'text-slate-600 hover:bg-slate-100'
                                    }`}
                            >
                                <Database size={18} />
                                {t('sidebarTitle')}
                            </button>
                        </>
                    )}
                    {currentUser?.role === 'SUPER_ADMIN' && (
                        <button
                            onClick={() => setActiveTab('tenants')}
                            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${activeTab === 'tenants' ? 'bg-white text-indigo-600 shadow-sm border border-slate-200/60' : 'text-slate-600 hover:bg-slate-100'
                                }`}
                        >
                            <LayoutGrid size={18} />
                            {t('navTenants')}
                        </button>
                    )}
                </div>
            </div>

            {/* Content Area */}
            <div className="flex-1 flex flex-col min-w-0 h-full overflow-hidden relative bg-white z-10">
                <div className="px-8 pt-8 pb-6 flex items-start justify-between shrink-0">
                    <div>
                        <h1 className="text-2xl font-bold text-slate-900 leading-tight">
                            {activeTab === 'general' ? t('generalSettings') : activeTab === 'user' ? t('userManagement') : activeTab === 'model' ? t('modelManagement') : activeTab === 'knowledge_base' ? t('sidebarTitle') : t('navTenants')}
                        </h1>
                        <p className="text-[15px] text-slate-500 mt-1">
                            {activeTab === 'general' ? t('generalSettingsSubtitle') : activeTab === 'user' ? t('userManagementSubtitle') : activeTab === 'model' ? t('modelManagementSubtitle') : activeTab === 'knowledge_base' ? t('kbSettingsSubtitle') : t('tenantsSubtitle')}
                        </p>
                    </div>
                </div>

                <div className="flex-1 overflow-y-auto px-10 pb-10 scrollbar-hide">
                    <div className="w-full">
                        {error && (
                            <motion.div
                                initial={{ opacity: 0, y: -10 }}
                                animate={{ opacity: 1, y: 0 }}
                                className="mb-8 p-4 bg-red-50/80 backdrop-blur-md border border-red-200/50 text-red-700 rounded-2xl flex gap-3 items-center text-sm shadow-sm"
                            >
                                <div className="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center shrink-0">
                                    <X className="w-4 h-4 text-red-600" />
                                </div>
                                <div>
                                    <span className="font-black uppercase tracking-widest text-[10px] block mb-0.5">{t('errorLabel')}</span>
                                    {error}
                                </div>
                            </motion.div>
                        )}

                        <AnimatePresence mode="wait">
                            <motion.div
                                key={activeTab}
                                initial={{ opacity: 0, x: 20 }}
                                animate={{ opacity: 1, x: 0 }}
                                exit={{ opacity: 0, x: -20 }}
                                transition={{ duration: 0.3 }}
                            >
                                {activeTab === 'general' && renderGeneralTab()}
                                {activeTab === 'user' && renderUserTab()}
                                {activeTab === 'model' && (isAdmin || currentUser?.role === 'SUPER_ADMIN') && renderModelTab()}
                                {activeTab === 'knowledge_base' && (isAdmin || currentUser?.role === 'SUPER_ADMIN') && renderKnowledgeBaseTab()}
                                {activeTab === 'tenants' && currentUser?.role === 'SUPER_ADMIN' && renderTenantsTab()}
                            </motion.div>
                        </AnimatePresence>
                    </div>
                </div>
            </div>
        </div>
    );
};
