import { useState } from 'react';
import { GalleryImage } from '../../types';
import { GalleryPreview } from './GalleryPreview';
import { GalleryModal } from './GalleryModal';

interface GalleryManagerProps {
  articleId: string;
  images: GalleryImage[];
  onChange: (images: GalleryImage[]) => void;
}

export function NewGalleryManager({ articleId, images, onChange }: GalleryManagerProps) {
  const [showModal, setShowModal] = useState(false);
  const [editingImage, setEditingImage] = useState<GalleryImage | null>(null);

  const handleAddImages = (newImages: GalleryImage[]) => {
    onChange([...images, ...newImages]);
    setShowModal(false);
  };

  const handleEditImage = (image: GalleryImage) => {
    setEditingImage(image);
    setShowModal(true);
  };

  const handleUpdateImage = (updatedImage: GalleryImage) => {
    onChange(images.map(img => img.id === updatedImage.id ? updatedImage : img));
    setEditingImage(null);
    setShowModal(false);
  };

  const handleDeleteImage = (id: string) => {
    onChange(images.filter(img => img.id !== id));
  };

  const handleReorderImages = (dragIndex: number, dropIndex: number) => {
    const reorderedImages = [...images];
    const [draggedImage] = reorderedImages.splice(dragIndex, 1);
    reorderedImages.splice(dropIndex, 0, draggedImage);
    onChange(reorderedImages);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setEditingImage(null);
  };

  return (
      <>
        <GalleryPreview
            images={images}
            onAddImage={() => setShowModal(true)}
            onEditImage={handleEditImage}
            onDeleteImage={handleDeleteImage}
            onReorderImages={handleReorderImages}
        />

        <GalleryModal
            articleId={articleId}
            isOpen={showModal}
            onClose={handleCloseModal}
            onAddImages={handleAddImages}
            editingImage={editingImage}
            onUpdateImage={handleUpdateImage}
        />
      </>
  );
}