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

import { FC, Fragment, memo, useEffect, useState } from 'react';
import { jsx } from '@emotion/react';
import { spaceColumnContainer } from '../../styles';
import { IDailyViewProps } from '../../types';
import { DayToDrop } from './DayToDrop';
import { useMiddlewareContext } from '../../hooks/useMiddlewareContext';
import { CurrentTimeLine } from './CurrentTimeLine';
import { spaceWidth } from '../styles';

export const DailyViewVertical: FC<IDailyViewProps> = memo(
  ({ spaces, EventComponent, onAddNewSlotClick }) => {
    const { partialRanges, options } = useMiddlewareContext();

    const [updates, setUpdates] = useState(false);

    useEffect(() => {
      setUpdates(true);
    }, [options.hourSize]);

    useEffect(() => {
      if (updates) setUpdates(false);
    }, [updates]);

    if (updates) return null;

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

    return (
      <Fragment>
        {spaces.map((space, index) => {
          const hiddenEvents = !options.partialRendering
            ? false
            : index < partialRanges.horizontal.from ||
              index >= partialRanges.horizontal.to;

          if (space.children.length === 0) {
            return (
              <div key={space.id} css={spaceColumnContainer(columnsCount, 1)}>
                <DayToDrop
                  id={String(space.id)}
                  EventComponent={EventComponent}
                  withoutChildren
                  hiddenEvents={hiddenEvents}
                  onAddNewSlotClick={onAddNewSlotClick}
                />
              </div>
            );
          } else {
            return (
              <div
                key={space.id}
                css={spaceColumnContainer(
                  columnsCount,
                  space.children.length || 1
                )}
              >
                {space.children.map((item) => {
                  return (
                    <DayToDrop
                      key={item.id}
                      id={String(item.id)}
                      EventComponent={EventComponent}
                      hiddenEvents={hiddenEvents}
                      onAddNewSlotClick={onAddNewSlotClick}
                    />
                  );
                })}
              </div>
            );
          }
        })}
        <CurrentTimeLine width={columnsCount * spaceWidth} />
      </Fragment>
    );
  }
);
