import React, {useCallback, useMemo, FC} from 'react';
import {StyleProp, View, ViewStyle} from 'react-native';
import {IconCheck, IconProps} from '@tabler/icons-react-native';
import {Button} from '@components/_HuGo/Button';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

type ItemId = string | number;

export type VerticalButtonGroupItem<T extends ItemId = ItemId> = {
  id: T;
  label: string;
};

interface Props<T extends ItemId = ItemId> {
  disabled?: boolean;
  onChange?: (id: T) => void;
  options: VerticalButtonGroupItem<T>[];
  selected: T;
  withLimitedOptions?: boolean;
  withTick?: boolean;
}

const DummyIcon: FC<IconProps> = () => <View style={styles.dummyIcon} />;

export function VerticalButtonGroup<T extends ItemId>({
  disabled = false,
  onChange,
  options,
  selected,
  withLimitedOptions = true,
  withTick = true,
}: Props<T>) {
  const {theme} = useTheme();
  const onPress = useCallback(
    (index: T) => () => onChange?.(index),
    [onChange],
  );

  const limitedOptions = useMemo(
    () => (withLimitedOptions ? options.slice(0, 3) : options),
    [options, withLimitedOptions],
  );

  const getButtonStyle = useCallback(
    (index: number, totalLength: number): StyleProp<ViewStyle> => {
      const isFirst = index === 0;
      const isLast = index === totalLength - 1;

      return [
        styles.withoutLimitedOptions,
        isFirst ? styles.withoutBottomRadius : styles.withoutTopRadius,
        !isLast && styles.withoutBottomRadius,
      ];
    },
    [],
  );

  return (
    <View style={styles.containerVertical}>
      {limitedOptions.map((item, index) => {
        const isSelected = item.id === selected;
        const IconLeft = withTick
          ? isSelected
            ? IconCheck
            : DummyIcon
          : undefined;
        const buttonStyle = getButtonStyle(index, limitedOptions.length);
        const disabledButtonStyle = disabled &&
          isSelected && {
            backgroundColor: theme.button.background.primary.disabled,
          };

        return (
          <View key={item.id} style={styles.buttonContainerVertical}>
            <Button
              onPress={onPress(item.id)}
              text={item.label}
              style={[buttonStyle, disabledButtonStyle]}
              disabled={disabled}
              variant={isSelected ? 'secondaryActive' : 'secondary'}
              IconLeft={IconLeft as FC<IconProps>}
              size="sm"
            />
          </View>
        );
      })}
    </View>
  );
}
