import { useState, useEffect } from 'react';
import { GalleryImage } from '../types';
import { galleryService } from '../services/galleryService';
import { uploadImage } from '../services/imageService';
import { ImageResolution } from '../types/image';

export function useGallery(articleId: string) {
  const [images, setImages] = useState<GalleryImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadGallery();
  }, [articleId]);

  const loadGallery = async () => {
    try {
      setLoading(true);
      const galleryImages = await galleryService.getArticleGallery(articleId);
      setImages(galleryImages);
      setError(null);
    } catch (err) {
      setError('Failed to load gallery images');
      console.error('Error loading gallery:', err);
    } finally {
      setLoading(false);
    }
  };

  const addImage = async (file: File, resolution: ImageResolution) => {
    try {
      const uploadedImage = await uploadImage(file, resolution);
      const galleryImage = await galleryService.createImage(articleId, {
        url: uploadedImage.url,
        caption: '',
        alt: file.name,
        width: uploadedImage.width,
        height: uploadedImage.height,
        size: uploadedImage.size,
        format: uploadedImage.format
      });
      setImages([...images, galleryImage]);
      return galleryImage;
    } catch (err) {
      console.error('Error adding image:', err);
      throw err;
    }
  };

  const updateImage = async (id: string, updates: Partial<GalleryImage>) => {
    try {
      const updatedImage = await galleryService.updateImage(id, updates);
      setImages(images.map(img => img.id === id ? updatedImage : img));
      return updatedImage;
    } catch (err) {
      console.error('Error updating image:', err);
      throw err;
    }
  };

  const deleteImage = async (id: string) => {
    try {
      await galleryService.deleteImage(id);
      setImages(images.filter(img => img.id !== id));
    } catch (err) {
      console.error('Error deleting image:', err);
      throw err;
    }
  };

  const reorderImages = async (imageIds: string[]) => {
    try {
      await galleryService.reorderImages(articleId, imageIds);
      const reorderedImages = imageIds.map(id => 
        images.find(img => img.id === id)!
      );
      setImages(reorderedImages);
    } catch (err) {
      console.error('Error reordering images:', err);
      throw err;
    }
  };

  return {
    images,
    loading,
    error,
    addImage,
    updateImage,
    deleteImage,
    reorderImages,
    refresh: loadGallery
  };
}