import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'; import { CheckCircle, XCircle, ExternalLink, Calendar, User, Flag } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Card, CardContent, CardHeader } from '@/components/ui/card'; import { Textarea } from '@/components/ui/textarea'; import { Label } from '@/components/ui/label'; import { supabase } from '@/integrations/supabase/client'; import { useToast } from '@/hooks/use-toast'; import { format } from 'date-fns'; import { useAdminSettings } from '@/hooks/useAdminSettings'; import { useAuth } from '@/hooks/useAuth'; import { smartMergeArray } from '@/lib/smartStateUpdate'; interface Report { id: string; reported_entity_type: string; reported_entity_id: string; report_type: string; reason: string; status: string; created_at: string; reporter_profile?: { username: string; display_name?: string; }; reported_content?: any; } const REPORT_TYPE_LABELS = { spam: 'Spam', inappropriate: 'Inappropriate Content', harassment: 'Harassment', fake_info: 'Fake Information', offensive: 'Offensive Language', }; const STATUS_COLORS = { pending: 'secondary', reviewed: 'default', dismissed: 'outline', } as const; export interface ReportsQueueRef { refresh: () => void; } export const ReportsQueue = forwardRef((props, ref) => { const [reports, setReports] = useState([]); const [loading, setLoading] = useState(true); const [isInitialLoad, setIsInitialLoad] = useState(true); const [actionLoading, setActionLoading] = useState(null); const [newReportsCount, setNewReportsCount] = useState(0); const { toast } = useToast(); const { user } = useAuth(); // Get admin settings for polling configuration const { getAdminPanelRefreshMode, getAdminPanelPollInterval, getAutoRefreshStrategy } = useAdminSettings(); const refreshMode = getAdminPanelRefreshMode(); const pollInterval = getAdminPanelPollInterval(); const refreshStrategy = getAutoRefreshStrategy(); // Expose refresh method via ref useImperativeHandle(ref, () => ({ refresh: () => fetchReports(false) // Manual refresh shows loading }), []); const fetchReports = async (silent = false) => { try { // Only show loading on initial load if (!silent) { setLoading(true); } const { data, error } = await supabase .from('reports') .select(` id, reported_entity_type, reported_entity_id, report_type, reason, status, created_at, reporter_id `) .eq('status', 'pending') .order('created_at', { ascending: true }); if (error) throw error; // Get unique reporter IDs const reporterIds = [...new Set((data || []).map(r => r.reporter_id))]; // Fetch reporter profiles const { data: profiles } = await supabase .from('profiles') .select('user_id, username, display_name') .in('user_id', reporterIds); const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []); // Fetch the reported content for each report const reportsWithContent = await Promise.all( (data || []).map(async (report) => { let reportedContent = null; if (report.reported_entity_type === 'review') { const { data: reviewData } = await supabase .from('reviews') .select('title, content, rating') .eq('id', report.reported_entity_id) .single(); reportedContent = reviewData; } // Add other entity types as needed return { ...report, reporter_profile: profileMap.get(report.reporter_id), reported_content: reportedContent, }; }) ); // Use smart merging for silent refreshes if strategy is 'merge' if (silent && refreshStrategy === 'merge') { const mergeResult = smartMergeArray(reports, reportsWithContent, { compareFields: ['status'], preserveOrder: true, addToTop: true, }); if (mergeResult.hasChanges) { setReports(mergeResult.items); // Update new reports count if (mergeResult.changes.added.length > 0) { setNewReportsCount(prev => prev + mergeResult.changes.added.length); } } } else { // Full replacement for non-silent refreshes or 'replace' strategy setReports(reportsWithContent); setNewReportsCount(0); } } catch (error) { console.error('Error fetching reports:', error); toast({ title: "Error", description: "Failed to load reports queue", variant: "destructive", }); } finally { // Only clear loading if it was set if (!silent) { setLoading(false); } if (isInitialLoad) { setIsInitialLoad(false); } } }; // Initial fetch on mount useEffect(() => { if (user) { fetchReports(false); // Show loading } }, [user]); // Polling for auto-refresh useEffect(() => { if (!user || refreshMode !== 'auto' || isInitialLoad) return; const interval = setInterval(() => { fetchReports(true); // Silent refresh }, pollInterval); return () => { clearInterval(interval); }; }, [user, refreshMode, pollInterval, isInitialLoad]); const handleReportAction = async (reportId: string, action: 'reviewed' | 'dismissed') => { setActionLoading(reportId); try { const { error } = await supabase .from('reports') .update({ status: action, reviewed_at: new Date().toISOString(), }) .eq('id', reportId); if (error) throw error; toast({ title: `Report ${action}`, description: `The report has been marked as ${action}`, }); // Remove report from queue setReports(prev => prev.filter(r => r.id !== reportId)); } catch (error) { console.error('Error updating report:', error); toast({ title: "Error", description: `Failed to ${action} report`, variant: "destructive", }); } finally { setActionLoading(null); } }; if (loading) { return (
); } if (reports.length === 0) { return (

No pending reports

All user reports have been reviewed.

); } return (
{/* New Reports Notification */} {newReportsCount > 0 && (
)} {reports.map((report) => (
{REPORT_TYPE_LABELS[report.report_type as keyof typeof REPORT_TYPE_LABELS]} {report.reported_entity_type}
{format(new Date(report.created_at), 'MMM d, yyyy HH:mm')}
{report.reporter_profile && (
Reported by: {report.reporter_profile.display_name || report.reporter_profile.username} {report.reporter_profile.display_name && ( @{report.reporter_profile.username} )}
)}
{report.reason && (

{report.reason}

)} {report.reported_content && (
{report.reported_entity_type === 'review' && (
{report.reported_content.title && (

{report.reported_content.title}

)} {report.reported_content.content && (

{report.reported_content.content}

)}
Rating: {report.reported_content.rating}/5
)}
)}
))}
); });