import { useState, useEffect } 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';

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 function ReportsQueue() {
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const { toast } = useToast();

  const fetchReports = async () => {
    try {
      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,
          };
        })
      );

      setReports(reportsWithContent);
    } catch (error) {
      console.error('Error fetching reports:', error);
      toast({
        title: "Error",
        description: "Failed to load reports queue",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchReports();
  }, []);

  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">
      {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>
  );
}