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';
import { getErrorMessage } from '@/lib/errorHandler';

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 () => {
    try {
      // Step 1: Get photo_submission_id from submission_id
      const { data: photoSubmission, error: photoSubmissionError } = await supabase
        .from('photo_submissions')
        .select('id, entity_type, title')
        .eq('submission_id', submissionId)
        .maybeSingle();

      if (photoSubmissionError) {
        throw photoSubmissionError;
      }
      
      if (!photoSubmission) {
        setPhotos([]);
        setLoading(false);
        return;
      }

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

      if (error) {
        throw error;
      }
      
      setPhotos(data || []);
    } catch (error: unknown) {
      const errorMsg = getErrorMessage(error);
      setPhotos([]);
      setError(errorMsg);
    } 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} />;
}
