import React, { PropsWithChildren, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { DropdownSelectState } from '../../state';
import { Box, BoxProps, Checkbox, CheckboxProps } from '@wix/design-system';

export interface MultiInlineCheckboxProps<V>
  extends Partial<Omit<BoxProps, 'filter'>> {
  /** List of items to select from */
  data: V[];
  renderItem?: (
    item: V,
    index: number,
  ) => Partial<PropsWithChildren<CheckboxProps>>;
  state: DropdownSelectState<V>;
}

function _MultiInlineCheckbox<V>(props: MultiInlineCheckboxProps<V>) {
  const { renderItem, data, state, ...rest } = props;

  const { filter, select } = state;

  const keyedItems = useMemo(
    () =>
      data.map((item, index) => {
        const key = filter.itemKey(item);
        return {
          id: key,
          key,
          item,
          index,
          indexWithinPage: index,
          pageIndex: 0,
        };
      }),
    [data],
  );

  return (
    <Box direction="vertical" gap="SP2" {...rest}>
      {keyedItems.map((keyedItem, index) => {
        const checkboxProps = renderItem?.(keyedItem.item, index);

        return (
          <Checkbox
            {...checkboxProps}
            dataHook={`multi-inline-checkbox-${keyedItem.key}`}
            key={keyedItem.key}
            onChange={(e) => {
              const checked = e.target.checked;
              checked ? state.set(keyedItem) : state.delete(keyedItem);
              checkboxProps?.onChange?.(e);
            }}
            checked={checkboxProps?.checked || select.isChecked(keyedItem.key)}
          >
            {checkboxProps?.children ?? filter.itemName(keyedItem.item)}
          </Checkbox>
        );
      })}
    </Box>
  );
}

export const MultiInlineCheckbox = observer(_MultiInlineCheckbox);
