import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { KanbanState } from '../../state/KanbanState';
import { CardComponent } from '../Kanban/Card';
import { ItemActionsState } from '../../state';
import { KanbanBaseProps } from '../Kanban/KanbanProps';
import React from 'react';

export interface KanbanDragOverlayCardItemProps<T, S, F extends FiltersMap> {
  state: KanbanState<T, S, F>;
  renderItem?: KanbanBaseProps<T, S, F>['renderItem'];
  actionCell?: KanbanBaseProps<T, S, F>['actionCell'];
  dataExtension?: KanbanBaseProps<T, S, F>['dataExtension'];
  tags?: KanbanBaseProps<T, S, F>['tags'];
}

function _KanbanDragOverlayCardItem<T, S, F extends FiltersMap>(
  props: KanbanDragOverlayCardItemProps<T, S, F>,
) {
  const { state, renderItem, actionCell, dataExtension, tags } = props;

  const { activeId } = state.dragAndDropState;

  if (!activeId) {
    return null;
  }

  // Parse the activeId to get stageKey and itemKey
  const [stageKey, itemKey] = activeId.split('-##-');
  if (!stageKey || !itemKey) {
    return null;
  }

  const stageState = state.kanbanStageStates[stageKey];
  if (!stageState) {
    return null;
  }

  const keyedItem = stageState.itemsCollectionState.getKeyedItem(itemKey);
  if (!keyedItem) {
    return null;
  }

  const itemActionsState = new ItemActionsState({
    fade: 'static',
    keyedItem,
    collection: stageState.itemsCollectionState,
    reportBi: state.toolbar.reportBi,
  });

  const cardProps = {
    keyedItem,
    stageKey: stageState.stageKey,
    originalItem: keyedItem.item,
    itemIndex: 0, // Index not relevant for overlay
    itemActionsState,
    item: {
      ...renderItem?.({
        stage: stageState.stage,
        item: keyedItem.item,
      }),
      key: keyedItem.key,
    },
    actionCell,
    dataExtension,
    tags,
    isDragging: true,
    state,
  };

  return <CardComponent {...cardProps} />;
}

export const KanbanDragOverlayCardItem = observer(_KanbanDragOverlayCardItem);
