<template>
  <Touchable
    :pressedColor="pressedBackgroundColor"
    :innerStyle="style"
    :touchable="touchable"
    gap="gap.md"
    @click="(e) => emit('click', e)"
    v-bind="$attrs"
  >
    <Icon v-if="icon" v-bind="props" />
    <slot>
      <Text :text="text" />
    </slot>
  </Touchable>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { propGetThemeVar, useTheme, type ViewStyle } from '../theme/ThemeDefine';
import { selectStyleType } from '../theme/ThemeTools';
import type { IconProps } from './Icon.vue';
import Icon from './Icon.vue';
import Touchable from '../feedback/Touchable.vue';
import Text from './Text.vue';

/**
 * 图标按钮形状预设
 * * round: 圆角按钮
 * * round-full: 圆角按钮，宽度和高度相等
 * * square-full: 方角按钮，宽度和高度相等
 * * custom: 自定义按钮形状
 */
export type IconButtonShapeType = 'round'|'round-full'|'square-full'|'custom';

export interface IconButtonProps extends IconProps {
  /**
   * 按钮文字，在自定义slot后无效。
   */
  text?: string;
  /**
   * 按钮按下时的背景颜色
   * @default PressedColor(Color.white)
   */
  pressedBackgroundColor?: string,
  /**
   * 按钮边距
   */
  padding?: number,
  /**
   * 是否可点击
   * @default true
   */
  touchable?: boolean|undefined;
  /**
   * 按钮形状预设
   * @default round
   */
  shape?: IconButtonShapeType;
  /**
   * 是否禁用
   * @default false
   */
  disabled?: boolean|undefined;
  /**
   * 按钮样式
   */
  buttonStyle?: ViewStyle;
  /**
   * 按钮大小。可以是一个数字，也可以是一个数组，数组的第一个元素是宽度，第二个元素是高度。
   */
  buttonSize?: number|((number|string)[])|string;
  /**
   * 按钮背景颜色
   */
  backgroundColor?: string;
}

const emit = defineEmits(['click']);
const theme = useTheme();
const props = withDefaults(defineProps<IconButtonProps>(), {
  shape: 'custom',
  pressedBackgroundColor: () => propGetThemeVar('IconButtonPressedColor', 'pressed.white'),
  touchable: true,
});
const style = computed(() => {
  return {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: props.padding,
    width: Array.isArray(props.buttonSize) ? theme.resolveThemeSize(props.buttonSize[0]) : theme.resolveThemeSize(props.buttonSize),
    height: Array.isArray(props.buttonSize) ? theme.resolveThemeSize(props.buttonSize[1]) : theme.resolveThemeSize(props.buttonSize),
    backgroundColor: theme.resolveThemeColor(props.backgroundColor),
    ...selectStyleType(props.shape, 'round', {
      "round": {
        borderRadius: theme.resolveThemeSize('IconButtonRoundBorderRadius', 20),
      },
      "round-full": {
        height: '100%',
        aspectRatio: 1,
        borderRadius: '50%',
      },
      "custom": {},
      "square-full": {
        height: '100%',
        aspectRatio: 1,
        borderRadius: 0,
      },
    }),
    opacity: props.disabled ? theme.getVar('IconButtonDisabledOpacity', 0.4) : 1,
    ...props.buttonStyle,
  };
});

defineOptions({
  options: {
    inheritAttrs: false,
    virtualHost: true,
  }
})
</script>