import { useState, useEffect, forwardRef, useImperativeHandle, useMemo, useCallback } from 'react'; import { CheckCircle, XCircle, ExternalLink, Calendar, User, Flag, ArrowUp, ArrowDown } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { logger } from '@/lib/logger'; import * as storage from '@/lib/localStorage'; import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, } from '@/components/ui/pagination'; import { supabase } from '@/lib/supabaseClient'; import { format } from 'date-fns'; import { useAdminSettings } from '@/hooks/useAdminSettings'; import { useAuth } from '@/hooks/useAuth'; import { useIsMobile } from '@/hooks/use-mobile'; import { smartMergeArray } from '@/lib/smartStateUpdate'; import { handleError, handleSuccess } from '@/lib/errorHandler'; // Type-safe reported content interfaces interface ReportedReview { id: string; title: string | null; content: string | null; rating: number; } interface ReportedProfile { user_id: string; username: string; display_name: string | null; } interface ReportedSubmission { id: string; submission_type: string; status: string; } // Union type for all possible reported content type ReportedContent = ReportedReview | ReportedProfile | ReportedSubmission | null; // Discriminated union for entity types type ReportEntityType = 'review' | 'profile' | 'content_submission'; /** * Type guards for reported content */ function isReportedReview(content: ReportedContent): content is ReportedReview { return content !== null && 'rating' in content; } function isReportedProfile(content: ReportedContent): content is ReportedProfile { return content !== null && 'username' in content; } function isReportedSubmission(content: ReportedContent): content is ReportedSubmission { return content !== null && 'submission_type' in content; } interface Report { id: string; reported_entity_type: ReportEntityType; reported_entity_id: string; report_type: string; reason: string | null; status: string; created_at: string; reporter_profile?: { username: string; display_name?: string | null; }; reported_content?: ReportedContent; } 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; type ReportSortField = 'created_at' | 'reporter' | 'report_type' | 'entity_type'; type ReportSortDirection = 'asc' | 'desc'; interface ReportSortConfig { field: ReportSortField; direction: ReportSortDirection; } export interface ReportsQueueRef { refresh: () => void; } export const ReportsQueue = forwardRef((props, ref) => { const isMobile = useIsMobile(); 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 { user } = useAuth(); // Pagination state const [currentPage, setCurrentPage] = useState(1); const [pageSize, setPageSize] = useState(25); const [totalCount, setTotalCount] = useState(0); const totalPages = Math.ceil(totalCount / pageSize); // Sort state with error handling const [sortConfig, setSortConfig] = useState(() => { return storage.getJSON('reportsQueue_sortConfig', { field: 'created_at', direction: 'asc' as ReportSortDirection }); }); // 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 }), []); // Persist sort configuration with error handling useEffect(() => { storage.setJSON('reportsQueue_sortConfig', sortConfig); }, [sortConfig]); const fetchReports = async (silent = false) => { try { // Only show loading on initial load if (!silent) { setLoading(true); } // Get total count const { count } = await supabase .from('reports') .select('*', { count: 'exact', head: true }) .eq('status', 'pending'); setTotalCount(count || 0); // Apply pagination const startIndex = (currentPage - 1) * pageSize; const endIndex = startIndex + pageSize - 1; 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 }) .range(startIndex, endIndex); if (error) throw error; // Get unique reporter IDs const reporterIds = [...new Set((data || []).map(r => r.reporter_id))]; // Fetch reporter profiles with emails (for admins) let profiles: Array<{ user_id: string; username: string; display_name?: string | null; avatar_url?: string | null }> | null = null; const { data: allProfiles, error: rpcError } = await supabase .rpc('get_users_with_emails'); if (rpcError) { const { data: basicProfiles } = await supabase .from('profiles') .select('user_id, username, display_name, avatar_url') .in('user_id', reporterIds); profiles = basicProfiles as typeof profiles; } else { profiles = allProfiles?.filter(p => reporterIds.includes(p.user_id)) || null; } const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []); // Batch fetch reported content to avoid N+1 queries // Separate entity IDs by type for efficient batching const reviewIds = data?.filter(r => r.reported_entity_type === 'review') .map(r => r.reported_entity_id) || []; const profileIds = data?.filter(r => r.reported_entity_type === 'profile') .map(r => r.reported_entity_id) || []; const submissionIds = data?.filter(r => r.reported_entity_type === 'content_submission') .map(r => r.reported_entity_id) || []; // Parallel batch fetch for all entity types const [reviewsData, profilesData, submissionsData] = await Promise.all([ reviewIds.length > 0 ? supabase .from('reviews') .select('id, title, content, rating') .in('id', reviewIds) .then(({ data }) => data || []) : Promise.resolve([]), profileIds.length > 0 ? supabase .rpc('get_users_with_emails') .then(({ data, error }) => { if (error) { return supabase .from('profiles') .select('user_id, username, display_name') .in('user_id', profileIds) .then(({ data: basicProfiles }) => basicProfiles || []); } return data?.filter(p => profileIds.includes(p.user_id)) || []; }) : Promise.resolve([]), submissionIds.length > 0 ? supabase .from('content_submissions') .select('id, submission_type, status') .in('id', submissionIds) .then(({ data }) => data || []) : Promise.resolve([]), ]); // Create lookup maps for O(1) access const reviewMap = new Map( reviewsData.map(r => [r.id, r as ReportedReview] as const) ); const profilesMap = new Map( profilesData.map(p => [p.user_id, p as ReportedProfile] as const) ); const submissionsMap = new Map( submissionsData.map(s => [s.id, s as ReportedSubmission] as const) ); // Map reports to their content (O(n) instead of O(n*m)) const reportsWithContent: Report[] = (data || []).map(report => { let reportedContent: ReportedContent = null; // Type-safe entity type handling const entityType = report.reported_entity_type as ReportEntityType; switch (entityType) { case 'review': reportedContent = reviewMap.get(report.reported_entity_id) || null; break; case 'profile': reportedContent = profilesMap.get(report.reported_entity_id) || null; break; case 'content_submission': reportedContent = submissionsMap.get(report.reported_entity_id) || null; break; } return { ...report, reported_entity_type: entityType, 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: unknown) { handleError(error, { action: 'Load Reports', userId: user?.id, metadata: { currentPage, pageSize } }); } 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 { // Fetch full report details including reporter_id for audit log const { data: reportData } = await supabase .from('reports') .select('reporter_id, reported_entity_type, reported_entity_id, reason') .eq('id', reportId) .single(); const { error } = await supabase .from('reports') .update({ status: action, reviewed_by: user?.id, reviewed_at: new Date().toISOString(), }) .eq('id', reportId); if (error) throw error; // Log audit trail for report resolution if (user && reportData) { try { await supabase.rpc('log_admin_action', { _admin_user_id: user.id, _target_user_id: reportData.reporter_id, _action: action === 'reviewed' ? 'report_resolved' : 'report_dismissed', _details: { report_id: reportId, reported_entity_type: reportData.reported_entity_type, reported_entity_id: reportData.reported_entity_id, report_reason: reportData.reason, action: action } }); } catch (auditError) { logger.error('Failed to log report action audit', { error: auditError }); } } handleSuccess(`Report ${action}`, `The report has been marked as ${action}`); // Remove report from queue setReports(prev => { const newReports = prev.filter(r => r.id !== reportId); // If last item on page and not page 1, go to previous page if (newReports.length === 0 && currentPage > 1) { setCurrentPage(prev => prev - 1); } return newReports; }); } catch (error: unknown) { handleError(error, { action: `${action === 'reviewed' ? 'Resolve' : 'Dismiss'} Report`, userId: user?.id, metadata: { reportId, action } }); } finally { setActionLoading(null); } }; // Sort reports function const sortReports = useCallback((reports: Report[], config: ReportSortConfig): Report[] => { const sorted = [...reports]; sorted.sort((a, b) => { let compareA: string | number; let compareB: string | number; switch (config.field) { case 'created_at': compareA = new Date(a.created_at).getTime(); compareB = new Date(b.created_at).getTime(); break; case 'reporter': compareA = (a.reporter_profile?.username || '').toLowerCase(); compareB = (b.reporter_profile?.username || '').toLowerCase(); break; case 'report_type': compareA = a.report_type; compareB = b.report_type; break; case 'entity_type': compareA = a.reported_entity_type; compareB = b.reported_entity_type; break; default: return 0; } let result = 0; if (typeof compareA === 'string' && typeof compareB === 'string') { result = compareA.localeCompare(compareB); } else if (typeof compareA === 'number' && typeof compareB === 'number') { result = compareA - compareB; } return config.direction === 'asc' ? result : -result; }); return sorted; }, []); if (loading) { return (
); } if (reports.length === 0) { return (

No pending reports

All user reports have been reviewed.

); } // Apply client-side sorting const sortedReports = useMemo(() => { return sortReports(reports, sortConfig); }, [reports, sortConfig]); return (
{/* New Reports Notification */} {newReportsCount > 0 && (
)} {/* Sort Controls */}
{sortConfig.field !== 'created_at' && (
{sortConfig.direction === 'asc' ? : } {sortConfig.field === 'reporter' ? 'Reporter' : sortConfig.field === 'report_type' ? 'Type' : sortConfig.field === 'entity_type' ? 'Entity' : sortConfig.field}
)}
{/* Report Cards */} {sortedReports.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' && isReportedReview(report.reported_content) && (
{report.reported_content.title && (

{report.reported_content.title}

)} {report.reported_content.content && (

{report.reported_content.content}

)}
Rating: {report.reported_content.rating}/5
)} {report.reported_entity_type === 'profile' && isReportedProfile(report.reported_content) && (
{report.reported_content.display_name || report.reported_content.username}
@{report.reported_content.username}
)} {report.reported_entity_type === 'content_submission' && isReportedSubmission(report.reported_content) && (
Type: {report.reported_content.submission_type}
Status: {report.reported_content.status}
)}
)}
))} {/* Pagination Controls */} {totalPages > 1 && !loading && (
Showing {((currentPage - 1) * pageSize) + 1} - {Math.min(currentPage * pageSize, totalCount)} of {totalCount} reports {!isMobile && ( <> )}
{isMobile ? (
Page {currentPage} of {totalPages}
) : ( setCurrentPage(p => Math.max(1, p - 1))} className={currentPage === 1 ? 'pointer-events-none opacity-50' : 'cursor-pointer'} /> {currentPage > 3 && ( <> setCurrentPage(1)} isActive={currentPage === 1}> 1 {currentPage > 4 && } )} {Array.from({ length: totalPages }, (_, i) => i + 1) .filter(page => page >= currentPage - 2 && page <= currentPage + 2) .map(page => ( setCurrentPage(page)} isActive={currentPage === page} > {page} )) } {currentPage < totalPages - 2 && ( <> {currentPage < totalPages - 3 && } setCurrentPage(totalPages)} isActive={currentPage === totalPages}> {totalPages} )} setCurrentPage(p => Math.min(totalPages, p + 1))} className={currentPage === totalPages ? 'pointer-events-none opacity-50' : 'cursor-pointer'} /> )}
)}
); });