import type {Route} from "../../.react-router/types/app/pages/+types/Dashboard";
import {useDisclosure, useWindowScroll} from "@mantine/hooks";
import {Affix, AppShell, Button, Space, Stack, Transition} from "@mantine/core";
import {PageHeader} from "~/components/PageHeader.tsx";
import {PageNavbar} from "~/components/PageNavbar.tsx";
import {useEffect, useState} from "react";
import {Outlet, useLocation, useNavigate} from "react-router";
import {getEnumKeyByValue} from "~/utils/utils.ts";
import {apiPing} from "~/utils/compare_api.ts";
import ArrowUpIcon from "mdi-react/ArrowUpIcon";
import HomeIcon from "mdi-react/HomeIcon";
import GlobalAffix from "~/components/GlobalAffix.tsx";
import {DashboardPageType} from "~/utils/enums.ts";

export function meta({}: Route.MetaArgs) {
    return [
        { title: "Dashboard" },
        { name: "description", content: "Dashboard Main" },
    ];
}

export default function Component() {
    const navigate = useNavigate();
    const [currentStat, setCurrentStat] = useState(DashboardPageType.Home)
    const [opened, { toggle }] = useDisclosure()
    const location = useLocation();

    const changePage = (pageType: DashboardPageType, navigateTo?: string) => {
        // if (currentStat == pageType) return
        setCurrentStat(pageType)
        navigate(navigateTo || pageType)
    }

    const refreshMyInfo = () => {
        apiPing()
            .then((res => {
                if (!res.success) {
                    navigate(DashboardPageType.Home)
                }
            }))
            .catch(err => {
                console.log("apiGetMyInfo failed", err)
                navigate(DashboardPageType.Home)
            })
    }

    useEffect(() => {
        refreshMyInfo()
        let currPage = getEnumKeyByValue(DashboardPageType, location.pathname)
        if (currPage) {
            setCurrentStat(DashboardPageType[currPage])
        }
        else {
            const pathParts = location.pathname.split("/")
            const path = pathParts.slice(0, pathParts.length - 1).join("/")
            currPage = getEnumKeyByValue(DashboardPageType, path + "/")
            if (currPage) {
                setCurrentStat(DashboardPageType[currPage])
            }
        }
    }, []);

    return (
        <AppShell header={{ height: 60 }} navbar={{width: 300, breakpoint: `sm`, collapsed: {mobile: !opened}}} padding="md">
            <AppShell.Header p="md">
                <PageHeader opened={opened} toggle={toggle} appendTitle={""}/>
            </AppShell.Header>

            <AppShell.Navbar p="md">
                <PageNavbar currentStat={currentStat} changePageStat={changePage} />
            </AppShell.Navbar>

            <AppShell.Main>
                <Outlet context={{ refreshMyInfo, changePage }} />
                <Space h={50} />
                <GlobalAffix />
            </AppShell.Main>
        </AppShell>
    );
}
