import { useState } from 'react';
import { X, Plus, Move, Pencil, Trash2 } from 'lucide-react';
import { GalleryImage } from '../types';

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">Добавить новое фото</h3>
        <div className="space-y-3">
          <div>
            <label htmlFor="imageUrl" className="block text-sm font-medium text-gray-700">
              <span className="italic font-bold">URL изображения</span>
            </label>
            <input
              type="url"
              id="imageUrl"
              value={newImageUrl}
              onChange={(e) => setNewImageUrl(e.target.value)}
              className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
              placeholder="https://example.com/image.jpg"
            />
          </div>
          <div>
            <label htmlFor="imageCaption" className="block text-sm font-medium text-gray-700">
              <span className="italic font-bold">Заголовок</span>
            </label>
            <input
              type="text"
              id="imageCaption"
              value={newImageCaption}
              onChange={(e) => setNewImageCaption(e.target.value)}
              className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
            />
          </div>
          <div>
            <label htmlFor="imageAlt" className="block text-sm font-medium text-gray-700">
              <span className="italic font-bold">Текст при наведении на изображение</span>
            </label>
            <input
              type="text"
              id="imageAlt"
              value={newImageAlt}
              onChange={(e) => setNewImageAlt(e.target.value)}
              className="px-2 py-1 mt-1 block w-full rounded-lg border border-gray-300 shadow-sm hover:border-blue-300 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition-all duration-200"
            />
          </div>
          <button
            onClick={handleAddImage}
            disabled={!newImageUrl.trim()}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Plus size={16} className="mr-2" />
            Добавить фото
          </button>
        </div>
      </div>

      {/* Gallery Preview */}
      <div className="border rounded-lg p-4">
        <h3 className="text-lg font-medium text-gray-900 mb-4">Состав галереи</h3>
        <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
          {images.map((image, index) => (
            <div
              key={image.id}
              className="relative group border rounded-lg overflow-hidden"
              draggable
              onDragStart={(e) => e.dataTransfer.setData('text/plain', index.toString())}
              onDragOver={(e) => e.preventDefault()}
              onDrop={(e) => {
                e.preventDefault();
                const dragIndex = parseInt(e.dataTransfer.getData('text/plain'));
                handleReorder(dragIndex, index);
              }}
            >
              <img
                src={image.url}
                alt={image.alt}
                className="w-full h-48 object-cover"
              />
              <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-opacity duration-200">
                <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                  <div className="flex space-x-2">
                    <button
                      onClick={() => setEditingImage(image)}
                      className="p-2 bg-white rounded-full text-gray-700 hover:text-blue-600"
                    >
                      <Pencil size={16} />
                    </button>
                    <button
                      onClick={() => handleRemoveImage(image.id)}
                      className="p-2 bg-white rounded-full text-gray-700 hover:text-red-600"
                    >
                      <Trash2 size={16} />
                    </button>
                    <button className="p-2 bg-white rounded-full text-gray-700 cursor-move">
                      <Move size={16} />
                    </button>
                  </div>
                </div>
              </div>
              <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white p-2 text-sm">
                {image.caption}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Edit Image Modal */}
      {editingImage && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-md w-full p-6">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-medium text-gray-900">Edit Image</h3>
              <button
                onClick={() => setEditingImage(null)}
                className="text-gray-400 hover:text-gray-500"
              >
                <X size={20} />
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Image URL
                </label>
                <input
                  type="url"
                  value={editingImage.url}
                  onChange={(e) => setEditingImage({ ...editingImage, url: e.target.value })}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Caption
                </label>
                <input
                  type="text"
                  value={editingImage.caption}
                  onChange={(e) => setEditingImage({ ...editingImage, caption: e.target.value })}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700">
                  Alt Text
                </label>
                <input
                  type="text"
                  value={editingImage.alt}
                  onChange={(e) => setEditingImage({ ...editingImage, alt: e.target.value })}
                  className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                />
              </div>
              <div className="flex justify-end space-x-3">
                <button
                  onClick={() => setEditingImage(null)}
                  className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  Cancel
                </button>
                <button
                  onClick={() => handleUpdateImage(editingImage)}
                  className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  Save Changes
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}