import React, { useState, useEffect } from 'react'; import { useAuth, api, getWsUrl, getStorageKey } from '@nexus/shared'; import styles from './TopBar.module.css'; interface TopBarProps { title: string; subtitle?: string; onTicketSelect?: (ticket: any) => void; } export const TopBar: React.FC = ({ title, subtitle, onTicketSelect }) => { const [time, setTime] = useState(new Date()); const [searchQuery, setSearchQuery] = useState(''); const [results, setResults] = useState([]); const [isSearching, setIsSearching] = useState(false); const [hasSearched, setHasSearched] = useState(false); const [showLogoutConfirm, setShowLogoutConfirm] = useState(false); const [showNotifications, setShowNotifications] = useState(false); const searchRef = React.useRef(null); const { logout, user } = useAuth(); const [notifications, setNotifications] = useState([]); const [hasUnread, setHasUnread] = useState(false); const fetchNotifications = async () => { try { const res = await api.get('notifications/'); setNotifications(res.data); setHasUnread(res.data.some((n: any) => !n.is_read)); } catch (err) { console.error("Failed to fetch notifications:", err); } }; const markAllAsRead = async () => { try { await api.patch('notifications/mark-read/'); setHasUnread(false); fetchNotifications(); } catch (err) { console.error("Failed to mark notifications read:", err); } }; useEffect(() => { fetchNotifications(); const token = localStorage.getItem(getStorageKey('token')); if (token && user?.workspace_id) { try { const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`)); ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'notification' || data.event === 'ticket_updated') { setHasUnread(true); fetchNotifications(); } }; ws.onerror = () => console.warn('[WS] Connection error — notifications may be delayed'); ws.onclose = () => console.info('[WS] Connection closed'); return () => ws.close(); } catch (e) { console.warn('[WS] Failed to initialize:', e); } } }, [user?.workspace_id]); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (searchRef.current && !searchRef.current.contains(event.target as Node)) { setResults([]); } }; document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); useEffect(() => { const t = setInterval(() => setTime(new Date()), 1000); return () => clearInterval(t); }, []); const handleSearch = async (e?: React.FormEvent) => { if (e) e.preventDefault(); if (!searchQuery.trim()) { setResults([]); setHasSearched(false); return; } setIsSearching(true); try { const resp = await api.get(`tickets/search/?q=${encodeURIComponent(searchQuery)}`); setResults(resp.data.results || []); setHasSearched(true); } catch (err) { console.error('Ticket search failed:', err); } finally { setIsSearching(false); } }; const handleNotifClick = async (n: any) => { setShowNotifications(false); if (!n.link) return; // Parse deep links (e.g., /dashboard?ticket=UUID) try { const url = new URL(n.link, window.location.origin); const ticketId = url.searchParams.get('ticket'); if (ticketId) { const res = await api.get(`tickets/${ticketId}/`); onTicketSelect?.(res.data); } } catch (err) { console.error("Failed to parse or fetch notification link:", err); } }; // Handle Deep Linking on Load useEffect(() => { const params = new URLSearchParams(window.location.search); const ticketId = params.get('ticket'); if (ticketId) { api.get(`tickets/${ticketId}/`) .then(res => onTicketSelect?.(res.data)) .catch(err => console.error("URL-based ticket load failed:", err)); } }, []); // We only search on Enter now, so we remove the useEffect watcher return (
{title}
{subtitle &&
{subtitle}
}
⌕ setSearchQuery(e.target.value)} /> {hasSearched && (
{results.length > 0 ? ( results.map(r => (
{ onTicketSelect?.(r); setResults([]); setSearchQuery(''); setHasSearched(false); }} >
{r.score}% Match #{r.id?.slice(0, 8).toUpperCase()}
{r.status}
{r.title}
Created {new Date(r.created_at).toLocaleDateString()}
)) ) : (
No tickets found matching your query.
)}
)} {isSearching && (
Scanning network...
)} {results.length === 0 && searchQuery && !isSearching && !hasSearched && (
Press Enter to search
)}
LIVE {time.toLocaleTimeString('en-GB')}
{hasUnread && } {showNotifications && (
Notifications {notifications.length > 0 && ( {notifications.length} total )}
{notifications.length === 0 ? (
No new system alerts
) : ( notifications.map(n => (
handleNotifClick(n)} style={{ cursor: n.link ? 'pointer' : 'default' }} >
{n.title}
{n.message}
{new Date(n.created_at).toLocaleString()}
)) )}
)}
{showLogoutConfirm && (
Do you want to quit?
)}
); };