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

import { FC, Fragment, useEffect, useState } from 'react';
import { jsx } from '@emotion/react';
import { spaceRowContainer } from '../../../styles';
import { IDailyViewProps } from '../../../types';
import { DayToDropHorizontal } from './DayToDropHorizontal';
import { HorizontalCurrentTimeLine } from './HorizontalCurrentTimeLine';
import { useMiddlewareContext } from '../../../hooks/useMiddlewareContext';

export const DailyViewHorizontal: FC<IDailyViewProps> = ({
  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;

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

        if (space.children.length === 0) {
          return (
            <div key={space.id} css={spaceRowContainer()}>
              {
                <DayToDropHorizontal
                  id={String(space.id)}
                  EventComponent={EventComponent}
                  onAddNewSlotClick={onAddNewSlotClick}
                  hiddenEvents={hiddenEvents}
                />
              }
            </div>
          );
        } else {
          return (
            <div key={space.id} css={spaceRowContainer()}>
              {space.children.map((item) => {
                return (
                  <DayToDropHorizontal
                    key={item.id}
                    id={String(item.id)}
                    EventComponent={EventComponent}
                    onAddNewSlotClick={onAddNewSlotClick}
                    hiddenEvents={hiddenEvents}
                  />
                );
              })}
            </div>
          );
        }
      })}
      <HorizontalCurrentTimeLine />
    </Fragment>
  );
};
