import SubmissionItem from './SubmissionItem';
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
import { FC, useEffect } from 'react';
import { fetchMySubmissions, setContestStatus } from '../../../redux/slices/contests';

export interface Mission {
    id: number;
    authorId: number;
    name: string;
    difficulty: 'Easy' | 'Medium' | 'Hard';
    tags: string[];
    timeLimit: number;
    memoryLimit: number;
    createdAt: string;
    updatedAt: string;
}

interface SubmissionsProps {
    contestId: number;
}

const Submissions: FC<SubmissionsProps> = ({ contestId }) => {
    const dispatch = useAppDispatch();
    
    const {submissions, status} = useAppSelector(
        (state) => state.contests.fetchMySubmissions
    );

    useEffect(() => {
        dispatch(fetchMySubmissions(contestId));
    }, [contestId]);

    useEffect(() => {
        if (status == "successful"){
            dispatch(setContestStatus({key:"fetchMySubmissions", status: "idle"}));
        }
    }, [status])

    const checkStatus = (status: string) => {
        if (status == 'IncorrectAnswer') return 'wronganswer';
        if (status == 'TimeLimitError') return 'timelimit';
        return undefined;
    };

    return (
        <div className="h-full w-full box-border overflow-y-scroll  overflow-x-hidden thin-scrollbar pr-[10px]">
            {submissions &&
                submissions.map((v, i) => (
                    <SubmissionItem
                        key={i}
                        id={v.id??0}
                        language={v.solution.language}
                        time={v.solution.time}
                        verdict={
                            v.solution.testerMessage?.includes(
                                'Compilation failed',
                            )
                                ? 'Compilation failed'
                                : v.solution.testerMessage
                        }
                        type={i % 2 ? 'second' : 'first'}
                        status={
                            v.solution.testerMessage == 'All tests passed'
                                ? 'success'
                                : checkStatus(v.solution.testerErrorCode)
                        }
                    />
                ))}
        </div>
    );
};

export default Submissions;
