import React, { ComponentProps, useMemo } from 'react';
import { Chip, useTheme } from 'react-native-paper';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import { StyleSheet } from 'react-native';
import { getContrastColor } from '../utilities';
import { Tag } from '../database';

const tagChipStyles = StyleSheet.create({
  chip: {
    borderWidth: 1,
  },
});

const TagChip = ({
  tag,
  active = true,
  elevated = false,
  onPress,
  ...props
}: {
  tag: Tag;
  active?: boolean;
  elevated?: boolean;
  onPress?: () => void;
} & Omit<ComponentProps<typeof Chip>, 'children'>) => {
  const theme = useTheme();

  const chipTheme = useMemo(() => {
    return {
      ...theme,
      colors: {
        ...theme.colors,
        secondaryContainer: tag.color,
        outline: tag.color,
      },
    };
  }, [tag.color, theme]);

  const contrastColor = getContrastColor(tag.color);

  return (
    <Chip
      {...props}
      icon={() => {
        return (
          <FontAwesome5 name="tag" color={active ? contrastColor : tag.color} />
        );
      }}
      compact
      elevated={elevated}
      theme={chipTheme}
      mode={active ? 'flat' : 'outlined'}
      style={[tagChipStyles.chip, props.style]}
      textStyle={{
        color: active ? contrastColor : theme.colors.onBackground,
      }}
      onPress={onPress}>
      {'#' + tag.name}
    </Chip>
  );
};

export default TagChip;
