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 '@/integrations/supabase/client';
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<ReportsQueueRef>((props, ref) => {
  const isMobile = useIsMobile();
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(true);
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(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<ReportSortConfig>(() => {
    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) {
          console.error('Failed to log report action audit:', 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: any;
      let compareB: any;
      
      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 (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (reports.length === 0) {
    return (
      <div className="text-center py-8">
        <CheckCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
        <h3 className="text-lg font-semibold mb-2">No pending reports</h3>
        <p className="text-muted-foreground">
          All user reports have been reviewed.
        </p>
      </div>
    );
  }

  // Apply client-side sorting
  const sortedReports = useMemo(() => {
    return sortReports(reports, sortConfig);
  }, [reports, sortConfig]);

  return (
    <div className="space-y-6">
      {/* New Reports Notification */}
      {newReportsCount > 0 && (
        <div className="flex items-center justify-center">
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              setNewReportsCount(0);
              fetchReports(false);
            }}
            className="flex items-center gap-2 border-destructive/50 bg-destructive/5 hover:bg-destructive/10"
          >
            <Flag className="w-4 h-4" />
            Show {newReportsCount} new {newReportsCount === 1 ? 'report' : 'reports'}
          </Button>
        </div>
      )}

      {/* Sort Controls */}
      <div className={`flex gap-4 bg-muted/50 rounded-lg ${isMobile ? 'p-3' : 'p-4'}`}>
        <div className={`space-y-2 ${isMobile ? 'w-full' : 'flex-1 max-w-[200px]'}`}>
          <Label className={`font-medium ${isMobile ? 'text-xs' : 'text-sm'}`}>Sort By</Label>
          <div className="flex gap-2">
            <Select 
              value={sortConfig.field} 
              onValueChange={(value) => setSortConfig(prev => ({ ...prev, field: value as ReportSortField }))}
            >
              <SelectTrigger className={isMobile ? "h-10 flex-1" : "flex-1"}>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="created_at">Date Reported</SelectItem>
                <SelectItem value="reporter">Reporter</SelectItem>
                <SelectItem value="report_type">Report Type</SelectItem>
                <SelectItem value="entity_type">Entity Type</SelectItem>
              </SelectContent>
            </Select>
            
            <Button
              variant="outline"
              size={isMobile ? "default" : "sm"}
              onClick={() => setSortConfig(prev => ({ 
                ...prev, 
                direction: prev.direction === 'asc' ? 'desc' : 'asc' 
              }))}
              className={isMobile ? "h-10" : ""}
              title={sortConfig.direction === 'asc' ? 'Sort Descending' : 'Sort Ascending'}
            >
              {sortConfig.direction === 'asc' ? (
                <ArrowUp className="w-4 h-4" />
              ) : (
                <ArrowDown className="w-4 h-4" />
              )}
            </Button>
          </div>
        </div>
        
        {sortConfig.field !== 'created_at' && (
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Badge variant="secondary" className="flex items-center gap-1">
              {sortConfig.direction === 'asc' ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />}
              {sortConfig.field === 'reporter' ? 'Reporter' :
               sortConfig.field === 'report_type' ? 'Type' :
               sortConfig.field === 'entity_type' ? 'Entity' : sortConfig.field}
            </Badge>
          </div>
        )}
      </div>

      {/* Report Cards */}
      {sortedReports.map((report) => (
        <Card key={report.id} className="border-l-4 border-l-red-500">
          <CardHeader className="pb-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Badge variant="destructive">
                  <Flag className="w-3 h-3 mr-1" />
                  {REPORT_TYPE_LABELS[report.report_type as keyof typeof REPORT_TYPE_LABELS]}
                </Badge>
                <Badge variant="outline">
                  {report.reported_entity_type}
                </Badge>
              </div>
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Calendar className="w-4 h-4" />
                {format(new Date(report.created_at), 'MMM d, yyyy HH:mm')}
              </div>
            </div>
            
            {report.reporter_profile && (
              <div className="flex items-center gap-2 text-sm">
                <User className="w-4 h-4 text-muted-foreground" />
                <span>Reported by:</span>
                <span className="font-medium">
                  {report.reporter_profile.display_name || report.reporter_profile.username}
                </span>
                {report.reporter_profile.display_name && (
                  <span className="text-muted-foreground">
                    @{report.reporter_profile.username}
                  </span>
                )}
              </div>
            )}
          </CardHeader>
          
          <CardContent className="space-y-4">
            {report.reason && (
              <div>
                <Label>Report Reason:</Label>
                <p className="text-sm bg-muted/50 p-3 rounded-lg mt-1">
                  {report.reason}
                </p>
              </div>
            )}
            
            {report.reported_content && (
              <div>
                <Label>Reported Content:</Label>
                <div className="bg-destructive/5 border border-destructive/20 p-4 rounded-lg mt-1">
                  {report.reported_entity_type === 'review' && isReportedReview(report.reported_content) && (
                    <div>
                      {report.reported_content.title && (
                        <h4 className="font-semibold mb-2">{report.reported_content.title}</h4>
                      )}
                      {report.reported_content.content && (
                        <p className="text-sm mb-2">{report.reported_content.content}</p>
                      )}
                      <div className="text-sm text-muted-foreground">
                        Rating: {report.reported_content.rating}/5
                      </div>
                    </div>
                  )}
                  
                  {report.reported_entity_type === 'profile' && isReportedProfile(report.reported_content) && (
                    <div>
                      <div className="font-semibold mb-2">
                        {report.reported_content.display_name || report.reported_content.username}
                      </div>
                      <div className="text-sm text-muted-foreground">
                        @{report.reported_content.username}
                      </div>
                    </div>
                  )}
                  
                  {report.reported_entity_type === 'content_submission' && isReportedSubmission(report.reported_content) && (
                    <div>
                      <div className="text-sm">
                        <span className="font-semibold">Type:</span> {report.reported_content.submission_type}
                      </div>
                      <div className="text-sm text-muted-foreground">
                        <span className="font-semibold">Status:</span> {report.reported_content.status}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
            
            <div className="flex gap-2 pt-2">
              <Button
                onClick={() => handleReportAction(report.id, 'reviewed')}
                disabled={actionLoading === report.id}
                className="flex-1"
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                Mark Reviewed
              </Button>
              <Button
                variant="outline"
                onClick={() => handleReportAction(report.id, 'dismissed')}
                disabled={actionLoading === report.id}
                className="flex-1"
              >
                <XCircle className="w-4 h-4 mr-2" />
                Dismiss
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}

      {/* Pagination Controls */}
      {totalPages > 1 && !loading && (
        <div className="flex items-center justify-between border-t pt-4 mt-6">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <span>
              Showing {((currentPage - 1) * pageSize) + 1} - {Math.min(currentPage * pageSize, totalCount)} of {totalCount} reports
            </span>
            {!isMobile && (
              <>
                <span>•</span>
                <Select 
                  value={pageSize.toString()} 
                  onValueChange={(value) => {
                    setPageSize(parseInt(value));
                    setCurrentPage(1);
                  }}
                >
                  <SelectTrigger className="w-[120px] h-8">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="10">10 per page</SelectItem>
                    <SelectItem value="25">25 per page</SelectItem>
                    <SelectItem value="50">50 per page</SelectItem>
                    <SelectItem value="100">100 per page</SelectItem>
                  </SelectContent>
                </Select>
              </>
            )}
          </div>
          
          {isMobile ? (
            <div className="flex items-center justify-between gap-4">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
              >
                Previous
              </Button>
              <span className="text-sm text-muted-foreground">
                Page {currentPage} of {totalPages}
              </span>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
              >
                Next
              </Button>
            </div>
          ) : (
            <Pagination>
              <PaginationContent>
                <PaginationItem>
                  <PaginationPrevious 
                    onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                    className={currentPage === 1 ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                  />
                </PaginationItem>
                
                {currentPage > 3 && (
                  <>
                    <PaginationItem>
                      <PaginationLink onClick={() => setCurrentPage(1)} isActive={currentPage === 1}>
                        1
                      </PaginationLink>
                    </PaginationItem>
                    {currentPage > 4 && <PaginationEllipsis />}
                  </>
                )}
                
                {Array.from({ length: totalPages }, (_, i) => i + 1)
                  .filter(page => page >= currentPage - 2 && page <= currentPage + 2)
                  .map(page => (
                    <PaginationItem key={page}>
                      <PaginationLink 
                        onClick={() => setCurrentPage(page)}
                        isActive={currentPage === page}
                      >
                        {page}
                      </PaginationLink>
                    </PaginationItem>
                  ))
                }
                
                {currentPage < totalPages - 2 && (
                  <>
                    {currentPage < totalPages - 3 && <PaginationEllipsis />}
                    <PaginationItem>
                      <PaginationLink onClick={() => setCurrentPage(totalPages)} isActive={currentPage === totalPages}>
                        {totalPages}
                      </PaginationLink>
                    </PaginationItem>
                  </>
                )}
                
                <PaginationItem>
                  <PaginationNext 
                    onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                    className={currentPage === totalPages ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                  />
                </PaginationItem>
              </PaginationContent>
            </Pagination>
          )}
        </div>
      )}
    </div>
  );
});