import { Page } from "@/pages/base";
import { Box, Button, CircularProgress, Container, Divider, Typography } from "@material-ui/core";
import { Link as RouterLink, useLocation } from "react-router-dom";
import React, { useMemo } from "react";
import { route } from "@/routing";
import { useAsync } from "@/hooks";
import api from "@/api";

export const FallbackPage = () => {
    const location = useLocation();

    const promise = useMemo(() => api.page.get(location.pathname), [ location.pathname ]);

    const { isLoading, value, error } = useAsync(promise);

    console.log({ isLoading, value, error, location });

    if (isLoading) {
        return <CircularProgress />
    }

    if (error) {
        return <Page title="Strona nie została znaleziona">
            <Container>
                <Typography variant="h1">404</Typography>
                <Typography variant="h2">Strona nie została znaleziona</Typography>

                <Box my={ 4 }>
                    <Divider variant="fullWidth"/>
                </Box>

                <Button to={ route("home") } color="primary" component={ RouterLink }>strona główna</Button>
            </Container>
        </Page>
    }

    if (value) {
        return <Page title={ value.title.pl }>
            <Page.Header maxWidth="md">
                <Page.Title>{ value.title.pl }</Page.Title>
            </Page.Header>
            <Container>
                <div dangerouslySetInnerHTML={{ __html: value.content.pl }} />
            </Container>
        </Page>
    }

    return <Page/>;
}

export default FallbackPage;
