import {Box, useMediaQuery, useTheme} from "@mui/material";
import React, {useState} from "react";
import {CHAMPIONSHIP_STAGES} from "../../data/constants";
import Calendar from "./Calendar";
import MobileCalendarStageList from "./MobileCalendarStageList";
import DesktopCalendarStageList from "./DesktopCalendarStageList";
import dayjs from "dayjs";

export const CalendarContent = ({selectedClass}) => {
    const [viewDate, setViewDate] = useState(dayjs()); // Дата для отображения месяца
    const [openDrawer, setOpenDrawer] = useState(false);
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

    // Фильтрованные этапы для текущего месяца/класса
    //todo: change from api
    const filteredStages = CHAMPIONSHIP_STAGES.filter((stage) => {
        const stageDate = new Date(stage.date);
        const isSameMonth = stageDate.getMonth() === viewDate.month();
        const isSameYear = stageDate.getFullYear() === viewDate.year();
        const classMatch = selectedClass === 'Все' || stage.class === selectedClass;
        return isSameMonth && isSameYear && classMatch;
    });

    // Группируем этапы по дате
    const stagesByDate = filteredStages.reduce((acc, stage) => {
        const days = dayjs(stage.date);
        const dayKey = days.date() + "-" + days.month();
        acc[dayKey] = acc[dayKey] || [];
        acc[dayKey].push(stage);
        return acc;
    }, {});

    return (
        <>
            {/* Основной контент */}
            <Box sx={{
                display: 'grid',
                gridTemplateColumns: {xs: '1fr', md: '2fr 1fr'},
                gap: {xs: 2, md: 4},
                width: '100%',
                maxWidth: 1400,
                mx: 'auto',
                mt: 2,
            }}>
                {/* Календарь */}
                <Calendar viewDate={viewDate} setViewDate={setViewDate} stagesByDate={stagesByDate}/>

                {/* Список этапов (только на десктопе) */}
                {!isMobile && (<DesktopCalendarStageList filteredStages={filteredStages} viewDate={viewDate}/>)}
            </Box>

            <MobileCalendarStageList isMobile={isMobile} openDrawer={openDrawer} setOpenDrawer={setOpenDrawer}
                                     filteredStages={filteredStages} viewDate={viewDate}/>
        </>
    );
}