import { useState } from 'react'; import { useQuery } from '@tanstack/react-query'; import { fetchEditHistory } from '@/lib/submissionItemsService'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { EditHistoryEntry } from './EditHistoryEntry'; import { History, Loader2, AlertCircle } from 'lucide-react'; interface EditHistoryRecord { id: string; item_id: string; edited_at: string; previous_data: Record; new_data: Record; edit_reason: string | null; changed_fields: string[]; profiles?: { username: string; avatar_url?: string | null; } | null; } interface EditHistoryAccordionProps { submissionId: string; } const INITIAL_LOAD = 20; const LOAD_MORE_INCREMENT = 10; export function EditHistoryAccordion({ submissionId }: EditHistoryAccordionProps) { const [limit, setLimit] = useState(INITIAL_LOAD); const { data: editHistory, isLoading, error } = useQuery({ queryKey: ['edit-history', submissionId, limit], queryFn: async () => { const { supabase } = await import('@/integrations/supabase/client'); // Fetch edit history with user profiles const { data, error } = await supabase .from('item_edit_history') .select(` id, item_id, edited_at, previous_data, new_data, edit_reason, changed_fields, profiles:edited_by ( username, avatar_url ) `) .eq('item_id', submissionId) .order('edited_at', { ascending: false }) .limit(limit); if (error) throw error; return (data || []) as unknown as EditHistoryRecord[]; }, staleTime: 5 * 60 * 1000, // 5 minutes }); const loadMore = () => { setLimit(prev => prev + LOAD_MORE_INCREMENT); }; const hasMore = editHistory && editHistory.length === limit; return (
Edit History {editHistory && editHistory.length > 0 && ( ({editHistory.length} edit{editHistory.length !== 1 ? 's' : ''}) )}
{isLoading && (
)} {error && ( Failed to load edit history: {error instanceof Error ? error.message : 'Unknown error'} )} {!isLoading && !error && editHistory && editHistory.length === 0 && ( No edit history found for this submission. )} {!isLoading && !error && editHistory && editHistory.length > 0 && (
{editHistory.map((entry: EditHistoryRecord) => ( ))}
{hasMore && (
)}
)}
); }