import React, { ReactElement, useEffect, useState } from 'react';
import { Fade, FadeProps } from '../Fade';
import { CollectionState, FiltersMap, KeyedItem } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import {
  CollectionListItemProps,
  RowActionsColumnSlot,
  RowColumnSlotProps,
} from '../CollectionListItem';
import { CollectionItemActions } from '../CollectionItemActions';
import { Box } from '@wix/design-system';
import { ItemActionsState } from '../../state';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';

export interface CollectionListRowProps<T, F extends FiltersMap = FiltersMap>
  extends Partial<FadeProps> {
  fade?: boolean;
  dataHook?: string;
  collection: CollectionState<T, F>;
  keyedItem: KeyedItem<T>;
  element: ReactElement<CollectionListItemProps>;
}

export const CollectionListRow = observer(function CollectionListRow<
  T,
  F extends FiltersMap = FiltersMap,
>({
  fade,
  element,
  collection,
  keyedItem,
  dataHook,
  ...rest
}: CollectionListRowProps<T, F>) {
  const toolbarState = useToolbarCollectionContext();

  const [state] = useState(
    () =>
      new ItemActionsState({
        collection,
        keyedItem,
        fade: 'idle',
        reportBi: toolbarState.reportBi,
      }),
  );

  const { type: CollectionListItemComponent, props: collectionListItemProps } =
    element;

  useEffect(() => {
    if (state.keyedItem !== keyedItem) {
      state.keyedItem = keyedItem;
    }
  }, [keyedItem]);

  const transformColumn = (columnElement: ReactElement<RowColumnSlotProps>) => {
    const { props } = columnElement;
    const overrides = RowActionsColumnSlot.isElementOf(columnElement)
      ? {
          width: 100,
          align: 'right' as const,
          value: (
            <CollectionItemActions state={state} collection={collection} />
          ),
        }
      : {
          value: (
            <Box dataHook="collection-list-column" color="D20">
              {props.children}
            </Box>
          ),
        };

    return {
      ...props,
      ...overrides,
    };
  };

  let child = (
    <CollectionListItemComponent
      showDivider
      {...collectionListItemProps}
      transformColumn={transformColumn}
    />
  );

  if (fade) {
    child = (
      <Fade
        timeout={650}
        {...rest}
        onExiting={(node) => {
          state.onFadeStart();
          void rest.onExiting?.(node);
        }}
        onExited={(node) => {
          state.onFadeDone();
          void rest.onExited?.(node);
        }}
      >
        <div data-hook={dataHook}>{child}</div>
      </Fade>
    );
  }

  return child;
});
