import type { ProjectInfo } from '@shumai/dtos' import { usePermissions } from '@/ui/hooks/use-permissions' import { client } from '@/ui/api/client' import { MembersDialog } from '@/ui/components/members-dialog' import { ProjectDialog } from '@/ui/components/project-dialog' import { SortDropdown } from '@/ui/components/sort-dropdown' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar' import { Button } from '@/ui/components/ui/button' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Input } from '@/ui/components/ui/input' import { Switch } from '@/ui/components/ui/switch' import { formatDateAgo } from '@/ui/lib/time' import { cn } from '@/ui/lib/utils' import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query' import { createFileRoute, useNavigate } from '@tanstack/react-router' import type { InferRequestType, InferResponseType } from 'hono/client' import { MoreHorizontal, PlusIcon } from 'lucide-react' import { useState } from 'react' import { toast } from 'sonner' function TeamPage() { const { teamId } = Route.useParams() const { canEdit, canAdmin } = usePermissions() const navigate = useNavigate() const queryClient = useQueryClient() // State for clicked project for animation const [clickedProjectId, setClickedProjectId] = useState(null) // State for Project Dialog const [isProjectDialogOpen, setIsProjectDialogOpen] = useState(false) const [projectDialogMode, setProjectDialogMode] = useState<'create' | 'edit'>('create') const [selectedProject, setSelectedProject] = useState(undefined) // State for Delete Alert const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [projectToDelete, setProjectToDelete] = useState(undefined) const [deleteConfirmText, setDeleteConfirmText] = useState('') // State for Members Dialog const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false) // Sort State const [sortBy, setSortBy] = useState('name') const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc') const $getProjects = client.api.teams[':teamId'].projects.$get const { data: projects } = useSuspenseQuery({ queryKey: ['teams', teamId, 'projects', sortBy, sortDirection], queryFn: async () => { const res = await $getProjects({ param: { teamId: teamId }, query: { sortBy, sortDirection }, }) if (!res.ok) throw new Error('Failed to fetch projects') return await res.json() }, }) const { data: members } = useQuery({ queryKey: ['teams', teamId, 'members'], queryFn: async () => { const res = await client.api.teams[':teamId'].members.$get({ param: { teamId: teamId }, query: {}, }) if (!res.ok) throw new Error('Failed to fetch members') return await res.json() }, }) const { data: me } = useQuery({ queryKey: ['teams', teamId, 'me'], queryFn: async () => { const res = await client.api.teams[':teamId'].me.$get({ param: { teamId: teamId }, }) if (!res.ok) throw new Error('Failed to fetch me') return await res.json() }, }) const $inviteTeam = client.api.teams[':teamId'].invite.$post const inviteMutation = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (args) => { const res = await $inviteTeam(args) if (!res.ok) { throw new Error('Failed to invite') } return await res.json() }, }) const deleteProjectMutation = useMutation({ mutationFn: async (projectId: string) => { const res = await client.api.projects[':projectId'].$delete({ param: { projectId }, }) if (!res.ok) throw new Error('Failed to delete project') }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] }) }, }) const toggleProjectNotificationsMutation = useMutation({ mutationFn: async (project: ProjectInfo) => { const res = await client.api.projects[':projectId'].$put({ param: { projectId: project.id! }, json: { enableNotification: !project.enableNotification, }, }) if (!res.ok) throw new Error('Failed to update project notification settings') return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] }) toast.success('Project notification settings updated') }, onError: (err) => { toast.error( err instanceof Error ? err.message : 'Failed to update project notification settings', ) }, }) const handleCreateProjectClick = () => { setProjectDialogMode('create') setSelectedProject(undefined) setIsProjectDialogOpen(true) } const handleCreateCardClick = () => { setClickedProjectId('create') setTimeout(() => { setClickedProjectId(null) }, 100) setTimeout(() => { handleCreateProjectClick() }, 200) } const handleEditProjectClick = (project: ProjectInfo) => { setProjectDialogMode('edit') setSelectedProject(project) setIsProjectDialogOpen(true) } const handleDeleteProjectClick = (project: ProjectInfo) => { setProjectToDelete(project) setDeleteConfirmText('') setIsDeleteDialogOpen(true) } const handleConfirmDelete = async () => { if (projectToDelete && deleteConfirmText === 'delete') { try { await deleteProjectMutation.mutateAsync(projectToDelete.id!) setIsDeleteDialogOpen(false) } catch (error) { console.error(error) } } } const handleCardClick = (projectId: string, e: React.MouseEvent) => { if (e.detail > 1) return setClickedProjectId(projectId) // Restore scale after 100ms for "shrink and restore" effect setTimeout(() => { setClickedProjectId(null) }, 100) // Navigate after 200ms setTimeout(() => { navigate({ to: '/projects/$projectId', params: { projectId }, }) }, 200) } const handleInvite = async (role: 'editor' | 'reviewer') => { const res = await inviteMutation.mutateAsync({ param: { teamId: teamId }, json: { role }, }) return res.code } const updateMemberRoleMutation = useMutation({ mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => { const res = await client.api.teams[':teamId'].members[':userId'].$patch({ param: { teamId, userId }, json: { role }, }) if (!res.ok) throw new Error('Failed to update member role') }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] }) }, }) const removeMemberMutation = useMutation({ mutationFn: async (userId: string) => { const res = await client.api.teams[':teamId'].members[':userId'].$delete({ param: { teamId, userId }, }) if (!res.ok) throw new Error('Failed to remove member') }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] }) }, }) const getInitials = (name?: string) => { if (!name) return '??' return name .split(' ') .map((n) => n[0]) .slice(0, 2) .join('') .toUpperCase() } const handleSortChange = (newSortBy: string, newSortDirection: 'asc' | 'desc') => { setSortBy(newSortBy) setSortDirection(newSortDirection) } const safeMembers = Array.isArray(members) ? members : [] return (

Projects

setIsMembersDialogOpen(true)} > {safeMembers.slice(0, 3).map((member) => ( {member.image && ( )} {getInitials(member.name)} ))} {safeMembers.length > 3 && (
+{safeMembers.length - 3}
)}
{canEdit && ( )}
{projects.data?.map((project: ProjectInfo) => (
handleCardClick(project.id!, e)} >
{project.coverImage ? ( {project.name} ) : ( )}

{project.name}

Updated {formatDateAgo((project.updatedAt as string) ?? '')}

e.stopPropagation()}> {canEdit && ( { e.stopPropagation() handleEditProjectClick(project) }} > Project Settings )} { e.preventDefault() toggleProjectNotificationsMutation.mutate(project) }} > Notification {canAdmin && ( handleDeleteProjectClick(project)} > Delete )}
))} {canEdit && (

Create Project

)}
Are you absolutely sure? This action cannot be undone. This will permanently delete the project " {projectToDelete?.name}" and all its assets.
Type delete to confirm: setDeleteConfirmText(e.target.value)} placeholder="delete" className="h-9" autoFocus />
Cancel { e.preventDefault() handleConfirmDelete() }} disabled={deleteConfirmText !== 'delete' || deleteProjectMutation.isPending} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > {deleteProjectMutation.isPending ? 'Deleting...' : 'Delete'}
{ await updateMemberRoleMutation.mutateAsync({ userId: memberId, role }) }} onRemoveMember={async (memberId) => { await removeMemberMutation.mutateAsync(memberId) }} currentUserId={me?.id} />
) } export const Route = createFileRoute('/teams/$teamId/')({ component: TeamPage, })