import React, { useState, useRef, useEffect } from 'react'; import { useUsers, useWorkspaces, type User, api, useWorkspace } from '@nexus/shared'; import { MoreHorizontal, Edit3, Trash2, AlertCircle, RefreshCcw, Shield, Palette, Image } from 'lucide-react'; import styles from './WorkspaceSettings.module.css'; interface WorkspaceSettingsProps { workspaceId?: string; } export const WorkspaceSettings: React.FC = ({ workspaceId }) => { const { users, loading: usersLoading, addUser, updateUser, deleteUser, refresh } = useUsers(workspaceId); const { workspaces, refresh: refreshWorkspaces } = useWorkspaces(); const { workspace: freshWorkspace, refresh: refreshActiveWs } = useWorkspace(workspaceId); const [isModalOpen, setIsModalOpen] = useState(false); const [formData, setFormData] = useState({ email: '', fullName: '', role: '3sc_agent', team: 'SUCCESS', password: 'TemporaryPassword123!' }); const [formError, setFormError] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const [activeMenuId, setActiveMenuId] = useState(null); const [editingUser, setEditingUser] = useState(null); const [deletingUser, setDeletingUser] = useState(null); const menuRef = useRef(null); // Branding State const [brandingLogo, setBrandingLogo] = useState(''); const [brandingColor, setBrandingColor] = useState('#7c3aed'); const [isBrandingSubmitting, setIsBrandingSubmitting] = useState(false); const currentWorkspace = (freshWorkspace?.id === workspaceId) ? freshWorkspace : (workspaces.find(w => w.id === workspaceId) || workspaces[0]); useEffect(() => { if (currentWorkspace?.branding) { setBrandingLogo(currentWorkspace.branding.logo_url || ''); setBrandingColor(currentWorkspace.branding.colors?.primary || '#7c3aed'); } }, [currentWorkspace]); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (menuRef.current && !menuRef.current.contains(event.target as Node)) { setActiveMenuId(null); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); const handleUpdateBranding = async () => { if (!currentWorkspace) return; setIsBrandingSubmitting(true); // OPTIMISTIC UI: Inject CSS variables immediately for "Instant" feel document.documentElement.style.setProperty('--primary', brandingColor); // Auto-calculate hover/accent colors based on primary document.documentElement.style.setProperty('--primary-hover', brandingColor + 'ee'); try { await api.patch('/workspace/', { workspace_id: workspaceId, branding: { ...currentWorkspace.branding, logo_url: brandingLogo, colors: { ...currentWorkspace.branding?.colors, primary: brandingColor } } }); // Invalidate caches sessionStorage.removeItem('nexus_active_ws_v1'); await refreshActiveWs(workspaceId); await refreshWorkspaces(); } catch (err) { console.error("Failed to update branding:", err); } finally { setIsBrandingSubmitting(false); } }; const handleAddMember = async (e: React.FormEvent) => { e.preventDefault(); setIsSubmitting(true); setFormError(null); try { await addUser({ email: formData.email, full_name: formData.fullName, role: formData.role, team: formData.team, password: formData.password, workspace_id: workspaceId // Force explicit targeting }); setIsModalOpen(false); setFormData({ email: '', fullName: '', role: '3sc_agent', team: 'SUCCESS', password: 'TemporaryPassword123!' }); } catch (err: any) { setFormError(err.message); } finally { setIsSubmitting(false); } }; const handleUpdateMember = async (e: React.FormEvent) => { e.preventDefault(); if (!editingUser) return; setIsSubmitting(true); setFormError(null); try { await updateUser(editingUser.id, { full_name: editingUser.full_name, role: editingUser.role, team: editingUser.team }); setEditingUser(null); } catch (err: any) { setFormError(err.message); } finally { setIsSubmitting(false); } }; const handleDeleteMember = async () => { if (!deletingUser) return; setIsSubmitting(true); try { await deleteUser(deletingUser.id); setDeletingUser(null); } catch (err: any) { alert("Failed to remove member: " + err.message); } finally { setIsSubmitting(false); } }; const THEME_PRESETS = [ { name: 'Nexus Violet', color: '#7c3aed' }, { name: 'Royal Indigo', color: '#4338ca' }, { name: 'Ocean Blue', color: '#3b82f6' }, { name: 'Emerald Green', color: '#10b981' }, { name: 'Slate Steel', color: '#475569' }, { name: 'Crimson Red', color: '#ef4444' }, { name: 'Amber Glow', color: '#f59e0b' }, { name: 'Deep Rose', color: '#e11d48' }, ]; return (

{workspaceId === 'all' ? 'System-Wide Directory' : (currentWorkspace?.name || 'Workspace Settings')}

{workspaceId === 'all' ? 'Unified view of all internal staff and cross-workspace members. Manage global access and system-level permissions.' : "Manage your organization's identity, team, and security settings. Use this panel to control access and oversee your dedicated support environment."}

{workspaceId !== 'all' && currentWorkspace && (

Identity & Branding

setBrandingLogo(e.target.value)} placeholder="https://example.com/logo.png" />
{brandingLogo ? ( Logo ) : ( )}
{THEME_PRESETS.map(preset => (
{ setBrandingColor(e.target.value); document.documentElement.style.setProperty('--primary', e.target.value); }} /> { setBrandingColor(e.target.value); if (e.target.value.startsWith('#') && e.target.value.length === 7) { document.documentElement.style.setProperty('--primary', e.target.value); } }} />
Changes propagate across customer and internal portals immediately.
)}

Workspace Team

{usersLoading && users.length === 0 ? ( ) : users.length === 0 ? ( ) : ( users.map(user => ( )) )}
Member Role Team Status
Synchronizing team data...
No members found in this workspace.
{(user.full_name?.slice(0,1) || user.email?.slice(0,1) || '?').toUpperCase()}
{user.full_name} {user.email}
{user.role.replace('_', ' ')} {user.team || '—'}
Active Member
{activeMenuId === user.id && (
)}
{/* Add Member Modal */} {isModalOpen && (
setIsModalOpen(false)}>
e.stopPropagation()}>

Add Team Member

Grant workspace access to a new team member.

setFormData({...formData, fullName: e.target.value})} />
setFormData({...formData, email: e.target.value})} />
{formError &&
{formError}
}
)} {/* Edit Member Modal */} {editingUser && (
setEditingUser(null)}>
e.stopPropagation()}>

Edit Team Member

Update details for {editingUser.email}

setEditingUser({...editingUser, full_name: e.target.value})} />
{formError &&
{formError}
}
)} {/* Delete Confirmation Modal */} {deletingUser && (
setDeletingUser(null)}>
e.stopPropagation()}>

Remove Access?

Are you sure you want to revoke access for {deletingUser.full_name} ({deletingUser.email})? They will be immediately removed from the workspace.

)}
); };