import React, { useRef, useState } from 'react';
import { UploadButtonProps } from '../Button/ButtonTypes';
import Button from '../Button/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;
  const isButtonLoading = loading || isUploading;

  return (
    <>
      <Button
        {...props}
        variant={variant}
        size={size}
        disabled={isDisabled}
        loading={isButtonLoading}
        className={`uploadButton ${className}`}
        onClick={handleClick}
        icon={icon}
        iconPosition={iconPosition}
      >
        {children || (isUploading ? 'Uploading...' : 'Upload File')}
      </Button>
      
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        onChange={handleFileSelect}
        className="hiddenInput"
        disabled={isDisabled}
      />
    </>
  );
};

export default UploadButton;
