import { useRef, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useUserRole } from '@/hooks/useUserRole';
import { useAuth } from '@/hooks/useAuth';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { ReportsQueue, ReportsQueueRef } from '@/components/moderation/ReportsQueue';
import { QueueSkeleton } from '@/components/moderation/QueueSkeleton';
import { useAdminSettings } from '@/hooks/useAdminSettings';
import { useModerationStats } from '@/hooks/useModerationStats';

export default function AdminReports() {
  const { user, loading: authLoading } = useAuth();
  const { isModerator, loading: roleLoading } = useUserRole();
  const navigate = useNavigate();
  const reportsQueueRef = useRef<ReportsQueueRef>(null);
  
  const { 
    getAdminPanelRefreshMode, 
    getAdminPanelPollInterval,
  } = useAdminSettings();
  
  const refreshMode = getAdminPanelRefreshMode();
  const pollInterval = getAdminPanelPollInterval();
  
  const { refresh: refreshStats, lastUpdated } = useModerationStats({
    enabled: !!user && !authLoading && !roleLoading && isModerator(),
    pollingEnabled: refreshMode === 'auto',
    pollingInterval: pollInterval,
  });

  const handleRefresh = useCallback(() => {
    reportsQueueRef.current?.refresh();
    refreshStats();
  }, [refreshStats]);

  useEffect(() => {
    if (!authLoading && !roleLoading) {
      if (!user) {
        navigate('/auth');
        return;
      }
      
      if (!isModerator()) {
        navigate('/');
        return;
      }
    }
  }, [user, authLoading, roleLoading, navigate, isModerator]);

  if (authLoading || roleLoading) {
    return (
      <AdminLayout
        onRefresh={handleRefresh}
        refreshMode={refreshMode}
        pollInterval={pollInterval}
        lastUpdated={lastUpdated}
      >
        <div className="space-y-6">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">User Reports</h1>
            <p className="text-muted-foreground mt-1">
              Review and resolve user-submitted reports
            </p>
          </div>

          <QueueSkeleton count={5} />
        </div>
      </AdminLayout>
    );
  }

  if (!user || !isModerator()) {
    return null;
  }

  return (
    <AdminLayout
      onRefresh={handleRefresh}
      refreshMode={refreshMode}
      pollInterval={pollInterval}
      lastUpdated={lastUpdated}
    >
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">User Reports</h1>
          <p className="text-muted-foreground mt-1">
            Review and resolve user-submitted reports
          </p>
        </div>

        <ReportsQueue ref={reportsQueueRef} />
      </div>
    </AdminLayout>
  );
}
