import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { PhotoGrid } from '@/components/common/PhotoGrid';
import type { PhotoSubmissionItem } from '@/types/photo-submissions';
import type { PhotoItem } from '@/types/photos';

interface PhotoSubmissionDisplayProps {
  submissionId: string;
}

export function PhotoSubmissionDisplay({ submissionId }: PhotoSubmissionDisplayProps) {
  const [photos, setPhotos] = useState<PhotoSubmissionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const fetchPhotos = async () => {
    console.log('🖼️ PhotoSubmissionDisplay: Starting fetch for submission:', submissionId);
    
    try {
      // Check user auth and roles
      const { data: session } = await supabase.auth.getSession();
      const userId = session?.session?.user?.id;
      console.log('👤 Current user ID:', userId);
      
      if (userId) {
        const { data: roles } = await supabase
          .from('user_roles')
          .select('role')
          .eq('user_id', userId);
        console.log('👤 Current user roles:', roles);
      }

      // Step 1: Get photo_submission_id from submission_id
      console.log('📸 Step 1: Querying photo_submissions table...');
      const { data: photoSubmission, error: photoSubmissionError } = await supabase
        .from('photo_submissions')
        .select('id, entity_type, title')
        .eq('submission_id', submissionId)
        .maybeSingle();

      console.log('📸 Photo submission query result:', { 
        photoSubmission, 
        error: photoSubmissionError 
      });

      if (photoSubmissionError) {
        console.error('❌ Error fetching photo_submission:', photoSubmissionError);
        throw photoSubmissionError;
      }
      
      if (!photoSubmission) {
        console.log('⚠️ No photo_submission found for submission_id:', submissionId);
        setPhotos([]);
        setLoading(false);
        return;
      }

      console.log('✅ Found photo_submission ID:', photoSubmission.id);

      // Step 2: Get photo items using photo_submission_id
      console.log('🖼️ Step 2: Querying photo_submission_items table...');
      const { data, error } = await supabase
        .from('photo_submission_items')
        .select('*')
        .eq('photo_submission_id', photoSubmission.id)
        .order('order_index');

      console.log('🖼️ Photo items query result:', { 
        itemCount: data?.length, 
        error 
      });

      if (error) {
        console.error('❌ Error fetching photo_submission_items:', error);
        throw error;
      }
      
      setPhotos(data || []);
      console.log(`✅ Successfully loaded ${data?.length || 0} photos`);
    } catch (error: any) {
      console.error('❌ PhotoSubmissionDisplay error:', error);
      setPhotos([]);
      setError(error.message || 'Failed to load photos');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div className="text-sm text-muted-foreground">Loading photos...</div>;
  }

  if (error) {
    return (
      <div className="text-sm text-destructive">
        Error loading photos: {error}
        <br />
        <span className="text-xs">Submission ID: {submissionId}</span>
      </div>
    );
  }

  if (photos.length === 0) {
    return (
      <div className="text-sm text-muted-foreground">
        No photos found for this submission
        <br />
        <span className="text-xs text-muted-foreground/60">ID: {submissionId}</span>
      </div>
    );
  }

  // Convert PhotoSubmissionItem[] to PhotoItem[] for PhotoGrid
  const photoItems: PhotoItem[] = photos.map(photo => ({
    id: photo.id,
    url: photo.cloudflare_image_url,
    filename: photo.filename || `Photo ${photo.order_index + 1}`,
    caption: photo.caption,
    title: photo.title,
    date_taken: photo.date_taken,
  }));

  return <PhotoGrid photos={photoItems} />;
}
