import {
  PickerTableListItem,
  PickerTableListItemProps,
} from '../PickerTableListItem';
import React, { useState } from 'react';
import { FiltersMap, KeyedItem } from '@wix/bex-core';
import { PickerStandaloneState } from '../../state';
import { TextWidthLoader } from '../TextWidthLoader';
import { Button } from '@wix/design-system';
import { observer } from 'mobx-react-lite';

export interface PickerStandaloneTableListItemProps<T, F extends FiltersMap>
  extends Omit<PickerTableListItemProps<T, F>, 'state'> {
  state: PickerStandaloneState<T, F>;
  keyedItem: KeyedItem<T>;
  primaryActionWidth?: string;
  defaultPrimaryButtonText?: string;
}

function _PickerStandaloneTableListItem<T, F extends FiltersMap>(
  props: PickerStandaloneTableListItemProps<T, F>,
) {
  const {
    state,
    keyedItem,
    onClick,
    primaryActionWidth,
    defaultPrimaryButtonText,
    ...rest
  } = props;
  const [hovered, setHovered] = useState(false);
  const { submitted, picker, isMobileView } = state;

  const {
    collection: { bulkSelect, translate: t },
  } = picker;

  const primaryButtonText =
    state.primaryButtonText ?? defaultPrimaryButtonText ?? t('cairo.continue');

  const { containerProps, listItemProps, primaryActionProps } = isMobileView
    ? {
        containerProps: undefined,
        listItemProps: {
          primaryActionWidth: 'min-content',
        },
        primaryActionProps: undefined,
      }
    : {
        containerProps: {
          onMouseEnter: () => setHovered(true),
          onMouseLeave: () => setHovered(false),
        },
        listItemProps: {
          primaryActionWidth,
        },
        primaryActionProps: {
          showButton: submitted ? bulkSelect.isChecked(keyedItem.key) : hovered,
        },
      };

  return (
    <div {...containerProps}>
      <PickerTableListItem
        state={picker}
        keyedItem={keyedItem}
        onClick={
          submitted
            ? undefined
            : (e: any) => {
                state.handlePrimaryButtonClick(keyedItem);
                onClick?.(e);
              }
        }
        {...listItemProps}
        primaryAction={
          primaryActionProps && primaryActionProps.showButton ? (
            <Button dataHook="primary-action-button" size="small">
              {submitted ? (
                <TextWidthLoader size="tiny" text={primaryButtonText} />
              ) : (
                primaryButtonText
              )}
            </Button>
          ) : undefined
        }
        {...rest}
      />
    </div>
  );
}

export const PickerStandaloneTableListItem = observer(
  _PickerStandaloneTableListItem,
);
