import { useState } from 'react';
import Uppy from '@uppy/core';
import XHRUpload from '@uppy/xhr-upload';
import { DashboardModal, useUppy } from '@uppy/react';
import '@uppy/core/dist/style.css';
import '@uppy/dashboard/dist/style.css';
import '@uppy/progress-bar/dist/style.css';
import '@uppy/status-bar/dist/style.css';
import { useToasts } from '@geist-ui/react';
import { Result } from '../pages/api/upload';
export default function Uploader({ file, onClose }: { file: string; onClose(s: string): void; }) {
	const endpoint = '/api/upload';
	const getfile = '/api/getfile/';
	const [filepath, setfilepath] = useState(file);
	const [, toast] = useToasts();
	const [open, setopen] = useState(false);
	const uppy = useUppy(() => {
		const uppy = Uppy({
			allowMultipleUploads: false,
			autoProceed: true,
			debug: true,
			restrictions: {
				maxFileSize: 10737418240,	
				maxNumberOfFiles: 1,
				minNumberOfFiles: 1,
				allowedFileTypes: ['application/x-7z-compressed', 'application/x-gzip', 'application/zip', 'application/x-rar']
			}
		});
		uppy.use(XHRUpload, {
			fieldName: 'file',
			formData: true,
			method: 'PUT',
			endpoint,
			timeout: 1000 * 60 * 10	
		});
		uppy.on('complete', (result) => {
			
			const [success] = result.successful;
			if (success) {
				const ret = success.response.body as Result;
				if (ret.ok) {
					toast({
						text: '上传成功',
						type: 'success'
					});
					const file = getfile + ret.fileid;
					setfilepath(file);
					setopen(false);
					onClose(file);
				} else {
					toast({
						text: '上传失败',
						type: 'error'
					});
					setfilepath('');
				}
			}
		});
		uppy.on('error', () => {
			toast({
				text: '上传失败',
				type: 'error'
			});
			setfilepath('');
		});
		return uppy;
	});
	return <>
		<div>
			{filepath && <a href={filepath} download>下载</a>}
		</div>
		<input type='button' value='上传文件...' onClick={() => {
			setopen(true);
		}} />
		<DashboardModal closeModalOnClickOutside uppy={uppy} open={open}
			onRequestClose={() => {
				setopen(false);
			}} />
		<style jsx>{`
input{
margin:10px;
padding-top:10px;
padding-bottom:10px;
padding-left:50px;
padding-right:50px;
border-style: none;
background-color: #202523a1;
color: #ffd00071;
border-radius: 15px;
transition: all 800ms;
}
input:hover{
background-color: #499b41a1;
color: #ffd000ab;
}
`}</style>
	</>;
}