import styled from '@emotion/native';
import { TouchableOpacity } from 'react-native';
import type { Theme } from '../../theme';
import Badge from '../Badge';
import Typography from '../Typography';

type Variant = 'filled' | 'outlined' | 'ghost';

const getBackgroundColor = (
  theme: Theme,
  themeIsActive: boolean,
  themeHasLabel: boolean,
  themeVariant: Variant
): string => {
  const { colors } = theme.__hd__.filterTrigger;

  if (themeIsActive && !themeHasLabel && themeVariant === 'filled') {
    return colors.wrapper.background.active.filledLabeless;
  }

  const state = themeIsActive ? 'active' : 'inactive';
  return colors.wrapper.background[state][themeVariant];
};

const getBorderStyles = (
  theme: Theme,
  themeIsActive: boolean,
  themeHasLabel: boolean,
  themeVariant: Variant
) => {
  const { colors, borderWidths, radii } = theme.__hd__.filterTrigger;

  let borderColor: string;
  if (themeIsActive && !themeHasLabel && themeVariant === 'filled') {
    borderColor = colors.wrapper.border.active.filledLabeless;
  } else {
    const state = themeIsActive ? 'active' : 'inactive';
    borderColor = colors.wrapper.border[state][themeVariant];
  }

  return {
    borderWidth: borderWidths.wrapper[themeVariant],
    borderColor,
    borderRadius: themeHasLabel
      ? radii.wrapper.default
      : radii.wrapper.labeless,
  };
};

const getSpacingStyles = (theme: Theme, themeHasLabel: boolean) => {
  const { space } = theme.__hd__.filterTrigger;
  const paddingConfig = themeHasLabel
    ? space.wrapper.default
    : space.wrapper.labeless;

  return {
    gap: space.wrapper.itemGap,
    paddingHorizontal: paddingConfig.paddingHorizontal,
    paddingVertical: paddingConfig.paddingVertical,
  };
};

export const StyledFilterWrapper = styled(TouchableOpacity)<{
  themeActive: boolean;
  themeVariant: Variant;
  themeHasLabel: boolean;
}>(({ theme, themeActive, themeVariant, themeHasLabel }) => ({
  position: 'relative',
  flexDirection: 'row',
  alignItems: 'center',
  justifyContent: 'center',
  alignSelf: 'flex-start',
  height: theme.__hd__.filterTrigger.sizes.wrapperHeight,
  backgroundColor: getBackgroundColor(
    theme,
    themeActive,
    themeHasLabel,
    themeVariant
  ),
  ...getBorderStyles(theme, themeActive, themeHasLabel, themeVariant),
  ...getSpacingStyles(theme, themeHasLabel),
}));

export const StyledBadge = styled(Badge)<{ themeHasLabel: boolean }>(
  ({ theme, themeHasLabel }) => ({
    position: 'absolute',

    ...(themeHasLabel
      ? {
          right: 0,
          bottom: 0,
        }
      : {
          right: -theme.__hd__.filterTrigger.space.badge.labelessRight,
          bottom: -theme.__hd__.filterTrigger.space.badge.labelessBottom,
        }),
  })
);

export const StyledText = styled(Typography.Body)(({ theme }) => ({
  lineHeight: theme.__hd__.filterTrigger.lineHeights.text,
  textAlignVertical: 'center',
  includeFontPadding: false,
}));
