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';

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
      const { data: itemsData, error: itemsError } = await supabase
        .from('submission_items')
        .select('*')
        .eq('submission_id', submissionId)
        .order('order_index');

      if (itemsError) throw itemsError;

      // 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) {
        console.warn('Error checking photo submissions:', photoError);
      }

      setItems((itemsData || []) as SubmissionItemData[]);
      setHasPhotos(photoData && photoData.length > 0);
    } catch (err) {
      console.error('Error fetching submission items:', 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 (
    <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>
  );
});
