import React, { useEffect, useMemo } from 'react';
import { ToolbarBaseProps, ToolbarCollection } from '../ToolbarCollection';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { KanbanBaseProps } from './KanbanProps';
import { StageComponent } from './Stage';
import { Box, Divider } from '@wix/design-system';
import { CollectionCard } from '../CollectionCard';
import { KanbanCardDragAndDrop } from '../KanbanDragAndDropDndKit/KanbanCardDragAndDrop';
import { StagesSkeleton } from './StagesSkeleton';
import { useKanbanCollectionSyncProps } from './useKanbanCollectionSyncProps';

export interface KanbanProps<C, S, F extends FiltersMap>
  extends ToolbarBaseProps,
    KanbanBaseProps<C, S, F> {}

function _Kanban<C, S, F extends FiltersMap>(props: KanbanProps<C, S, F>) {
  const { state, dataHook } = props;

  const { toolbar, events } = state;

  const scrollToStage = ({ stageKey }: { stageKey: string }) => {
    const stageElement = document.querySelector(
      `[data-hook="kanban-stage-container-${stageKey}"]`,
    );
    if (stageElement) {
      stageElement.scrollIntoView?.({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'center',
      });
    }
  };

  useKanbanCollectionSyncProps(props);

  useEffect(() => {
    events.on('scrollToStage', scrollToStage);

    return () => {
      events.off('scrollToStage', scrollToStage);
    };
  }, [events]);

  const stages = useMemo(() => {
    return props.state.stages;
  }, [props.state.stages]);

  // Calculate active stage key from activeId
  const activeId = state.dragAndDropState.activeId;
  const activeStageKey = activeId
    ? activeId.substring(0, activeId.indexOf('-##-')) || null
    : null;

  // Wrap with global drag and drop context - always enabled for Kanban
  const { KanbanDragAndDropContext, DragOverlay } = KanbanCardDragAndDrop;

  // Find the index of the first DONE stage
  const firstDoneIndex = stages.findIndex(
    (stage: S) => props.state?.stageType?.(stage) === 'DONE',
  );

  const stagesContent = (
    <KanbanDragAndDropContext state={state} stageId="all">
      <Box
        direction="horizontal"
        gap="12px"
        scrollbarWidth="thin"
        scrollbarColor="#CFD1DC transparent"
        overflowX="scroll"
      >
        {stages.map((stage: S, index: number) => (
          <>
            {index === firstDoneIndex && firstDoneIndex !== -1 && (
              <Divider
                direction="vertical"
                dataHook="kanban-stages-done-divider"
              />
            )}
            <StageComponent
              dataHook={`kanban-stage-${props.state.stageKey(stage)}`}
              key={props.state.stageKey(stage)}
              activeStageKey={activeStageKey}
              stageKey={props.state.stageKey(stage)}
              {...props}
            />
          </>
        ))}
      </Box>
      <DragOverlay
        state={state}
        renderItem={props.renderItem}
        actionCell={props.actionCell}
        dataExtension={props.dataExtension}
        tags={props.tags}
      />
    </KanbanDragAndDropContext>
  );

  return (
    <CollectionCard errorState={false} state={toolbar} dataHook={dataHook}>
      <ToolbarCollection search={true} sticky state={toolbar} filters={props.filters}>
        {/* hack for showing manage tags action in more actions menu */}
        <Box
          dataHook="kanban-tags-container"
          height="0px"
          width="0px"
          display="hidden"
        >
          {props.tags && props.tags}
        </Box>
        <Box
          dataHook="kanban-test"
          marginTop="16px"
          marginBottom="12px"
          marginLeft="18px"
          marginRight="18px"
          overflow="auto"
          direction="vertical"
        >
          <Box dataHook="kanban-stages" direction="vertical">
            {props.state.isLoadingStages ? <StagesSkeleton /> : stagesContent}
          </Box>
        </Box>
      </ToolbarCollection>
    </CollectionCard>
  );
}

export const Kanban = observer(_Kanban);
