import { useState, useEffect } from 'react';
import { Camera, Upload, LogIn, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useAuth } from '@/hooks/useAuth';
import { useNavigate } from 'react-router-dom';
import { UppyPhotoSubmissionUpload } from '@/components/upload/UppyPhotoSubmissionUpload';
import { PhotoManagementDialog } from '@/components/upload/PhotoManagementDialog';
import { PhotoModal } from '@/components/moderation/PhotoModal';
import { supabase } from '@/integrations/supabase/client';
import { EntityPhotoGalleryProps } from '@/types/submissions';
import { useUserRole } from '@/hooks/useUserRole';

interface Photo {
  id: string;
  url: string;
  caption?: string;
  title?: string;
  user_id: string;
  created_at: string;
}

export function EntityPhotoGallery({ 
  entityId, 
  entityType, 
  entityName,
  parentId 
}: EntityPhotoGalleryProps) {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { isModerator } = useUserRole();
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [showUpload, setShowUpload] = useState(false);
  const [showManagement, setShowManagement] = useState(false);
  const [loading, setLoading] = useState(true);
  const [selectedPhotoIndex, setSelectedPhotoIndex] = useState<number | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

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

  const fetchPhotos = async () => {
    try {
      console.log('📷 [FETCH PHOTOS] Starting fetch for:', { entityId, entityType });
      
      // Fetch photos directly from the photos table
      const { data: photoData, error } = await supabase
        .from('photos')
        .select('id, cloudflare_image_url, title, caption, submitted_by, created_at, order_index')
        .eq('entity_type', entityType)
        .eq('entity_id', entityId)
        .order('order_index', { ascending: true })
        .order('created_at', { ascending: false });

      console.log('📷 [FETCH PHOTOS] Query result:', { photoData, error, count: photoData?.length });

      if (error) throw error;

      // Map to Photo interface
      const mappedPhotos: Photo[] = photoData?.map((photo) => ({
        id: photo.id,
        url: photo.cloudflare_image_url,
        caption: photo.caption || undefined,
        title: photo.title || undefined,
        user_id: photo.submitted_by,
        created_at: photo.created_at,
      })) || [];

      console.log('📷 [FETCH PHOTOS] Mapped photos:', mappedPhotos);
      setPhotos(mappedPhotos);
    } catch (error) {
      console.error('📷 [FETCH PHOTOS] Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleUploadClick = () => {
    if (!user) {
      navigate('/auth');
      return;
    }
    setShowUpload(true);
  };

  const handleSubmissionComplete = () => {
    setShowUpload(false);
    fetchPhotos(); // Refresh photos after submission
  };

  const handlePhotoClick = (index: number) => {
    setSelectedPhotoIndex(index);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedPhotoIndex(null);
  };

  if (showUpload) {
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold">Upload Photos for {entityName}</h3>
          <Button variant="ghost" onClick={() => setShowUpload(false)}>
            Back to Gallery
          </Button>
        </div>
        <UppyPhotoSubmissionUpload
          entityId={entityId}
          entityType={entityType}
          parentId={parentId}
          onSubmissionComplete={handleSubmissionComplete}
        />
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-pulse flex items-center gap-3">
          <Camera className="w-8 h-8 text-muted-foreground" />
          <span className="text-muted-foreground">Loading photos...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header with Upload and Management Buttons */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Photo Gallery</h3>
          <p className="text-sm text-muted-foreground">
            Share your photos of {entityName}
          </p>
        </div>
        <div className="flex gap-2">
          {isModerator && photos.length > 0 && (
            <Button onClick={() => setShowManagement(true)} variant="outline" className="gap-2">
              <Settings className="w-4 h-4" />
              Manage
            </Button>
          )}
          <Button onClick={handleUploadClick} className="gap-2">
            {user ? (
              <>
                <Upload className="w-4 h-4" />
                Upload Photos
              </>
            ) : (
              <>
                <LogIn className="w-4 h-4" />
                Sign in to Upload
              </>
            )}
          </Button>
        </div>
      </div>

      {/* Photo Management Dialog */}
      <PhotoManagementDialog
        entityId={entityId}
        entityType={entityType}
        open={showManagement}
        onOpenChange={setShowManagement}
        onUpdate={fetchPhotos}
      />

      {/* Photo Grid */}
      {photos.length > 0 ? (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {photos.map((photo, index) => (
            <Card key={photo.id} className="overflow-hidden">
              <CardContent className="p-0">
                <img
                  src={photo.url}
                  alt={photo.title || photo.caption || `${entityName} photo`}
                  className="w-full h-48 object-cover hover:scale-105 transition-transform cursor-pointer"
                  onClick={() => handlePhotoClick(index)}
                />
                {(photo.title || photo.caption) && (
                  <div className="p-3">
                    {photo.title && (
                      <h4 className="font-medium text-sm truncate">{photo.title}</h4>
                    )}
                    {photo.caption && (
                      <p className="text-xs text-muted-foreground truncate mt-1">
                        {photo.caption}
                      </p>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <div className="text-center py-12">
          <Camera className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
          <h3 className="text-xl font-semibold mb-2">No Photos Yet</h3>
          <p className="text-muted-foreground mb-4">
            Be the first to share photos of {entityName}!
          </p>
          <Button onClick={handleUploadClick} className="gap-2">
            {user ? (
              <>
                <Upload className="w-4 h-4" />
                Upload First Photo
              </>
            ) : (
              <>
                <LogIn className="w-4 h-4" />
                Sign in to Upload
              </>
            )}
          </Button>
        </div>
      )}

      {/* Photo Lightbox Modal */}
      {selectedPhotoIndex !== null && (
        <PhotoModal
          photos={photos.map(photo => ({
            id: photo.id,
            url: photo.url,
            caption: photo.caption,
            filename: photo.title,
          }))}
          initialIndex={selectedPhotoIndex}
          isOpen={isModalOpen}
          onClose={handleCloseModal}
        />
      )}
    </div>
  );
}
