import React, { useState } from 'react';
import { ImagePlus } from 'lucide-react';
import { Editor } from '@tiptap/react';
import ImageUploadModal from '../ImageUploadModal';
import {imageResolutions} from "../../config/imageResolutions.ts";
import axios from "axios";

interface TipTapImageUploadButtonProps {
  editor: Editor;
  articleId: string;
}

const TipTapImageUploadButton: React.FC<TipTapImageUploadButtonProps> = ({ editor, articleId }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleImageUpload = async (file: File | null, caption: string) => {
    if (!file) return;

    try {
      const resolution = imageResolutions.find((r) => r.id === 'large');
      if (!resolution) throw new Error('Недопустимое значение разрешения');

      const formData = new FormData();
      formData.append('file', file);
      formData.append('resolutionId', resolution.id);
      formData.append('folder', `articles/${articleId}`);

      const response = await axios.post('/api/images/upload-url', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });

      const uploadedUrl = response.data?.fileUrl;

      if (uploadedUrl) {
        editor
            .chain()
            .focus()
            .command(({ tr, dispatch }) => {
              const node = editor.schema.nodes.customImage.create({
                src: uploadedUrl,
                alt: file.name,
                scale: 1, // Начальный масштаб
                caption: caption,
              });
              if (dispatch) {
                tr.insert(editor.state.selection.anchor, node);
                dispatch(tr);
              }
              return true;
            })
            .run();
      } else {
        throw new Error('Сервер не вернул URL файла изображения');
      }
    } catch (error) {
      console.error('Ошибка загрузки изображения:', error);
    } finally {
      setIsModalOpen(false);
    }
  };

  return (
      <>
        <button
            type="button"
            onClick={() => setIsModalOpen(true)}
            className="p-2 hover:bg-gray-200 rounded"
            title="Добавить изображение"
        >
          <ImagePlus className="w-5 h-5" />
        </button>
        <ImageUploadModal
            isOpen={isModalOpen}
            onConfirm={handleImageUpload}
            onCancel={() => setIsModalOpen(false)}
        />
      </>
  );
};

export default TipTapImageUploadButton;