import { useState } from 'react';
import { GalleryImage } from '../../types';
import { GalleryGrid } from './GalleryGrid';
import { ImageForm } from './ImageForm';
import { EditImageModal } from './EditImageModal';

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

export function GalleryManager({ images, onChange }: GalleryManagerProps) {
  const [editingImage, setEditingImage] = useState<GalleryImage | null>(null);
  const [newImageUrl, setNewImageUrl] = useState('');
  const [newImageCaption, setNewImageCaption] = useState('');
  const [newImageAlt, setNewImageAlt] = useState('');

  const handleAddImage = () => {
    if (!newImageUrl.trim()) return;

    const newImage: GalleryImage = {
      id: Date.now().toString(),
      url: newImageUrl,
      caption: newImageCaption,
      alt: newImageAlt || newImageCaption
    };

    onChange([...images, newImage]);
    setNewImageUrl('');
    setNewImageCaption('');
    setNewImageAlt('');
  };

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

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

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

  return (
    <div className="space-y-6">
      {/* Add New Image */}
      <div className="border rounded-lg p-4 space-y-4">
        <h3 className="text-lg font-medium text-gray-900">Add New Image</h3>
        <ImageForm
          url={newImageUrl}
          caption={newImageCaption}
          alt={newImageAlt}
          onUrlChange={setNewImageUrl}
          onCaptionChange={setNewImageCaption}
          onAltChange={setNewImageAlt}
          onSubmit={handleAddImage}
          submitLabel="Add Image"
        />
      </div>

      {/* Gallery Preview */}
      <div className="border rounded-lg p-4">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Gallery Images</h3>
        <GalleryGrid
          images={images}
          onEdit={setEditingImage}
          onDelete={handleRemoveImage}
          onReorder={handleReorder}
        />
      </div>

      {/* Edit Image Modal */}
      {editingImage && (
        <EditImageModal
          image={editingImage}
          onClose={() => setEditingImage(null)}
          onSave={handleUpdateImage}
        />
      )}
    </div>
  );
}