/** @jsxRuntime classic */
/** @jsx jsx */

import { FC, Fragment } from 'react';
import { jsx } from '@emotion/react';
import { spaceColumnContainer, spaceRowContainer } from '../../styles';
import { ECalendarView, IWeeklyViewProps } from '../../types';
import { WeekToDrop } from './WeekToDrop';
import { useMiddlewareContext } from '../../hooks/useMiddlewareContext';

export const WeeklyView: FC<IWeeklyViewProps> = ({
  spaces,
  EventComponent,
}) => {
  const { options } = useMiddlewareContext();
  const { view = ECalendarView.VERTICAL } = options || {};
  const horizontal = view === ECalendarView.HORIZONTAL;

  return (
    <Fragment>
      {spaces.map((space) => {
        const columnsCount = spaces.reduce(
          (acc, { children }) => acc + (children.length || 1),
          0
        );

        if (space.children.length === 0) {
          return (
            <div
              key={space.id}
              css={
                horizontal
                  ? spaceRowContainer(spaces.length)
                  : spaceColumnContainer(columnsCount, 1)
              }
            >
              <WeekToDrop
                id={String(space.id)}
                EventComponent={EventComponent}
              />
            </div>
          );
        } else {
          return (
            <div
              key={space.id}
              css={
                horizontal
                  ? spaceRowContainer(spaces.length)
                  : spaceColumnContainer(
                      columnsCount,
                      space.children.length || 1
                    )
              }
            >
              {space.children.map((item) => {
                return (
                  <WeekToDrop
                    key={item.id}
                    id={String(item.id)}
                    EventComponent={EventComponent}
                  />
                );
              })}
            </div>
          );
        }
      })}
    </Fragment>
  );
};
