import { useState } from 'react';
import { ImageDropzone } from './ImageDropzone';
import { ResolutionSelect } from './ResolutionSelect';
import { UploadProgress } from './UploadProgress';
import { imageResolutions } from '../../config/imageResolutions';
import { uploadImageToS3 } from '../../services/imageService';
import { ImageUploadProgress } from '../../types/image';

interface ImageUploaderProps {
  onUploadComplete: (imageUrl: string) => void;
  articleId: string;
}

export function ImageUploader({ onUploadComplete, articleId }: ImageUploaderProps) {
  const [selectedResolution, setSelectedResolution] = useState('medium');
  const [uploadProgress, setUploadProgress] = useState<Record<string, ImageUploadProgress>>({});

  const handleDrop = async (files: File[]) => {
    for (const file of files) {
      try {
        setUploadProgress(prev => ({
          ...prev,
          [file.name]: { progress: 0, status: 'uploading' },
        }));

        const resolution = imageResolutions.find(r => r.id === selectedResolution);
        if (!resolution) throw new Error('Выбрано неправильное разрешение');

        const uploadedImage = await uploadImageToS3(file, resolution, articleId, (progress) => {
          setUploadProgress(prev => ({
            ...prev,
            [file.name]: { progress, status: 'uploading' },
          }));
        });

        setUploadProgress(prev => ({
          ...prev,
          [file.name]: {
            progress: 100,
            status: 'complete',
            imageUrl: uploadedImage.url, // Сохраняем URL изображения
          },
        }));

        onUploadComplete(uploadedImage.url);
      } catch (error) {
        setUploadProgress(prev => ({
          ...prev,
          [file.name]: {
            progress: 0,
            status: 'error',
            error: error instanceof Error ? error.message : 'Upload failed',
          }
        }));
      }
    }
  };

  const isUploading = Object.values(uploadProgress).some(
    p => p.status === 'uploading' || p.status === 'processing'
  );

  return (
    <div className="space-y-6">
      <ResolutionSelect
        resolutions={imageResolutions}
        selectedResolution={selectedResolution}
        onChange={setSelectedResolution}
        disabled={isUploading}
      />
      
      <ImageDropzone
        onDrop={handleDrop}
        disabled={isUploading}
      />

      {Object.entries(uploadProgress).map(([fileName, progress]) => (
        <UploadProgress
          key={fileName}
          fileName={fileName}
          progress={progress}
        />
      ))}
    </div>
  );
}