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

import { FC, useMemo, useState, useEffect } from 'react';
import { jsx, useTheme } from '@emotion/react';
import { Droppable } from '../../Droppable';
import { IDayToDropProps, ISlot } from '../../../types';
import { useMiddlewareContext } from '../../../hooks/useMiddlewareContext';
import {
  collisionGroupContainerHorizontal,
  horizontalDayToDropContainer,
  moreItemsButtonHorizontal,
  moreModal,
} from '../../styles';
import { calculateModalPosition } from '../../../utils';
import { BnClose } from '../../../../icons/BnClose';
import { DraggableHorizontal } from './DraggableHorizontal';
import { AddNewSlotButtons } from '../AddNewSlotButtons';

export const DayToDropHorizontal: FC<IDayToDropProps> = ({
  id,
  EventComponent,
  onAddNewSlotClick,
  hiddenEvents,
}) => {
  const {
    getEventsGroups,
    isResizing,
    day: daysCount,
    partialRanges,
    options,
    getPartialEvents,
    eventsToSpaces,
  } = useMiddlewareContext();
  const { partialRendering } = options;
  const colors = useTheme();

  const [hover, setHover] = useState(false);

  const eventsGroups = useMemo(() => {
    const events = hiddenEvents
      ? []
      : ((Array.isArray(eventsToSpaces?.[id])
          ? partialRendering
            ? getPartialEvents(
                eventsToSpaces[id],
                partialRanges.horizontal.from,
                partialRanges.horizontal.to
              )
            : eventsToSpaces[id]
          : []) as ISlot[]);

    return getEventsGroups(events);
  }, [
    eventsToSpaces,
    id,
    partialRanges.horizontal.from,
    partialRanges.horizontal.to,
    partialRendering,
    hiddenEvents,
  ]);

  const eventsFullGroups = useMemo(() => {
    const events = (Array.isArray(eventsToSpaces[id])
      ? eventsToSpaces[id]
      : []) as ISlot[];

    return getEventsGroups(events, true);
  }, [eventsToSpaces, id]);

  const [modals, setModals] = useState<boolean[]>([]);

  useEffect(() => {
    setModals(Array(eventsGroups.length).fill(false));
  }, [eventsGroups]);

  const handleToggleModal = (index: number) => {
    let newModals = modals.slice();
    newModals[index] = !newModals[index];
    setModals(newModals);
  };

  const MAX_COUNT = 4;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      css={horizontalDayToDropContainer(daysCount, colors)}
    >
      <Droppable id={id}>
        {eventsGroups.map((group, index) => {
          const withModal = (group.groups?.length || 0) > MAX_COUNT;

          if (Array.isArray(group.groups)) {
            const moreItemsCount = withModal
              ? group.groups
                  .slice(3)
                  .reduce((acc, events) => acc + events.length, 0)
              : 0;

            const element = document.querySelector(`#group-${index}`);
            const box = element as HTMLElement;
            const container = box?.parentElement;
            const boxW = container?.parentElement?.parentElement;
            const containerW = boxW?.parentElement;

            return (
              <div
                id={`group-${index}`}
                key={index}
                css={collisionGroupContainerHorizontal(group.top, group.height)}
              >
                {group.groups?.map((groupItems, index) => {
                  return (
                    <div key={index}>
                      {groupItems.map((event) => (
                        <DraggableHorizontal
                          parentId={id}
                          state={event}
                          key={event.id}
                          id={event.id}
                          groupTop={group.top}
                          groupCount={
                            withModal ? MAX_COUNT : group.groups?.length
                          }
                          groupIndex={index}
                        >
                          <EventComponent event={event} />
                        </DraggableHorizontal>
                      ))}
                    </div>
                  );
                })}
                {withModal && (
                  <button
                    css={moreItemsButtonHorizontal(colors)}
                    onClick={() => handleToggleModal(index)}
                  >
                    <div>+{`${moreItemsCount} more`}</div>
                  </button>
                )}
                {withModal && modals[index] && (
                  <div
                    css={moreModal(
                      colors,
                      calculateModalPosition(boxW, containerW, box, container)
                    )}
                  >
                    <div className="more-modal-header">
                      <div onClick={() => handleToggleModal(index)}>
                        <BnClose />
                      </div>
                    </div>
                    <div className="events-list">
                      {group.items.map((event) => (
                        <div key={event.id} css={{ margin: 2, height: '50px' }}>
                          <EventComponent event={event} />
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            );
          } else if (group.item) {
            return (
              <DraggableHorizontal
                parentId={id}
                state={group.item}
                key={group.item.id}
                id={group.item.id}
              >
                <EventComponent event={group.item} />
              </DraggableHorizontal>
            );
          } else {
            return null;
          }
        })}
        {hover && !isResizing && (
          <AddNewSlotButtons
            parentId={id}
            events={JSON.stringify(eventsFullGroups)}
            onClick={onAddNewSlotClick}
            horizontal
          />
        )}
      </Droppable>
    </div>
  );
};
