import { format } from 'date-fns'
import _ from 'lodash'
import { prettyCourseName, WEEK_DAYS, withClasses } from '../../utils.jsx'

export const Schedule = ({ events, selection, setSelection, hideOtherCourses }) => {
    const selectionSet = new Set(selection)

    const visibleEvents = !hideOtherCourses ? events : events.filter(e => selectionSet.has(e.id))

    const eventsByWeekday = _.mapValues(
        _.groupBy(visibleEvents, e => e.start.getDay()),
        dailyEvents => _.groupBy(dailyEvents, e => e.start.getHours())
    )

    return (
        <div class="schedule-view">
            {Object.entries(eventsByWeekday).map(([index, dailyEvents]) => (
                <>
                    <div class="header giorno">
                        <div class="inner">{WEEK_DAYS[index]}</div>
                    </div>
                    {Object.values(dailyEvents).map(events => (
                        <>
                            <div class="header orario">{format(events[0].start, 'H:mm')}</div>
                            {events.map(event => (
                                <div
                                    class={withClasses([
                                        'event',
                                        selectionSet.has(event.id) && 'selected',
                                    ])}
                                    onClick={() => {
                                        if (!selectionSet.has(event.id))
                                            setSelection([...selection, event.id])
                                        else
                                            setSelection(
                                                selection.filter(selId => selId !== event.id)
                                            )
                                    }}
                                >
                                    <div class="title">{prettyCourseName(event.name)}</div>
                                    <div class="orario">
                                        {format(event.start, 'H:mm')} &ndash;{' '}
                                        {format(event.end, 'H:mm')}
                                    </div>
                                    <div class="aula">{event.aule.join(', ')}</div>
                                </div>
                            ))}
                        </>
                    ))}
                </>
            ))}
        </div>
    )
}
