import { useState, useEffect } 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 } from 'lucide-react';
import type { SubmissionItemData } from '@/types/submissions';

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

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

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

  const fetchSubmissionItems = async () => {
    try {
      setLoading(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
      const { data: photoData, error: photoError } = await supabase
        .from('photo_submissions')
        .select('id')
        .eq('submission_id', submissionId)
        .single();

      if (photoError && photoError.code !== 'PGRST116') {
        console.warn('Error checking photo submissions:', photoError);
      }

      setItems((itemsData || []) as SubmissionItemData[]);
      setHasPhotos(!!photoData);
    } catch (err) {
      console.error('Error fetching submission items:', err);
      setError('Failed to load submission details');
    } finally {
      setLoading(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">
      {/* 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}
          />
        </div>
      ))}

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