'use client'; import { useState } from 'react'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { formatDistanceToNow } from 'date-fns'; import { Lock, Pencil, Trash2, Send, Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { apiFetch } from '@/lib/api/client'; interface Note { id: string; content: string; authorId: string; authorName?: string; isLocked: boolean; createdAt: string; updatedAt: string; } interface NotesListProps { entityType: 'clients' | 'interests' | 'yachts' | 'companies'; entityId: string; currentUserId?: string; } const NOTE_EDIT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes export function NotesList({ entityType, entityId, currentUserId }: NotesListProps) { const queryClient = useQueryClient(); const [newNote, setNewNote] = useState(''); const [editingId, setEditingId] = useState(null); const [editContent, setEditContent] = useState(''); const endpoint = `/api/v1/${entityType}/${entityId}/notes`; const queryKey = [entityType, entityId, 'notes']; const { data: notes = [], isLoading } = useQuery({ queryKey, queryFn: () => apiFetch<{ data: Note[] }>(endpoint).then((r) => r.data), }); const createMutation = useMutation({ mutationFn: (content: string) => apiFetch(endpoint, { method: 'POST', body: { content } }), onSuccess: () => { queryClient.invalidateQueries({ queryKey }); setNewNote(''); }, }); const updateMutation = useMutation({ mutationFn: ({ noteId, content }: { noteId: string; content: string }) => apiFetch(`${endpoint}/${noteId}`, { method: 'PATCH', body: { content } }), onSuccess: () => { queryClient.invalidateQueries({ queryKey }); setEditingId(null); }, }); const deleteMutation = useMutation({ mutationFn: (noteId: string) => apiFetch(`${endpoint}/${noteId}`, { method: 'DELETE' }), onSuccess: () => queryClient.invalidateQueries({ queryKey }), }); function canEdit(note: Note): boolean { if (note.authorId !== currentUserId) return false; if (note.isLocked) return false; const elapsed = Date.now() - new Date(note.createdAt).getTime(); return elapsed < NOTE_EDIT_WINDOW_MS; } function getTimeRemaining(note: Note): string | null { const elapsed = Date.now() - new Date(note.createdAt).getTime(); const remaining = NOTE_EDIT_WINDOW_MS - elapsed; if (remaining <= 0) return null; const mins = Math.ceil(remaining / 60000); return `${mins}m left to edit`; } return (
{/* Create note form */}