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<ReportsQueueRef>((props, ref) => {
  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 { 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 (
      <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>
    );
  }

  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>
      )}

      {reports.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' && (
                    <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>
                  )}
                </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>
      ))}
    </div>
  );
});