import React, { useRef, useState } from 'react';
import { UploadButtonProps } from '../ButtonTypes';
import Button from '../Button';

const UploadButton: React.FC<UploadButtonProps> = ({
  onUpload,
  accept = '*/*',
  multiple = false,
  disabled = false,
  loading = false,
  className = '',
  children,
  icon,
  iconPosition = 'left',
  variant = 'primary',
  size = 'md',
  ...props
}) => {
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    setIsUploading(true);
    
    try {
      if (multiple) {
        // Handle multiple files
        for (let i = 0; i < files.length; i++) {
          await onUpload(files[i]);
        }
      } else {
        // Handle single file
        await onUpload(files[0]);
      }
    } catch (error) {
      console.error('Upload failed:', error);
      // Error handling is done by the parent component
    } finally {
      setIsUploading(false);
      // Reset the input so the same file can be selected again
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleClick = () => {
    if (!disabled && !loading && !isUploading) {
      fileInputRef.current?.click();
    }
  };

  const isDisabled = disabled || loading || isUploading;

  return (
    <>
      <Button
        {...props}
        variant={variant}
        size={size}
        disabled={isDisabled}
        loading={false} // We handle the loading state manually
        className={`uploadButton ${className}`}
        onClick={handleClick}
        icon={isUploading ? undefined : icon} // Hide original icon when uploading
        iconPosition={iconPosition}
      >
        {isUploading && (
          <div className="spinnerIcon" style={{ marginRight: '8px' }} />
        )}
        {children || (isUploading ? 'Uploading...' : 'Upload File')}
      </Button>
      
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        onChange={handleFileSelect}
        className="hiddenInput"
        disabled={isDisabled}
      />
    </>
  );
};

export default UploadButton;
