import { Button, FormHelperText, Grid, Typography } from "@material-ui/core";
import { Description as DescriptionIcon } from "@material-ui/icons";
import { DropzoneArea } from "material-ui-dropzone";
import { Actions } from "@/components";
import { Link as RouterLink, useHistory } from "react-router-dom";
import { route } from "@/routing";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { InternshipPlanActions, useDispatch } from "@/state/actions";
import { UploadType } from "@/api/upload";
import api from "@/api";
import { useSelector } from "react-redux";
import { AppState } from "@/state/reducer";
import { InternshipDocument } from "@/api/dto/internship-registration";

export const PlanForm = () => {
    const { t } = useTranslation();

    const [file, setFile] = useState<File>();

    const dispatch = useDispatch();
    const history = useHistory();

    const document = useSelector<AppState>(state => state.plan.document);

    const handleSubmit = async () => {
        if (!file) {
            return;
        }

        let destination: InternshipDocument = document as any;

        if (!destination) {
            destination = await api.upload.create(UploadType.Ipp);
            dispatch({ type: InternshipPlanActions.Send, document: destination });
        }

        await api.upload.upload(destination, file);

        history.push("/");
    }

    return <Grid container>
        <Grid item xs={12}>
            <Typography variant="body1" component="p">{ t('forms.plan.instructions') }</Typography>
        </Grid>
        <Grid item xs={12}>
            <Button href="https://eti.pg.edu.pl/documents/611675/100028367/indywidualny%20program%20praktyk" startIcon={ <DescriptionIcon /> }>
                { t('steps.plan.template') }
            </Button>
        </Grid>
        <Grid item xs={12}>
            <DropzoneArea acceptedFiles={["image/*", "application/pdf"]} filesLimit={ 1 } dropzoneText={ t("dropzone") } onChange={ files => setFile(files[0]) }/>
            <FormHelperText>{ t('forms.plan.dropzone-help') }</FormHelperText>
        </Grid>
        <Grid item xs={12}>
            <Actions>
                <Button variant="contained" color="primary" onClick={ handleSubmit }>
                    { t('confirm') }
                </Button>

                <Button component={ RouterLink } to={ route("home") }>
                    { t('go-back') }
                </Button>
            </Actions>
        </Grid>
    </Grid>
}
