import React, { useCallback } from "react";
import { Page } from "@/pages/base";
import { Container, Divider, Typography, Button } from "@material-ui/core";
import { Async } from "@/components/async";
import { useTranslation } from "react-i18next";
import { useHistory, useRouteMatch } from "react-router-dom";
import { useAsync } from "@/hooks";
import { Edition } from "@/data/edition";
import api from "@/management/api";
import { Form, Formik } from "formik";
import { useSpacing } from "@/styles";
import { EditionForm, EditionFormValues, editionFormValuesTransformer } from "@/management/edition/form";
import { Actions } from "@/components";
import { Save } from "@material-ui/icons";
import { Cancel } from "mdi-material-ui";
import { EditionManagement } from "./manage";

const title = "edition.settings.title";

export function EditionSettings() {
    const { t } = useTranslation("management");
    const { params } = useRouteMatch();
    const history = useHistory();
    const spacing = useSpacing(2);

    const edition = useAsync<Edition>(useCallback(() => api.edition.details(params.edition), [params.edition]))

    const handleSubmit = async (values: EditionFormValues) => {
        const result: Edition = {
            ...edition.value,
            ...editionFormValuesTransformer.reverseTransform(values)
        };

        await api.edition.save(result);

        history.push("management:edition_manage", { edition: edition.id as string })
    };

    return <Page>
        <Page.Header maxWidth="md">
            <EditionManagement.Breadcrumbs>
                <Typography color="textPrimary">{ t(title) }</Typography>
            </EditionManagement.Breadcrumbs>
            <Page.Title>{ t(title) }</Page.Title>
        </Page.Header>
        <Container maxWidth="md">
            <Async async={ edition }>
                { edition =>
                    <Formik initialValues={ edition } onSubmit={ handleSubmit }>
                        <Form className={ spacing.vertical }>
                            <EditionForm />
                            <Divider />
                            <Actions>
                                <Button variant="contained" color="primary" type="submit" startIcon={ <Save /> }>{ t("save") }</Button>
                                <Button startIcon={ <Cancel /> }>{ t("cancel") }</Button>
                            </Actions>
                        </Form>
                    </Formik>
                }
            </Async>
        </Container>
    </Page>;
}
