import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
import { setMenuActivePage } from '../../../redux/slices/store';
import { Navigate, Route, Routes, useParams } from 'react-router-dom';
import {
    fetchContestById,
    fetchMyAttemptsInContest,
} from '../../../redux/slices/contests';
import ContestMissions from './Missions';
import Submissions from './Submissions';

export interface Article {
    id: number;
    name: string;
    tags: string[];
}

const Contest = () => {
    const { contestId } = useParams<{ contestId: string }>();
    const contestIdNumber =
        contestId && /^\d+$/.test(contestId) ? parseInt(contestId, 10) : null;
    if (!contestIdNumber) {
        return <Navigate to="/home/contests" replace />;
    }
    const dispatch = useAppDispatch();
    const contest = useAppSelector(
        (state) => state.contests.fetchContestById.contest,
    );

    useEffect(() => {
        dispatch(setMenuActivePage('contest'));
    }, []);

    useEffect(() => {
        dispatch(fetchContestById(contestIdNumber));
        dispatch(fetchMyAttemptsInContest(contestIdNumber));
    }, [contestIdNumber]);

    return (
        <div className="w-full h-full">
            <Routes>
                <Route
                    path="submissions"
                    element={<Submissions contest={contest} />}
                />
                <Route
                    path="*"
                    element={<ContestMissions contest={contest} />}
                />
            </Routes>
        </div>
    );
};

export default Contest;
