import React, { HTMLAttributes, useRef, useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button } from 'antd';

interface UploadProps extends HTMLAttributes<HTMLLabelElement> {
  trigger?: JSX.Element;
  multiple?: boolean;
  accept?: string;
  disabled?: boolean;
  name?: string | undefined;
  onUpload: (file: any, name?: string) => Promise<void>;
}

const defaultTrigger = (
  <Button type="link">
    <UploadOutlined />
    <span>上传图片</span>
  </Button>
);

const Upload: React.FC<UploadProps> = ({
  trigger = defaultTrigger,
  multiple = false,
  onUpload,
  name,
  accept,
  disabled = false,
}) => {
  const ref = useRef<HTMLFormElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const [loading, setLoading] = useState(false);
  return (
    <>
      <input
        style={{ display: 'none' }}
        type="file"
        accept={accept}
        multiple={multiple}
        disabled={disabled}
        ref={inputRef}
        onChange={async (e) => {
          setLoading(true);
          try {
            const { files } = e.target || {};
            await onUpload?.(files, name);
          } catch (error) {}
          ref.current?.reset?.();
          setLoading(false);
        }}
      />
      {React.cloneElement(trigger, {
        onClick: () => {
          if (loading) return;
          inputRef.current?.click();
        },
      })}
    </>
  );
};
export default Upload;
