import { useEffect } from 'react';
import { SecondaryButton } from '../../../components/button/SecondaryButton';
import { cn } from '../../../lib/cn';
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
import ContestsBlock from './ContestsBlock';
import { setMenuActivePage } from '../../../redux/slices/store';
import { fetchContests } from '../../../redux/slices/contests';

const Contests = () => {
    const dispatch = useAppDispatch();
    const now = new Date();

    // Берём данные из Redux
    const contests = useAppSelector((state) => state.contests.contests);
    const loading = useAppSelector((state) => state.contests.status);
    const error = useAppSelector((state) => state.contests.error);

    // При загрузке страницы — выставляем активную вкладку и подгружаем контесты
    useEffect(() => {
        dispatch(setMenuActivePage('contests'));
        dispatch(fetchContests({}));
    }, []);

    if (loading == 'loading') {
        return (
            <div className="text-liquid-white p-4">Загрузка контестов...</div>
        );
    }

    if (error) {
        return <div className="text-red-500 p-4">Ошибка: {error}</div>;
    }

    return (
        <div className="h-full w-[calc(100%+250px)] box-border p-[20px] pt-[20p]">
            <div className="h-full box-border">
                <div className="relative flex items-center mb-[20px]">
                    <div
                        className={cn(
                            'h-[50px] text-[40px] font-bold text-liquid-white flex items-center',
                        )}
                    >
                        Контесты
                    </div>
                    <SecondaryButton
                        onClick={() => {}}
                        text="Создать группу"
                        className="absolute right-0"
                    />
                </div>

                <div className="bg-liquid-lighter h-[50px] mb-[20px]" />

                <ContestsBlock
                    className="mb-[20px]"
                    title="Текущие"
                    contests={contests.filter((contest) => {
                        const endTime = new Date(contest.endsAt).getTime();
                        return endTime >= now.getTime();
                    })}
                />

                <ContestsBlock
                    className="mb-[20px]"
                    title="Прошедшие"
                    contests={contests.filter((contest) => {
                        const endTime = new Date(contest.endsAt).getTime();
                        return endTime < now.getTime();
                    })}
                />
            </div>
        </div>
    );
};

export default Contests;
