import React, { useCallback, useEffect, useState } from "react";
import { Page } from "@/pages/base";
import { useTranslation } from "react-i18next";
import { Box, Button, CircularProgress, Container, TextField, Typography } from "@material-ui/core";

import api from "@/api";
import { useVerticalSpacing } from "@/styles";
import { Edition } from "@/data/edition";
import { useAsyncState } from "@/hooks";
import { Label, Section } from "@/components/section";
import { Alert } from "@material-ui/lab";
import { Subset } from "@/helpers";
import { useDispatch } from "@/state/actions";
import { loginToEdition } from "@/pages/edition/pick";
import { useHistory, useRouteMatch } from "react-router-dom";
import { useDebouncedEffect } from "@/hooks/useDebouncedEffect";

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

    const classes = useVerticalSpacing(3);
    const dispatch = useDispatch();
    const history = useHistory();
    const match = useRouteMatch<any>();

    const [key, setKey] = useState<string>(match.params['edition'] || "");
    const [{ value: edition, isLoading }, setEdition] = useAsyncState<Subset<Edition> | null>(undefined);

    useDebouncedEffect(() => {
        setEdition(api.edition.get(key));
    }, [ key ])

    const handleRegister = async () => {
        try {
            await api.edition.join(key);
            await dispatch(loginToEdition(key));
            history.push("/");
        } catch (error) {
            console.log(error);
        }
    }

    const handleKeyChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
        setKey(ev.currentTarget.value);
    }

    const Edition = () => edition
        ? <Section>
            <Label>{ t("forms.edition-register.edition" ) }</Label>
            <Typography className="proposal__primary">{ edition.course?.name }</Typography>
            <Typography className="proposal__secondary">
                { t('internship.date-range', { start: edition.startDate, end: edition.endDate }) }
            </Typography>
        </Section>
        : <Alert severity="warning">{ t("forms.edition-register.edition-not-found") }</Alert>


    return <Page>
        <Page.Header maxWidth="md">
            <Page.Title>{ t("pages.edition.header") }</Page.Title>
        </Page.Header>

        <Container maxWidth="md" className={ classes.root }>
            <TextField label={ t("forms.edition-register.fields.key") } fullWidth
                       onChange={ handleKeyChange }
                       value={ key } />

            <Box>
                { isLoading ? <CircularProgress /> : <Edition /> }
            </Box>

            <Button onClick={ handleRegister } variant="contained" color="primary" disabled={ !edition }>{ t("forms.edition-register.register") }</Button>
        </Container>
    </Page>
}
