import { useEffect, useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Users, Trash2 } from 'lucide-react' import { sharing, type ShareInfo } from '../../services/api' import { SHARED_HEAPS_KEY, SHARED_FOLDERS_KEY, } from '../../hooks/useSharingQueries' import { Dialog, DialogContent, DialogHeader, DialogTitle, } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { Alert, AlertDescription } from '@/components/ui/alert' interface ShareDialogProps { isOpen: boolean type: 'heap' | 'folder' targetId: string targetName: string onClose: () => void } export function ShareDialog({ isOpen, type, targetId, targetName, onClose, }: ShareDialogProps) { const [username, setUsername] = useState('') const [permission, setPermission] = useState<'read' | 'write'>('read') const [error, setError] = useState(null) const queryClient = useQueryClient() const sharesQueryKey = [type, 'shares', targetId] const { data: shares = [], isLoading } = useQuery({ queryKey: sharesQueryKey, queryFn: () => type === 'heap' ? sharing.heapShares(targetId) : sharing.folderShares(targetId), enabled: isOpen, }) const addMutation = useMutation({ mutationFn: () => type === 'heap' ? sharing.shareHeap(targetId, username, permission) : sharing.shareFolder(targetId, username, permission), onSuccess: () => { setUsername('') setPermission('read') setError(null) queryClient.invalidateQueries({ queryKey: sharesQueryKey }) queryClient.invalidateQueries({ queryKey: type === 'heap' ? SHARED_HEAPS_KEY : SHARED_FOLDERS_KEY, }) }, onError: (err: any) => { setError(err?.response?.data?.detail || 'Failed to share') }, }) const revokeMutation = useMutation({ mutationFn: (shareId: string) => type === 'heap' ? sharing.revokeHeapShare(targetId, shareId) : sharing.revokeFolderShare(targetId, shareId), onSuccess: () => { queryClient.invalidateQueries({ queryKey: sharesQueryKey }) queryClient.invalidateQueries({ queryKey: type === 'heap' ? SHARED_HEAPS_KEY : SHARED_FOLDERS_KEY, }) }, }) useEffect(() => { if (isOpen) { setUsername('') setPermission('read') setError(null) } }, [isOpen]) return ( !o && onClose()}> Share {type === 'heap' ? 'heap' : 'folder'}
Sharing {targetName}
{/* Existing shares */} {shares.length > 0 && (
{shares.map((share) => (
{share.shared_with_username} {share.permission}
))}
)} {isLoading && (
Loading shares...
)}
{ e.preventDefault() if (username.trim()) addMutation.mutate() }} className="space-y-3" >
{ setUsername(e.target.value) setError(null) }} placeholder="Username" className="flex-1" autoFocus />
{error && ( {error} )}
) }