import React, { useState, useRef, useEffect } from 'react';
import { Grid , Button} from '../../';
import '../main.scss';

export const FileUpload = (props : any) => {
    const { style, text, showFile } = props;
    const [File, setFile] = useState<any>([]);
    const [state, setState] = useState({ uploaded: false, loading: false });
    const upload = useRef<any>(null)
    const submit = async () => {
        setState({ ...state, loading: true });
        const file: any = new FormData();
        file.append('file', File);
        setState({ uploaded : true, loading: true})
        await props.uploadFile(file);
        setState({ uploaded : true, loading: false})
    }

    const uploadClick = (e: any) => {
        if (upload && upload.current)
            upload?.current?.click();
    }
    useEffect(()=>{
        if(File && state.uploaded)
            submit()
    }, [File])
    return (
            <Grid cols={showFile? "2" : "1"}  width="100%">
                {showFile && (upload && upload.current ?
                    <div>
                        Selected File:
                    <b>{File?.name || 'Error'}</b>
                    </div>
                    : "Upload CSV File of Schools to Add")}

                <Button shadow onClick={uploadClick} disabled={state.loading} style={{...style, ...{placeSelf: "end"}, style}}>
                <i className="fa fa-cloud-upload" aria-hidden="true" style={{color: "white"}}></i>
                {text}</Button>
                <input type="file" name="file" ref={upload} style={{ display: "none" }} onChange={(e: any) => {
                    setFile(e.target.files[0]);
                    setState({ ...state, uploaded: true })
                }} />
            </Grid>
    );
}

export default FileUpload;