import React, { useEffect } from "react";
import { Page } from "@/pages/base";
import { Container, Stepper, Typography } from "@material-ui/core";
import { Redirect } from "react-router-dom";
import { route } from "@/routing";
import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
import { AppState } from "@/state/reducer";
import { Student } from "@/data";
import { Step } from "@/components";
import { ProposalStep } from "@/pages/steps/proposal";
import { PlanStep } from "@/pages/steps/plan";
import { InsuranceState } from "@/state/reducer/insurance";
import { InsuranceStep } from "@/pages/steps/insurance";
import { StudentStep } from "@/pages/steps/student";
import api from "@/api";
import { AppDispatch, InternshipPlanActions, InternshipProposalActions, useDispatch } from "@/state/actions";
import { internshipRegistrationDtoTransformer } from "@/api/dto/internship-registration";
import { UploadType } from "@/api/upload";
import { ReportStep } from "@/pages/steps/report";

export const updateInternshipInfo = async (dispatch: AppDispatch) => {
    const internship = await api.internship.get();

    dispatch({
        type: InternshipProposalActions.Receive,
        state: internship.internshipRegistration.state,
        comment: internship.internshipRegistration.changeStateComment,
        internship: internshipRegistrationDtoTransformer.transform(internship.internshipRegistration),
    })

    const plan = internship.documentation.find(doc => doc.type === UploadType.Ipp);

    if (plan) {
        dispatch({
            type: InternshipPlanActions.Receive,
            document: plan,
            state: plan.state,
        })
    } else {
        dispatch({
            type: InternshipPlanActions.Reset,
        })
    }
}

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

    const student = useSelector<AppState, Student | null>(state => state.student);

    const insurance = useSelector<AppState, InsuranceState>(root => root.insurance);
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(updateInternshipInfo);
    }, [])

    if (!student) {
        return <Redirect to={ route("user_login") }/>;
    }

    function *getSteps() {
        yield <StudentStep key="student"/>;
        yield <ProposalStep key="proposal"/>;
        yield <PlanStep key="plan"/>;

        if (insurance.required)
            yield <InsuranceStep key="insurance"/>;

        yield <ReportStep key="report"/>;
        yield <Step label={ t('steps.grade.header') } key="grade"/>
    }

    return <Page>
        <Page.Header>
            <Page.Title>{ t("pages.my-internship.header") }</Page.Title>
        </Page.Header>
        <Container>
            <Stepper orientation="vertical" nonLinear>
                { Array.from(getSteps()) }
            </Stepper>
        </Container>
    </Page>
}
