import React from "react";
import EnvTabsContainer from "./EnvTabsContainer";
import LoadingIndicator from "./LoadingIndicator";
import { DashboardLoadError, DashboardResponseContent, EnvTab, Environment } from "../types";
import { ENVIRONMENT_TABS } from "../const";
import { dashboardApi } from "../api";
import { AxiosError } from "axios";
import LoadingError from "./LoadingError";
import EnvironmentList from "./dashboard/EnvironmentList";

export default function Dashboard() {
    const defaultEnv = ENVIRONMENT_TABS[0];

    const [selectedEnv, setSelectedEnv] = React.useState(defaultEnv);
    const [loadingEnv, setLoadingEnv] = React.useState(false);
    const [loadingErr, setLoadingErr] = React.useState<DashboardLoadError | null>(null);
    const [activeEnvironments, setActiveEnvironments] = React.useState<Environment[] | null>(null);

    React.useEffect(() => {
        loadEnv(defaultEnv);
    }, []);

    const onSelectEnvTab = (envTab: EnvTab): void => {
        loadEnv(envTab);
    };

    const loadEnv = (envTab: EnvTab) => {
        console.log("loading env:", envTab);
        setLoadingErr(null);
        setLoadingEnv(true);

        dashboardApi
            .getFake(envTab.dashboardEndpoint)
            .then((response) => {
                return response.data.content;
            })
            .then((data: DashboardResponseContent) => {
                setActiveEnvironments(data.environments);
            })
            .catch((error: AxiosError) => {
                console.error(error);
                setLoadingErr({
                    message: error.message,
                    url: envTab.dashboardEndpoint,
                });
            })
            .finally(() => {
                setLoadingEnv(false);
            });
    };

    return (
        <>
            <LoadingIndicator active={loadingEnv} />
            <EnvTabsContainer selectedEnv={selectedEnv} onSelect={onSelectEnvTab} />
            {loadingErr && <LoadingError error={loadingErr} />}
            {activeEnvironments && <EnvironmentList environments={activeEnvironments} />}
        </>
    );
}
