import { Navigate, Route, Routes } from 'react-router-dom';
import AccountMenu from './AccoutMenu';
import RightPanel from './RightPanel';
import Missions from './missions/Missions';
import Contests from './contests/Contests';
import ArticlesBlock from './articles/ArticlesBlock';
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
import { useEffect } from 'react';
import { setMenuActivePage } from '../../../redux/slices/store';
import { useQuery } from '../../../hooks/useQuery';
import {
    fetchProfile,
    fetchProfileArticles,
    fetchProfileContests,
    fetchProfileMissions,
} from '../../../redux/slices/profile';

const Account = () => {
    const dispatch = useAppDispatch();
    const myname = useAppSelector((state) => state.auth.username);

    const query = useQuery();
    const username = query.get('username') ?? myname ?? '';

    useEffect(() => {
        if (username == myname) {
            dispatch(setMenuActivePage('account'));
        } else {
            dispatch(setMenuActivePage(''));
        }
        dispatch(
            fetchProfileMissions({
                username: username,
                recentPageSize: 1,
                authoredPageSize: 100,
            }),
        );
        dispatch(fetchProfileArticles({ username: username, pageSize: 100 }));
        dispatch(
            fetchProfileContests({
                username: username,
                pastPageSize: 100,
                minePageSize: 100,
                upcomingPageSize: 100,
            }),
        );
        dispatch(fetchProfile(username));
    }, [username]);

    return (
        <div className="h-full w-[calc(100%+250px)] box-border grid grid-cols-[1fr,430px] relative  divide-x-[1px] divide-liquid-lighter">
            <div className=" h-full min-h-0  flex flex-col">
                <div className=" h-full grid grid-rows-[80px,1fr] ">
                    <div className="h-full w-full">
                        <AccountMenu />
                    </div>
                    <div className="h-full min-h-0 overflow-y-scroll medium-scrollbar flex flex-col gap-[20px] ">
                        <Routes>
                            <Route path="missions" element={<Missions />} />
                            <Route
                                path="articles"
                                element={<ArticlesBlock />}
                            />
                            <Route path="contests" element={<Contests />} />
                            <Route
                                path="*"
                                element={
                                    <Navigate to="/home/account/missions" />
                                }
                            />
                        </Routes>
                    </div>
                </div>
            </div>
            <div className=" h-full min-h-0">
                <RightPanel />
            </div>
        </div>
    );
};

export default Account;
