import React, { PropsWithChildren, useEffect, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { useDropdownSelectFilterState } from '../../hooks';
import { FilterProps } from '../../model';
import { Box, RadioGroup, RadioProps } from '@wix/design-system';
import { KeyedItem } from '@wix/bex-core';
import { usePatternsTheme } from '../../themes/PatternsThemeProvider';

export interface RadioGroupFilterProps<V> extends FilterProps<V[]> {
  /**
   * List of items to select from
   * @external
   */
  data: V[];
  /**
   * A function that returns Radio props for rendering each item
   * @external
   */
  renderItem?: (
    item: V,
    index: number,
  ) => Partial<PropsWithChildren<RadioProps>>;
}

function _RadioGroupFilter<V>(props: RadioGroupFilterProps<V>) {
  const { filter, data = [], renderItem } = props;

  const { dropdownSelect, init } = useDropdownSelectFilterState<V>({
    filter,
  });

  const {
    radioGroup: { spacing },
  } = usePatternsTheme();

  const {
    select: { selectedValues },
    container: { translate: t },
  } = dropdownSelect;

  const defaultValue = { id: 'all', name: t('cairo.filtersPanel.default.All') };

  useEffect(() => {
    return init();
  }, []);

  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"
      dataHook={`radio-group-filter-${filter.name}`}
    >
      <RadioGroup
        dataHook="radio-group-filter-group"
        value={selectedValues[0]?.key || defaultValue.id}
        spacing={spacing}
        onChange={(v) => {
          if (v?.toString() === defaultValue.id) {
            dropdownSelect.clear();
          } else {
            const newItem = keyedItems.find(
              (item) => item.key === v?.toString(),
            );
            newItem && dropdownSelect.setSingle(newItem as KeyedItem<V>);
          }
        }}
      >
        <RadioGroup.Radio
          value={defaultValue.id}
          dataHook="radio-group-filter-option-all"
        >
          {defaultValue.name}
        </RadioGroup.Radio>
        {keyedItems.map((keyedItem, index) => {
          const radioProps = renderItem?.(keyedItem.item, index);
          const key = keyedItem.key;
          return (
            <RadioGroup.Radio
              {...radioProps}
              key={key}
              value={key}
              dataHook={`radio-group-filter-option-${key}`}
            >
              {radioProps?.children ?? filter.itemName(keyedItem.item)}
            </RadioGroup.Radio>
          );
        })}
      </RadioGroup>
    </Box>
  );
}

export const RadioGroupFilter = observer(_RadioGroupFilter);

RadioGroupFilter.displayName = 'RadioGroupFilter';
