
import React, { useState, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Grid } from 'lucide-react';
import { useImageUpload } from '@/hooks/useImageUpload';
import UploadTabs from './image-upload/UploadTabs';
import UploadProgress from './image-upload/UploadProgress';
import ImageGallery from './image-upload/ImageGallery';
import ImagePreview from './image-upload/ImagePreview';
import FileUploadZone from './image-upload/FileUploadZone';
import URLInput from './image-upload/URLInput';

interface ImageUploaderProps {
  value: string;
  onChange: (value: string) => void;
  label: string;
  aspectRatio: number;
  previewClassName?: string;
  description?: string;
  required?: boolean;
}

const ImageUploader = ({
  value,
  onChange,
  label,
  aspectRatio,
  previewClassName = "w-full max-w-md",
  description,
  required = false
}: ImageUploaderProps) => {
  const [dragActive, setDragActive] = useState(false);
  const [urlInput, setUrlInput] = useState('');
  const [showGallery, setShowGallery] = useState(false);
  
  const { uploadImage, uploading, progress, validateImageDimensions } = useImageUpload({
    folder: aspectRatio === 1 ? 'avatars' : 'projects',
    enableCompression: true
  });

  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  }, []);

  const handleDrop = useCallback(async (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      await handleFileUpload(e.dataTransfer.files[0]);
    }
  }, []);

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      await handleFileUpload(e.target.files[0]);
    }
  };

  const handleFileUpload = async (file: File) => {
    const isValid = await validateImageDimensions(
      file,
      aspectRatio === 1 ? 100 : 400,
      aspectRatio === 1 ? 100 : 200
    );
    
    if (!isValid) return;

    const url = await uploadImage(file);
    if (url) {
      onChange(url);
    }
  };

  const handleUrlSubmit = () => {
    if (urlInput.trim()) {
      onChange(urlInput.trim());
      setUrlInput('');
    }
  };

  const clearImage = () => {
    onChange('');
  };

  const handleGallerySelect = (url: string) => {
    onChange(url);
    setShowGallery(false);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label className="text-sm font-medium">
          {label} {required && '*'}
        </Label>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => setShowGallery(!showGallery)}
        >
          <Grid className="h-4 w-4 mr-1" />
          Galerie
        </Button>
      </div>

      {description && (
        <p className="text-sm text-gray-600">{description}</p>
      )}

      {showGallery && (
        <Card>
          <CardContent className="pt-4">
            <ImageGallery
              onSelect={handleGallerySelect}
              aspectRatio={aspectRatio}
              folder={aspectRatio === 1 ? 'avatars' : 'projects'}
            />
          </CardContent>
        </Card>
      )}

      <UploadProgress progress={progress} uploading={uploading} />

      <ImagePreview
        value={value}
        aspectRatio={aspectRatio}
        previewClassName={previewClassName}
        onClear={clearImage}
        disabled={uploading}
      />

      {!value && (
        <Card className={previewClassName}>
          <CardContent className="p-4">
            <UploadTabs>
              {{
                uploadContent: (
                  <FileUploadZone
                    aspectRatio={aspectRatio}
                    dragActive={dragActive}
                    uploading={uploading}
                    onDragEnter={handleDrag}
                    onDragLeave={handleDrag}
                    onDragOver={handleDrag}
                    onDrop={handleDrop}
                    onFileSelect={handleFileSelect}
                  />
                ),
                urlContent: (
                  <URLInput
                    value={urlInput}
                    onChange={setUrlInput}
                    onSubmit={handleUrlSubmit}
                    disabled={uploading}
                  />
                )
              }}
            </UploadTabs>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default ImageUploader;
