import { useState } from 'react' import { Archive, ArrowDownUp, Box, ChevronDown, Filter, Grid2X2, MoreVertical, Plus, Star, UserRound, UsersRound, } from 'lucide-react' import { StatusBadge } from '../../components/ui/StatusBadge' import { useApi } from '../../api/ApiProvider' import { canImportData } from '../../api/permissions' import { useApiQuery } from '../../api/useApiQuery' import { useWorkspace } from '../../api/WorkspaceContext' import './model-library.css' const ownerColors = { AJ: 'bg-[#8d6847]', EC: 'bg-[#b77973]', MP: 'bg-[#657d9d]', SW: 'bg-[#7f8b68]', DK: 'bg-[#8a7399]', } export function ModelLibrary({ query, onNotify, onOpenModel }) { const { projectId } = useWorkspace() const { request, user } = useApi() const canCreateModel = canImportData(user?.roles ?? []) const catalogQuery = useApiQuery(projectId ? `/v1/projects/${projectId}/models` : null) const apiModels = catalogQuery.data?.models ?? [] const modelRecords = apiModels.map((item) => { const timestamp = item.updated_at ? new Date(item.updated_at) : null const owner = item.owner?.full_name || 'Unknown' return { id: item.id, name: item.name, version: item.current_version?.version_label || '—', basis: item.current_version?.basis || '—', product: item.product_code || '—', status: item.status === 'needs_review' ? 'needs_review' : item.status === 'validated' ? 'validated' : item.status === 'approved' ? 'approved' : item.status === 'rejected' ? 'rejected' : item.status === 'superseded' ? 'superseded' : item.status === 'published' ? 'published' : 'draft', updated: timestamp && !Number.isNaN(timestamp.valueOf()) ? timestamp.toLocaleDateString() : '—', time: timestamp && !Number.isNaN(timestamp.valueOf()) ? timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '', owner, initials: owner.split(/\s+/).map((part) => part[0]).join('').slice(0, 2).toUpperCase() || '??', runs: item.run_count || 0, isOwned: Boolean(item.owner?.is_current_user || (user && item.owner?.id === user.id)), } }) const products = catalogQuery.data?.products ?? [] const counts = catalogQuery.data?.counts ?? { all: apiModels.length, owned: 0, shared: 0 } const tabItems = [{ label: 'All', count: counts.all }, { label: 'Owned', count: counts.owned }, { label: 'Shared', count: counts.shared }] const [activeTab, setActiveTab] = useState('All') const [product, setProduct] = useState('All products') const [statusFilter, setStatusFilter] = useState('All statuses') const [sortNewestFirst, setSortNewestFirst] = useState(true) const [view, setView] = useState('list') const [favorites, setFavorites] = useState([]) const [filtersOpen, setFiltersOpen] = useState(false) const [createOpen, setCreateOpen] = useState(false) const [newName, setNewName] = useState('') const [newProductCode, setNewProductCode] = useState('') const [newDescription, setNewDescription] = useState('') const [createBusy, setCreateBusy] = useState(false) const [createError, setCreateError] = useState('') const normalizedQuery = query.trim().toLowerCase() const visibleModels = modelRecords .filter((model) => { const matchesTab = activeTab === 'All' || (activeTab === 'Owned' && model.isOwned) || (activeTab === 'Shared' && !model.isOwned) const matchesProduct = product === 'All products' || model.product === product const matchesStatus = statusFilter === 'All statuses' || model.status === statusFilter const searchText = `${model.name} ${model.id} ${model.version} ${model.owner} ${model.product} ${model.basis}`.toLowerCase() return matchesTab && matchesProduct && matchesStatus && searchText.includes(normalizedQuery) }) .sort((first, second) => { const order = new Date(second.updated) - new Date(first.updated) return sortNewestFirst ? order : -order }) const toggleFavorite = (modelId) => { setFavorites((current) => current.includes(modelId) ? current.filter((favorite) => favorite !== modelId) : [...current, modelId], ) } const createModel = async event => { event.preventDefault() if (!canCreateModel || !projectId || createBusy) return setCreateBusy(true) setCreateError('') try { const created = await request(`/v1/projects/${encodeURIComponent(projectId)}/models`, { method: 'POST', body: JSON.stringify({ name: newName.trim(), product_code: newProductCode.trim(), description: newDescription.trim() || null }), }) catalogQuery.refetch() setCreateOpen(false) setNewName('') setNewProductCode('') setNewDescription('') onNotify(`Model ${created.name} created. Add its first draft version from Model detail.`) onOpenModel({ id: created.id, name: created.name, product: created.product_code, status: created.status, owner: user?.full_name ?? 'You' }) } catch (error) { setCreateError(error instanceof Error ? error.message : 'Could not create the model.') } finally { setCreateBusy(false) } } return (
{tabItems.map((tab) => ( ))}
{canCreateModel && }
{filtersOpen && (
)}
} label="Total models" value={String(counts.all)} detail="Across all products" /> } label="Owned by you" value={String(counts.owned)} detail={`${counts.all ? Math.round(counts.owned / counts.all * 100) : 0}% of total`} /> } label="Shared with you" value={String(counts.shared)} detail={`${counts.all ? Math.round(counts.shared / counts.all * 100) : 0}% of total`} />

Models ({visibleModels.length})

{catalogQuery.loading ?
Loading models from this project…
: catalogQuery.error ?
Could not load models: {catalogQuery.error.message}
: visibleModels.length > 0 ? (
{visibleModels.map((model) => ( toggleFavorite(model.id)} onMore={() => onNotify(`${model.name} actions opened`)} onOpen={() => onOpenModel(model)} view={view} /> ))}
) : (
{apiModels.length === 0 ? 'This project has no models yet.' : 'No models match the current search and filters.'}
)}

{visibleModels.length} of {counts.all} models · select Open model to enter the architecture workspace

{createOpen &&
setCreateOpen(false)}>
event.stopPropagation()}>

Create model

Creates an empty model shell. Create a draft version next.