'use client'; import { useState, useEffect } from 'react'; import { useQuery, useQueryClient } from '@tanstack/react-query'; import { getTenants, type Tenant } from '@/lib/api/tenants'; import { useTenantViewStore } from '@/stores/tenant-view-store'; import { useAuthStore } from '@/stores/auth-store'; import { Building, ChevronDown, Check, X } from 'lucide-react'; import { cn } from '@/lib/utils'; export function TenantSelector() { const [open, setOpen] = useState(false); const { user } = useAuthStore(); const queryClient = useQueryClient(); const { viewingTenantId, viewingTenantName, setViewingTenant, clearViewingTenant } = useTenantViewStore(); const { data: tenants, isLoading } = useQuery({ queryKey: ['tenants'], queryFn: getTenants, enabled: user?.role === 'admin', }); // Close dropdown when clicking outside useEffect(() => { const handleClickOutside = (e: MouseEvent) => { const target = e.target as HTMLElement; if (!target.closest('.tenant-selector')) { setOpen(false); } }; document.addEventListener('click', handleClickOutside); return () => document.removeEventListener('click', handleClickOutside); }, []); // Only show for admin users if (user?.role !== 'admin') { return null; } const currentTenant = viewingTenantId ? tenants?.find(t => t.id === viewingTenantId) : null; const displayName = viewingTenantName || currentTenant?.nombre || user?.tenantName; const isViewingOther = viewingTenantId && viewingTenantId !== user?.tenantId; return (
{open && (

Seleccionar cliente

{isLoading ? (
Cargando...
) : tenants && tenants.length > 0 ? ( <> {/* Option to go back to own tenant */}
{/* Other tenants */} {tenants .filter(t => t.id !== user?.tenantId) .map((tenant) => ( ))} ) : (
No hay otros clientes
)}
)}
); }