import { useState, useEffect, memo } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { SubmissionChangesDisplay } from './SubmissionChangesDisplay';
import { PhotoSubmissionDisplay } from './PhotoSubmissionDisplay';
import { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { AlertCircle, Loader2 } from 'lucide-react';
import type { SubmissionItemData } from '@/types/submissions';
import { logger } from '@/lib/logger';
import { getErrorMessage } from '@/lib/errorHandler';
import { ModerationErrorBoundary } from '@/components/error/ModerationErrorBoundary';

interface SubmissionItemsListProps {
  submissionId: string;
  view?: 'summary' | 'detailed';
  showImages?: boolean;
}

export const SubmissionItemsList = memo(function SubmissionItemsList({
  submissionId, 
  view = 'summary',
  showImages = true 
}: SubmissionItemsListProps) {
  const [items, setItems] = useState<SubmissionItemData[]>([]);
  const [hasPhotos, setHasPhotos] = useState(false);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchSubmissionItems();
  }, [submissionId]);

  const fetchSubmissionItems = async () => {
    try {
      // Only show skeleton on initial load, show refreshing indicator on refresh
      if (loading) {
        setLoading(true);
      } else {
        setRefreshing(true);
      }
      setError(null);

      // Fetch submission items with relational data
      const { data: itemsData, error: itemsError } = await supabase
        .from('submission_items')
        .select(`
          *,
          park_submission:park_submissions!item_data_id(*),
          ride_submission:ride_submissions!item_data_id(*)
        `)
        .eq('submission_id', submissionId)
        .order('order_index');

      if (itemsError) throw itemsError;

      // Transform to include item_data
      const transformedItems = itemsData?.map(item => {
        let itemData = {};
        switch (item.item_type) {
          case 'park':
            itemData = item.park_submission || {};
            break;
          case 'ride':
            itemData = item.ride_submission || {};
            break;
          default:
            itemData = {};
        }
        return { ...item, item_data: itemData };
      }) || [];

      // Check for photo submissions (using array query to avoid 406)
      const { data: photoData, error: photoError } = await supabase
        .from('photo_submissions')
        .select('id')
        .eq('submission_id', submissionId);

      if (photoError) {
        logger.warn('Error checking photo submissions:', photoError);
      }

      setItems(transformedItems as SubmissionItemData[]);
      setHasPhotos(!!(photoData && photoData.length > 0));
    } catch (err) {
      logger.error('Failed to fetch submission items', { error: getErrorMessage(err) });
      setError('Failed to load submission details');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  if (loading) {
    return (
      <div className="flex flex-col gap-2">
        <Skeleton className="h-16 w-full" />
        {view === 'detailed' && <Skeleton className="h-32 w-full" />}
      </div>
    );
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>{error}</AlertDescription>
      </Alert>
    );
  }

  if (items.length === 0 && !hasPhotos) {
    return (
      <div className="text-sm text-muted-foreground">
        No items found for this submission
      </div>
    );
  }

  return (
    <ModerationErrorBoundary submissionId={submissionId}>
      <div className="flex flex-col gap-3">
        {refreshing && (
          <div className="flex items-center gap-2 text-xs text-muted-foreground">
            <Loader2 className="h-3 w-3 animate-spin" />
            <span>Refreshing...</span>
          </div>
        )}
        
        {/* Show regular submission items */}
        {items.map((item) => (
          <div key={item.id} className={view === 'summary' ? 'border-l-2 border-primary/20 pl-3' : ''}>
            <SubmissionChangesDisplay 
              item={item}
              view={view}
              showImages={showImages}
              submissionId={submissionId}
            />
          </div>
        ))}

        {/* Show photo submission if exists */}
        {hasPhotos && (
          <div className={view === 'summary' ? 'border-l-2 border-primary/20 pl-3' : ''}>
            <PhotoSubmissionDisplay submissionId={submissionId} />
          </div>
        )}
      </div>
    </ModerationErrorBoundary>
  );
});
