import { useRef, useCallback } from 'react';
import { useAdminGuard } from '@/hooks/useAdminGuard';
import { MFARequiredAlert } from '@/components/auth/MFARequiredAlert';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { ModerationQueue, ModerationQueueRef } from '@/components/moderation/ModerationQueue';
import { QueueSkeleton } from '@/components/moderation/QueueSkeleton';
import { useAdminSettings } from '@/hooks/useAdminSettings';
import { useModerationStats } from '@/hooks/useModerationStats';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

export default function AdminModeration() {
  useDocumentTitle('Moderation Queue - Admin');
  const { isLoading, isAuthorized, needsMFA, user } = useAdminGuard();
  const moderationQueueRef = useRef<ModerationQueueRef>(null);
  
  const { 
    getAdminPanelRefreshMode, 
    getAdminPanelPollInterval,
  } = useAdminSettings();
  
  const refreshMode = getAdminPanelRefreshMode();
  const pollInterval = getAdminPanelPollInterval();
  
  const { lastUpdated } = useModerationStats({
    enabled: isAuthorized,
    pollingEnabled: refreshMode === 'auto',
    pollingInterval: pollInterval,
  });

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

  if (isLoading) {
    return (
      <AdminLayout
        onRefresh={handleRefresh}
        refreshMode={refreshMode}
        pollInterval={pollInterval}
        lastUpdated={lastUpdated ?? undefined}
      >
        <div className="space-y-6">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">Moderation Queue</h1>
            <p className="text-muted-foreground mt-1">
              Review and manage pending content submissions
            </p>
          </div>

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

  if (!isAuthorized) {
    return null;
  }
  
  if (needsMFA) {
    return (
      <AdminLayout>
        <MFARequiredAlert />
      </AdminLayout>
    );
  }

  return (
    <AdminLayout
      onRefresh={handleRefresh}
      refreshMode={refreshMode}
      pollInterval={pollInterval}
      lastUpdated={lastUpdated ?? undefined}
    >
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Moderation Queue</h1>
          <p className="text-muted-foreground mt-1">
            Review and manage pending content submissions
          </p>
        </div>

        <ModerationQueue ref={moderationQueueRef} />
      </div>
    </AdminLayout>
  );
}
