import React, {ReactNode} from 'react';
import {LayoutChangeEvent, LayoutRectangle, Pressable} from 'react-native';
import {Icon, IconCheck, IconX} from '@tabler/icons-react-native';
import {Typography} from '@components/_core/Typography';
import {useTheme} from '@shared/theme';

import {ChipSize} from '../../interfaces';
import {getColors, getTextVariant, styles} from './styles';

interface Props {
  text: string;
  size?: ChipSize;
  active?: boolean;
  disabled?: boolean;
  showCloseIcon?: boolean;
  onPress?: () => void;
  onClose?: () => void;
  onLayout?: (width: LayoutRectangle) => void;
  IconComponent?: Icon;
  showActiveIcon?: boolean;
  RightIcon?: ReactNode;
}

export function Chip({
  text,
  active,
  disabled,
  onClose,
  onPress,
  showCloseIcon,
  size = 'md',
  onLayout,
  IconComponent,
  showActiveIcon = true,
  RightIcon,
}: Props) {
  const {theme, iconSizes} = useTheme();
  const {backgroundColor, borderColor, color} = getColors({
    theme,
    active,
    disabled,
  });
  const textProps = getTextVariant(size);

  const onComponentLayout = ({nativeEvent}: LayoutChangeEvent) =>
    onLayout?.(nativeEvent.layout);

  return (
    <Pressable
      onPress={onPress}
      style={[styles.container, styles[size], {backgroundColor, borderColor}]}
      onLayout={onComponentLayout}>
      {IconComponent ? (
        <IconComponent size={iconSizes.x4} color={color} />
      ) : (
        active &&
        showActiveIcon && <IconCheck size={iconSizes.x4} color={color} />
      )}
      <Typography
        weight="semiBold"
        color={color}
        numberOfLines={1}
        allowFontScaling={false}
        {...textProps}>
        {text}
      </Typography>
      {RightIcon}
      {showCloseIcon && (
        <Pressable onPress={onClose}>
          <IconX size={iconSizes.x4} color={color} />
        </Pressable>
      )}
    </Pressable>
  );
}
