import React, { useState } from 'react';
import { X, Save } from 'lucide-react';
import { GalleryImage } from '../../types';
import { ImageUploader } from '../ImageUpload/ImageUploader';

interface GalleryModalProps {
  articleId: string;
  isOpen: boolean;
  onClose: () => void;
  onAddImages: (images: GalleryImage[]) => void;
  editingImage?: GalleryImage | null;
  onUpdateImage?: (image: GalleryImage) => void;
}

export function GalleryModal({
                               articleId,
                               isOpen,
                               onClose,
                               onAddImages,
                               editingImage,
                               onUpdateImage
                             }: GalleryModalProps) {
  const [uploadedImages, setUploadedImages] = useState<GalleryImage[]>([]);
  const [editForm, setEditForm] = useState({
    caption: editingImage?.caption || '',
    alt: editingImage?.alt || ''
  });

  React.useEffect(() => {
    if (editingImage) {
      setEditForm({
        caption: editingImage.caption,
        alt: editingImage.alt
      });
    }
  }, [editingImage]);

  const handleImageUpload = (imageUrl: string) => {
    const newImage: GalleryImage = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      url: imageUrl,
      caption: '',
      alt: '',
      width: 800,     // Примерное значение, можно заменить на динамическое
      height: 600,
      size: 100000,   // Примерное значение
      format: 'webp', // Формат по умолчанию
    };
    setUploadedImages(prev => [...prev, newImage]);
  };

  const handleUpdateImageDetails = (imageId: string, field: 'caption' | 'alt', value: string) => {
    setUploadedImages(prev => prev.map(img =>
        img.id === imageId ? { ...img, [field]: value } : img
    ));
  };

  const handleRemoveUploadedImage = (imageId: string) => {
    setUploadedImages(prev => prev.filter(img => img.id !== imageId));
  };

  const handleSaveImages = () => {
    if (editingImage && onUpdateImage) {
      // Update existing image
      onUpdateImage({
        ...editingImage,
        caption: editForm.caption,
        alt: editForm.alt
      });
    } else {
      // Add new images
      onAddImages(uploadedImages);
    }

    // Reset state
    setUploadedImages([]);
    setEditForm({ caption: '', alt: '' });
    onClose();
  };

  const handleClose = () => {
    setUploadedImages([]);
    setEditForm({ caption: '', alt: '' });
    onClose();
  };

  if (!isOpen) return null;

  return (
      <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
        <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-hidden">
          <div className="flex justify-between items-center p-6 border-b border-gray-200">
            <h3 className="text-lg font-medium text-gray-900">
              {editingImage ? 'Редактирование данных изображения' : 'Добавление изображений в галерею'}
            </h3>
            <button
                onClick={handleClose}
                className="text-gray-400 hover:text-gray-500"
            >
              <X size={24} />
            </button>
          </div>

          <div className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
            {editingImage ? (
                // Edit existing image form
                <div className="space-y-6">
                  <div className="flex justify-center">
                    <img
                        src={editingImage.url}
                        alt={editingImage.alt}
                        className="max-w-md max-h-64 object-contain rounded-lg border"
                    />
                  </div>

                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Подпись
                      </label>
                      <input
                          type="text"
                          value={editForm.caption}
                          onChange={(e) => setEditForm(prev => ({ ...prev, caption: 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="Введите подпись под изображением"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Альтернативный текст
                      </label>
                      <input
                          type="text"
                          value={editForm.alt}
                          onChange={(e) => setEditForm(prev => ({ ...prev, alt: 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="Введите альтернативный текст"
                      />
                    </div>
                  </div>
                </div>
            ) : (
                // Add new images interface
                <div className="space-y-6">
                  <ImageUploader
                      onUploadComplete={handleImageUpload}
                      articleId={articleId}
                  />

                  {uploadedImages.length > 0 && (
                      <div className="space-y-4">
                        <h4 className="text-md font-medium text-gray-900">
                          Загруженные изображения ({uploadedImages.length})
                        </h4>

                        <div className="space-y-4">
                          {uploadedImages.map((image) => (
                              <div key={image.id} className="border rounded-lg p-4">
                                <div className="flex items-start space-x-4">
                                  <img
                                      src={image.url}
                                      alt={image.alt}
                                      className="w-24 h-24 object-cover rounded-lg flex-shrink-0"
                                  />

                                  <div className="flex-1 space-y-3">
                                    <div>
                                      <label className="block text-sm font-medium text-gray-700">
                                        Подпись
                                      </label>
                                      <input
                                          type="text"
                                          value={image.caption}
                                          onChange={(e) => handleUpdateImageDetails(image.id, 'caption', 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="Введите подпись под изображением"
                                      />
                                    </div>

                                    <div>
                                      <label className="block text-sm font-medium text-gray-700">
                                        Альтернативный текст
                                      </label>
                                      <input
                                          type="text"
                                          value={image.alt}
                                          onChange={(e) => handleUpdateImageDetails(image.id, 'alt', 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="Введите альтернативный текст"
                                      />
                                    </div>
                                  </div>

                                  <button
                                      onClick={() => handleRemoveUploadedImage(image.id)}
                                      className="text-red-600 hover:text-red-800 p-2"
                                      title="Remove image"
                                  >
                                    <X size={20} />
                                  </button>
                                </div>
                              </div>
                          ))}
                        </div>
                      </div>
                  )}
                </div>
            )}
          </div>

          <div className="flex justify-end space-x-3 p-6 border-t border-gray-200">
            <button
                onClick={handleClose}
                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"
            >
              Отмена
            </button>
            <button
                onClick={handleSaveImages}
                disabled={editingImage ? false : uploadedImages.length === 0}
                className="inline-flex items-center 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 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Save size={16} className="mr-2" />
              {editingImage ? 'Сохранить изменения' : `Добавить ${uploadedImages.length} фото${uploadedImages.length !== 1 ? '' : ''}`}
            </button>
          </div>
        </div>
      </div>
  );
}