import React, { useState, useEffect } from 'react';

interface ImageUploadModalProps {
  isOpen: boolean;
  onConfirm: (file: File | null, caption: string) => void;
  onCancel: () => void;
}

const ImageUploadModal: React.FC<ImageUploadModalProps> = ({ isOpen, onConfirm, onCancel }) => {
  const [file, setFile] = useState<File | null>(null);
  const [caption, setCaption] = useState('');
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!isOpen) {
      setFile(null);
      setCaption('');
      setError(null);
    }
  }, [isOpen]);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      if (!selectedFile.type.startsWith('image/')) {
        setError('Пожалуйста, выберите файл изображения');
        setFile(null);
        return;
      }
      setFile(selectedFile);
      setError(null);
    }
  };

  const handleApply = () => {
    if (!file) {
      setError('Пожалуйста, выберите изображение');
      return;
    }
    onConfirm(file, caption);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleApply();
    } else if (e.key === 'Escape') {
      onCancel();
    }
  };

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (e.target === e.currentTarget) {
      onCancel();
    }
  };

  if (!isOpen) return null;

  return (
      <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 transition-opacity duration-300 ease-in-out"
          onClick={handleBackdropClick}
      >
        <div className="bg-white rounded-lg p-6 max-w-sm w-full transform transition-all duration-300 ease-in-out scale-100 opacity-100">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Добавить фото</h3>
          <div>
            <input
                type="file"
                accept="image/*"
                onChange={handleFileChange}
                className="w-full p-2 border rounded-md mb-4"
            />
            <input
                type="text"
                value={caption}
                onChange={(e) => setCaption(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder="Введите подпись (опционально)"
                className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 mb-4 border-gray-300"
            />
            {error && <p className="text-red-500 text-sm mb-4">{error}</p>}
            <div className="flex justify-end space-x-3">
              <button
                  type="button"
                  onClick={onCancel}
                  className="px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
              >
                Отмена
              </button>
              <button
                  type="button"
                  onClick={handleApply}
                  className="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
              >
                Применить
              </button>
            </div>
          </div>
        </div>
      </div>
  );
};

export default ImageUploadModal;