import React, { useEffect, useMemo } from "react";
import { Page } from "@/pages/base";
import { Button, Container, Stepper, Typography } from "@material-ui/core";
import { Link as RouterLink, 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 { getMissingStudentData, Student } from "@/data";
import { Deadlines, Edition, getEditionDeadlines } from "@/data/edition";
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 api from "@/api";

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

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

    const deadlines = useSelector<AppState, Deadlines>(state => getEditionDeadlines(state.edition as Edition)); // edition cannot be null at this point
    const insurance = useSelector<AppState, InsuranceState>(root => root.insurance);

    const missingStudentData = useMemo(() => student ? getMissingStudentData(student) : [], [student]);

    useEffect(() => void api.edition.available())

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

    function *getSteps() {
        yield <Step label={ t('steps.personal-data.header') } completed={ missingStudentData.length === 0 } until={ deadlines.personalData } key="personal-data">
            { missingStudentData.length > 0 && <>
                <p>{ t('steps.personal-data.info') }</p>

                <ul>
                    { missingStudentData.map(field => <li key={ field }>{ t(`student.${ field }`) }</li>) }
                </ul>

                <Button to={ route("internship_proposal") } variant="contained" color="primary" component={ RouterLink }>
                    { t('steps.personal-data.form') }
                </Button>
            </> }
        </Step>;

        yield <ProposalStep key="proposal"/>;
        yield <PlanStep key="plan"/>;

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

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

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