import React, {FC, useEffect, useState} from "react";
import UserStatsMockService from "../../mock/UserStatsMockService";
import Header from "../../components/Header/Header";
import UserList from "../../components/UserList/UserList";
import ErrorContainer from "../../components/ErrorContainer/ErrorContainer";
import Footer from "../../components/Footer/Footer";
import {RouteComponentProps} from "react-router/index";
import UserStatsResponse from "../../models/UserStatsResponse";
import {withRouter} from "react-router";
import RequestError from "../../models/RequestError";
import './MainPage.scss';
import {ClipLoader} from "react-spinners";
import UserStatsService from "../../services/UserStatsService";

const MainPage: FC<IMainPageProps> = (props: IMainPageProps) => {
    const [seasonId, setSeasonId] = useState(props.match.params.id)
    const [error, setError] = useState<RequestError | undefined>(undefined)
    const [loading, setLoadingState] = useState(true)
    const [seasonStats, setSeasonStats] = useState<UserStatsResponse>(UserStatsMockService.getStatsWithoutPromise(seasonId))
    const [spinnerColor] = useState('#61dafb')

    useEffect(() => {
        UserStatsService.getStats(seasonId)
            .then(res => {
                setSeasonStats(res)
                setLoadingState(false)
            })
            .catch(err => {
              console.error(err.message)
              setLoadingState(false)
              setError(new RequestError(0, "Could not retrieve stats. Try again later."))
            })
    }, [seasonId, setLoadingState])

    const spinnerCss = `
      margin: 0;
      z-index: 2;
      position: absolute;
    `

    return (
        <div className="MainPage">
            <Header />
            {
                error && <ErrorContainer message={error.message} />
            }

            <ClipLoader color={spinnerColor} loading={loading} size={150} css={spinnerCss} />
            <div className={loading || error ? "blurred" : ""}>
                <UserList enabled={loading || !(!error)} onSeasonIdChange={setSeasonId} userStats={seasonStats} />
            </div>

            <Footer />
        </div>
    )
}

export interface IMainPageProps extends RouteComponentProps<{ id: string }> {

}

export default withRouter(MainPage)