import React, { useState, useCallback } from 'react';
import {
  StyleSheet,
  TouchableOpacity,
  View,
  Text,
  ActivityIndicator,
  Animated,
  Pressable,
  Platform,
} from 'react-native';

/**
 * FEATURE: Fully Customizable Button Component - KHÔNG CÓ GIÁ TRỊ CỐ ĐỊNH
 * 
 * Tất cả props đều optional và có thể override hoàn toàn
 * Không có default styles cứng, chỉ có fallback khi không truyền props
 */

const Button = ({
  // FUNCTIONALITY: Text & Action props
  title,
  onPress,
  
  // UI/UX: Icon props
  icon: IconComponent,
  iconPosition = 'left',
  iconSize,
  iconColor,
  
  // UI/UX: Icon Spacing props - TỰ TÙY CHỈNH HOÀN TOÀN
  iconSpacing, // Áp dụng cho tất cả directions
  iconSpacingHorizontal, // Chỉ cho left/right
  iconSpacingVertical, // Chỉ cho top/bottom
  iconSpacingLeft, // Chỉ khi icon ở left
  iconSpacingRight, // Chỉ khi icon ở right  
  iconSpacingTop, // Chỉ khi icon ở top
  iconSpacingBottom, // Chỉ khi icon ở bottom
  
  // UI/UX: Dimension props - HOÀN TOÀN TÙY CHỈNH
  width,
  height,
  paddingHorizontal,
  paddingVertical,
  paddingTop,
  paddingBottom,
  paddingLeft,
  paddingRight,
  margin,
  marginHorizontal,
  marginVertical,
  marginTop,
  marginBottom,
  marginLeft,
  marginRight,
  
  // UI/UX: Color props - HOÀN TOÀN TÙY CHỈNH
  backgroundColor,
  pressedBackgroundColor,
  disabledBackgroundColor,
  textColor,
  pressedTextColor,
  disabledTextColor,
  
  // UI/UX: Border props - HOÀN TOÀN TÙY CHỈNH
  borderRadius,
  borderTopLeftRadius,
  borderTopRightRadius,
  borderBottomLeftRadius,
  borderBottomRightRadius,
  borderWidth,
  borderTopWidth,
  borderBottomWidth,
  borderLeftWidth,
  borderRightWidth,
  borderColor,
  borderTopColor,
  borderBottomColor,
  borderLeftColor,
  borderRightColor,
  borderStyle,
  
  // UI/UX: Text props - HOÀN TOÀN TÙY CHỈNH
  fontSize,
  fontWeight,
  fontFamily,
  fontStyle,
  textAlign,
  textDecorationLine,
  textDecorationStyle,
  textDecorationColor,
  letterSpacing,
  lineHeight,
  textTransform,
  numberOfLines,
  
  // UI/UX: Text Padding props - CHỈ CHO TEXT
  textPaddingHorizontal,
  textPaddingVertical,
  textPaddingTop,
  textPaddingBottom,
  textPaddingLeft,
  textPaddingRight,
  
  // STATE: Interaction props
  disabled = false,
  loading = false,
  
  // UI/UX: Layout props - HOÀN TOÀN TÙY CHỈNH
  justifyContent,
  alignItems,
  alignSelf,
  flexDirection,
  flex,
  flexWrap,
  flexGrow,
  flexShrink,
  flexBasis,
  
  // FEATURE: Inline layout props - CHO BUTTONS CÙNG DÒNG
  inline = false, // Tự động set flex để buttons nằm cùng dòng
  inlineSpacing, // Margin giữa các inline buttons
  
  // UI/UX: Position props - HOÀN TOÀN TÙY CHỈNH
  position,
  top,
  bottom,
  left,
  right,
  zIndex,
  
  // UI/UX: Shadow props - HOÀN TOÀN TÙY CHỈNH
  shadowColor,
  shadowOffset,
  shadowOpacity,
  shadowRadius,
  elevation,
  
  // UI/UX: Background props - HOÀN TOÀN TÙY CHỈNH
  opacity,
  transform,
  
  // PERFORMANCE: Style override props
  containerStyle = {},
  textStyle = {},
  iconStyle = {},
  iconContainerStyle = {},
  contentContainerStyle = {},
  loadingStyle = {},
  
  // FEATURE: Interaction props - HOÀN TOÀN TÙY CHỈNH
  activeOpacity,
  delayPressIn,
  delayPressOut,
  delayLongPress,
  onPressIn,
  onPressOut,
  onLongPress,
  
  // FEATURE: Animation props - HOÀN TOÀN TÙY CHỈNH
  enableAnimation = true,
  animationScale,
  animationOpacity,
  animationDuration,
  animationDelay,
  
  // FEATURE: Platform specific props
  useRipple = false,
  rippleColor,
  rippleBorderless = false,
  
  // FEATURE: Loading props - HOÀN TOÀN TÙY CHỈNH
  loadingSize,
  loadingColor,
  hideTextWhenLoading = false,
  hideIconWhenLoading = false,
  
  // FEATURE: Accessibility props
  accessible,
  accessibilityLabel,
  accessibilityHint,
  accessibilityRole,
  testID,
  
  // CONFIG: Custom props
  hitSlop,
  pressRetentionOffset,
  
}) => {
  
  // STATE: Animation và interaction state
  const [isPressed, setIsPressed] = useState(false);
  const [animatedValue] = useState(new Animated.Value(1));
  
  // FUNCTIONALITY: Handle press animations - TÙY CHỈNH HOÀN TOÀN
  const handlePressIn = useCallback((event) => {
    setIsPressed(true);
    onPressIn && onPressIn(event);
    
    if (enableAnimation && !disabled && !loading) {
      const animations = [];
      
      if (animationScale !== undefined) {
        animations.push(
          Animated.timing(animatedValue, {
            toValue: animationScale,
            duration: animationDuration || 150,
            delay: animationDelay || 0,
            useNativeDriver: true,
          })
        );
      }
      
      if (animations.length > 0) {
        Animated.parallel(animations).start();
      }
    }
  }, [
    onPressIn, enableAnimation, disabled, loading, animationScale, 
    animationDuration, animationDelay, animatedValue
  ]);
  
  // FUNCTIONALITY: Handle press release - TÙY CHỈNH HOÀN TOÀN
  const handlePressOut = useCallback((event) => {
    setIsPressed(false);
    onPressOut && onPressOut(event);
    
    if (enableAnimation && !disabled && !loading) {
      const animations = [];
      
      if (animationScale !== undefined) {
        animations.push(
          Animated.timing(animatedValue, {
            toValue: 1,
            duration: animationDuration || 150,
            delay: animationDelay || 0,
            useNativeDriver: true,
          })
        );
      }
      
      if (animations.length > 0) {
        Animated.parallel(animations).start();
      }
    }
  }, [
    onPressOut, enableAnimation, disabled, loading, animationScale,
    animationDuration, animationDelay, animatedValue
  ]);
  
  // FUNCTIONALITY: Handle press action
  const handlePress = useCallback((event) => {
    if (disabled || loading) return;
    onPress && onPress(event);
  }, [disabled, loading, onPress]);
  
  // FUNCTIONALITY: Handle long press
  const handleLongPress = useCallback((event) => {
    if (disabled || loading) return;
    onLongPress && onLongPress(event);
  }, [disabled, loading, onLongPress]);
  
  // FUNCTIONALITY: Calculate icon spacing - LOGIC TỰ TÙY CHỈNH
  const getIconSpacing = useCallback(() => {
    // FEATURE: Priority system cho spacing
    // 1. Specific position spacing (highest priority)
    // 2. Horizontal/Vertical spacing
    // 3. General iconSpacing
    // 4. No spacing (0)
    
    let horizontal = 0;
    let vertical = 0;
    
    // FUNCTIONALITY: Horizontal spacing (left/right positions)
    if (iconPosition === 'left' || iconPosition === 'right') {
      if (iconPosition === 'left' && iconSpacingLeft !== undefined) {
        horizontal = iconSpacingLeft;
      } else if (iconPosition === 'right' && iconSpacingRight !== undefined) {
        horizontal = iconSpacingRight;
      } else if (iconSpacingHorizontal !== undefined) {
        horizontal = iconSpacingHorizontal;
      } else if (iconSpacing !== undefined) {
        horizontal = iconSpacing;
      }
    }
    
    // FUNCTIONALITY: Vertical spacing (top/bottom positions)
    if (iconPosition === 'top' || iconPosition === 'bottom') {
      if (iconPosition === 'top' && iconSpacingTop !== undefined) {
        vertical = iconSpacingTop;
      } else if (iconPosition === 'bottom' && iconSpacingBottom !== undefined) {
        vertical = iconSpacingBottom;
      } else if (iconSpacingVertical !== undefined) {
        vertical = iconSpacingVertical;
      } else if (iconSpacing !== undefined) {
        vertical = iconSpacing;
      }
    }
    
    return { horizontal, vertical };
  }, [
    iconPosition, iconSpacing, iconSpacingHorizontal, iconSpacingVertical,
    iconSpacingLeft, iconSpacingRight, iconSpacingTop, iconSpacingBottom
  ]);
  
  // UI/UX: Build container styles - HOÀN TOÀN TÙY CHỈNH
  const buildContainerStyles = useCallback(() => {
    const styles = {};
    
    // FUNCTIONALITY: Dimensions - chỉ set khi có value
    if (width !== undefined) styles.width = width;
    if (height !== undefined) styles.height = height;
    
    // FUNCTIONALITY: Padding - chỉ set khi có value
    if (paddingHorizontal !== undefined) {
      styles.paddingLeft = paddingHorizontal;
      styles.paddingRight = paddingHorizontal;
    }
    if (paddingVertical !== undefined) {
      styles.paddingTop = paddingVertical;
      styles.paddingBottom = paddingVertical;
    }
    if (paddingTop !== undefined) styles.paddingTop = paddingTop;
    if (paddingBottom !== undefined) styles.paddingBottom = paddingBottom;
    if (paddingLeft !== undefined) styles.paddingLeft = paddingLeft;
    if (paddingRight !== undefined) styles.paddingRight = paddingRight;
    
    // FUNCTIONALITY: Margin - chỉ set khi có value
    if (margin !== undefined) styles.margin = margin;
    if (marginHorizontal !== undefined) {
      styles.marginLeft = marginHorizontal;
      styles.marginRight = marginHorizontal;
    }
    if (marginVertical !== undefined) {
      styles.marginTop = marginVertical;
      styles.marginBottom = marginVertical;
    }
    if (marginTop !== undefined) styles.marginTop = marginTop;
    if (marginBottom !== undefined) styles.marginBottom = marginBottom;
    if (marginLeft !== undefined) styles.marginLeft = marginLeft;
    if (marginRight !== undefined) styles.marginRight = marginRight;
    
    // FUNCTIONALITY: Background colors - với state logic
    if (disabled && disabledBackgroundColor !== undefined) {
      styles.backgroundColor = disabledBackgroundColor;
    } else if (isPressed && pressedBackgroundColor !== undefined) {
      styles.backgroundColor = pressedBackgroundColor;
    } else if (backgroundColor !== undefined) {
      styles.backgroundColor = backgroundColor;
    }
    
    // FUNCTIONALITY: Border radius - chỉ set khi có value
    if (borderRadius !== undefined) styles.borderRadius = borderRadius;
    if (borderTopLeftRadius !== undefined) styles.borderTopLeftRadius = borderTopLeftRadius;
    if (borderTopRightRadius !== undefined) styles.borderTopRightRadius = borderTopRightRadius;
    if (borderBottomLeftRadius !== undefined) styles.borderBottomLeftRadius = borderBottomLeftRadius;
    if (borderBottomRightRadius !== undefined) styles.borderBottomRightRadius = borderBottomRightRadius;
    
    // FUNCTIONALITY: Border width - chỉ set khi có value
    if (borderWidth !== undefined) styles.borderWidth = borderWidth;
    if (borderTopWidth !== undefined) styles.borderTopWidth = borderTopWidth;
    if (borderBottomWidth !== undefined) styles.borderBottomWidth = borderBottomWidth;
    if (borderLeftWidth !== undefined) styles.borderLeftWidth = borderLeftWidth;
    if (borderRightWidth !== undefined) styles.borderRightWidth = borderRightWidth;
    
    // FUNCTIONALITY: Border color - chỉ set khi có value
    if (borderColor !== undefined) styles.borderColor = borderColor;
    if (borderTopColor !== undefined) styles.borderTopColor = borderTopColor;
    if (borderBottomColor !== undefined) styles.borderBottomColor = borderBottomColor;
    if (borderLeftColor !== undefined) styles.borderLeftColor = borderLeftColor;
    if (borderRightColor !== undefined) styles.borderRightColor = borderRightColor;
    if (borderStyle !== undefined) styles.borderStyle = borderStyle;
    
    // FUNCTIONALITY: Layout - chỉ set khi có value
    if (justifyContent !== undefined) styles.justifyContent = justifyContent;
    if (alignItems !== undefined) styles.alignItems = alignItems;
    if (alignSelf !== undefined) styles.alignSelf = alignSelf;
    if (flexDirection !== undefined) styles.flexDirection = flexDirection;
    if (flex !== undefined) styles.flex = flex;
    if (flexWrap !== undefined) styles.flexWrap = flexWrap;
    if (flexGrow !== undefined) styles.flexGrow = flexGrow;
    if (flexShrink !== undefined) styles.flexShrink = flexShrink;
    if (flexBasis !== undefined) styles.flexBasis = flexBasis;
    
    // FEATURE: Inline layout - buttons cùng dòng
    if (inline) {
      styles.flex = flex !== undefined ? flex : 1; // Default flex = 1 khi inline
      if (inlineSpacing !== undefined) {
        styles.marginHorizontal = inlineSpacing;
      }
    }
    
    // FUNCTIONALITY: Position - chỉ set khi có value
    if (position !== undefined) styles.position = position;
    if (top !== undefined) styles.top = top;
    if (bottom !== undefined) styles.bottom = bottom;
    if (left !== undefined) styles.left = left;
    if (right !== undefined) styles.right = right;
    if (zIndex !== undefined) styles.zIndex = zIndex;
    
    // FUNCTIONALITY: Shadow - chỉ set khi có value
    if (shadowColor !== undefined) styles.shadowColor = shadowColor;
    if (shadowOffset !== undefined) styles.shadowOffset = shadowOffset;
    if (shadowOpacity !== undefined) styles.shadowOpacity = shadowOpacity;
    if (shadowRadius !== undefined) styles.shadowRadius = shadowRadius;
    if (elevation !== undefined) styles.elevation = elevation;
    
    // FUNCTIONALITY: Transform & Opacity - chỉ set khi có value
    if (opacity !== undefined) styles.opacity = opacity;
    if (transform !== undefined) styles.transform = transform;
    
    return styles;
  }, [
    width, height, paddingHorizontal, paddingVertical, paddingTop, paddingBottom,
    paddingLeft, paddingRight, margin, marginHorizontal, marginVertical,
    marginTop, marginBottom, marginLeft, marginRight, disabled, isPressed,
    disabledBackgroundColor, pressedBackgroundColor, backgroundColor,
    borderRadius, borderTopLeftRadius, borderTopRightRadius, borderBottomLeftRadius,
    borderBottomRightRadius, borderWidth, borderTopWidth, borderBottomWidth,
    borderLeftWidth, borderRightWidth, borderColor, borderTopColor, borderBottomColor,
    borderLeftColor, borderRightColor, borderStyle, justifyContent, alignItems,
    alignSelf, flexDirection, flex, flexWrap, flexGrow, flexShrink, flexBasis,
    inline, inlineSpacing, position, top, bottom, left, right, zIndex, shadowColor, 
    shadowOffset, shadowOpacity, shadowRadius, elevation, opacity, transform
  ]);
  
  // UI/UX: Build text styles - HOÀN TOÀN TÙY CHỈNH
  const buildTextStyles = useCallback(() => {
    const styles = {};
    
    // FUNCTIONALITY: Text colors - với state logic
    if (disabled && disabledTextColor !== undefined) {
      styles.color = disabledTextColor;
    } else if (isPressed && pressedTextColor !== undefined) {
      styles.color = pressedTextColor;
    } else if (textColor !== undefined) {
      styles.color = textColor;
    }
    
    // FUNCTIONALITY: Text properties - chỉ set khi có value
    if (fontSize !== undefined) styles.fontSize = fontSize;
    if (fontWeight !== undefined) styles.fontWeight = fontWeight;
    if (fontFamily !== undefined) styles.fontFamily = fontFamily;
    if (fontStyle !== undefined) styles.fontStyle = fontStyle;
    if (textAlign !== undefined) styles.textAlign = textAlign;
    if (textDecorationLine !== undefined) styles.textDecorationLine = textDecorationLine;
    if (textDecorationStyle !== undefined) styles.textDecorationStyle = textDecorationStyle;
    if (textDecorationColor !== undefined) styles.textDecorationColor = textDecorationColor;
    if (letterSpacing !== undefined) styles.letterSpacing = letterSpacing;
    if (lineHeight !== undefined) styles.lineHeight = lineHeight;
    if (textTransform !== undefined) styles.textTransform = textTransform;
    
    // FEATURE: Text padding - chỉ cho text element
    if (textPaddingHorizontal !== undefined) {
      styles.paddingLeft = textPaddingHorizontal;
      styles.paddingRight = textPaddingHorizontal;
    }
    if (textPaddingVertical !== undefined) {
      styles.paddingTop = textPaddingVertical;
      styles.paddingBottom = textPaddingVertical;
    }
    if (textPaddingTop !== undefined) styles.paddingTop = textPaddingTop;
    if (textPaddingBottom !== undefined) styles.paddingBottom = textPaddingBottom;
    if (textPaddingLeft !== undefined) styles.paddingLeft = textPaddingLeft;
    if (textPaddingRight !== undefined) styles.paddingRight = textPaddingRight;
    
    return styles;
  }, [
    disabled, isPressed, disabledTextColor, pressedTextColor, textColor,
    fontSize, fontWeight, fontFamily, fontStyle, textAlign, textDecorationLine,
    textDecorationStyle, textDecorationColor, letterSpacing, lineHeight, textTransform,
    textPaddingHorizontal, textPaddingVertical, textPaddingTop, textPaddingBottom,
    textPaddingLeft, textPaddingRight
  ]);
  
  // UI/UX: Get current icon color - TÙY CHỈNH HOÀN TOÀN
  const getCurrentIconColor = useCallback(() => {
    if (disabled && disabledTextColor !== undefined) {
      return disabledTextColor;
    }
    if (isPressed && pressedTextColor !== undefined) {
      return pressedTextColor;
    }
    if (iconColor !== undefined) {
      return iconColor;
    }
    if (textColor !== undefined) {
      return textColor;
    }
    return undefined;
  }, [disabled, isPressed, disabledTextColor, pressedTextColor, iconColor, textColor]);
  
  // UI/UX: Build animation styles
  const buildAnimationStyles = useCallback(() => {
    const styles = {};
    
    if (enableAnimation) {
      const transformArray = [];
      
      if (animationScale !== undefined) {
        transformArray.push({ scale: animatedValue });
      }
      
      if (transformArray.length > 0) {
        styles.transform = transformArray;
      }
      
      if (animationOpacity !== undefined) {
        styles.opacity = animatedValue;
      }
    }
    
    return styles;
  }, [enableAnimation, animationScale, animationOpacity, animatedValue]);
  
  // UI/UX: Render icon - HOÀN TOÀN TÙY CHỈNH
  const renderIcon = useCallback(() => {
    if (!IconComponent || (loading && hideIconWhenLoading)) return null;
    
    const iconProps = {};
    if (iconSize !== undefined) iconProps.size = iconSize;
    
    const currentIconColor = getCurrentIconColor();
    if (currentIconColor !== undefined) iconProps.color = currentIconColor;
    
    // FEATURE: Icon container với proper alignment
    const iconContainerStyles = [
      {
        // UI/UX: Đảm bảo icon align center
        justifyContent: 'center',
        alignItems: 'center',
      },
      iconContainerStyle
    ];
    
    return (
      <View style={iconContainerStyles}>
        {typeof IconComponent === 'function' ? (
          <IconComponent {...iconProps} style={iconStyle} />
        ) : (
          React.cloneElement(IconComponent, { 
            ...iconProps, 
            style: [IconComponent.props?.style, iconStyle] 
          })
        )}
      </View>
    );
  }, [
    IconComponent, loading, hideIconWhenLoading, iconSize, getCurrentIconColor,
    iconContainerStyle, iconStyle
  ]);
  
  // UI/UX: Render text - HOÀN TOÀN TÙY CHỈNH
  const renderText = useCallback(() => {
    if (!title || (loading && hideTextWhenLoading)) return null;
    
    return (
      <Text
        style={[buildTextStyles(), textStyle]}
        numberOfLines={numberOfLines}
      >
        {title}
      </Text>
    );
  }, [title, loading, hideTextWhenLoading, buildTextStyles, textStyle, numberOfLines]);
  
  // UI/UX: Render loading - HOÀN TOÀN TÙY CHỈNH
  const renderLoading = useCallback(() => {
    if (!loading) return null;
    
    const loadingProps = {};
    if (loadingSize !== undefined) loadingProps.size = loadingSize;
    if (loadingColor !== undefined) loadingProps.color = loadingColor;
    
    return (
      <ActivityIndicator
        {...loadingProps}
        style={loadingStyle}
      />
    );
  }, [loading, loadingSize, loadingColor, loadingStyle]);
  
  // UI/UX: Render content based on icon position
  const renderContent = useCallback(() => {
    const iconElement = renderIcon();
    const textElement = renderText();
    const loadingElement = renderLoading();
    const spacing = getIconSpacing();
    
    // FUNCTIONALITY: Build content container style với proper alignment
    const getContentContainerStyle = () => {
      const baseStyle = {
        // FEATURE: Default alignment cho icon + text
        flexDirection: iconPosition === 'top' || iconPosition === 'bottom' ? 'column' : 'row',
        justifyContent: 'center',
        alignItems: 'center',
        // PERFORMANCE: Đảm bảo content luôn center trong button
        flex: 1,
      };
      
      return [baseStyle, contentContainerStyle];
    };
    
    // FUNCTIONALITY: Loading state với proper layout
    if (loading) {
      return (
        <View style={getContentContainerStyle()}>
          {loadingElement}
          {!hideTextWhenLoading && textElement && (
            <View style={{ 
              marginLeft: iconPosition === 'left' || iconPosition === 'right' ? spacing.horizontal : 0,
              marginTop: iconPosition === 'top' || iconPosition === 'bottom' ? spacing.vertical : 0,
            }}>
              {textElement}
            </View>
          )}
          {!hideIconWhenLoading && iconElement}
        </View>
      );
    }
    
    // UI/UX: Render content theo icon position với CUSTOM spacing
    const renderContentByPosition = () => {
      // FEATURE: Dynamic spacing based on icon position & custom props
      const getSpacingStyle = (elementType, position) => {
        const style = {};
        
        if (elementType === 'icon') {
          switch (position) {
            case 'left':
              if (textElement) style.marginRight = spacing.horizontal;
              break;
            case 'right':
              if (textElement) style.marginLeft = spacing.horizontal;
              break;
            case 'top':
              if (textElement) style.marginBottom = spacing.vertical;
              break;
            case 'bottom':
              if (textElement) style.marginTop = spacing.vertical;
              break;
          }
        } else if (elementType === 'text') {
          switch (position) {
            case 'left':
              if (iconElement) style.marginLeft = spacing.horizontal;
              break;
            case 'right':
              if (iconElement) style.marginRight = spacing.horizontal;
              break;
            case 'top':
              if (iconElement) style.marginTop = spacing.vertical;
              break;
            case 'bottom':
              if (iconElement) style.marginBottom = spacing.vertical;
              break;
          }
        }
        
        return style;
      };
      
      switch (iconPosition) {
        case 'top':
          return (
            <>
              {iconElement && (
                <View style={getSpacingStyle('icon', 'top')}>
                  {iconElement}
                </View>
              )}
              {textElement && (
                <View style={getSpacingStyle('text', 'top')}>
                  {textElement}
                </View>
              )}
            </>
          );
          
        case 'bottom':
          return (
            <>
              {textElement && (
                <View style={getSpacingStyle('text', 'bottom')}>
                  {textElement}
                </View>
              )}
              {iconElement && (
                <View style={getSpacingStyle('icon', 'bottom')}>
                  {iconElement}
                </View>
              )}
            </>
          );
          
        case 'right':
          return (
            <>
              {textElement && (
                <View style={getSpacingStyle('text', 'right')}>
                  {textElement}
                </View>
              )}
              {iconElement && (
                <View style={getSpacingStyle('icon', 'right')}>
                  {iconElement}
                </View>
              )}
            </>
          );
          
        default: // left
          return (
            <>
              {iconElement && (
                <View style={getSpacingStyle('icon', 'left')}>
                  {iconElement}
                </View>
              )}
              {textElement && (
                <View style={getSpacingStyle('text', 'left')}>
                  {textElement}
                </View>
              )}
            </>
          );
      }
    };
    
    return (
      <View style={getContentContainerStyle()}>
        {renderContentByPosition()}
      </View>
    );
  }, [
    renderIcon, renderText, renderLoading, loading, iconPosition,
    contentContainerStyle, hideTextWhenLoading, hideIconWhenLoading, getIconSpacing
  ]);
  
  // PERFORMANCE: Build final styles
  const containerStyles = [
    buildContainerStyles(),
    containerStyle,
  ];
  
  const animationStyles = buildAnimationStyles();
  
  // FEATURE: Common props cho TouchableOpacity/Pressable
  const commonProps = {
    onPress: handlePress,
    onPressIn: handlePressIn,
    onPressOut: handlePressOut,
    onLongPress: onLongPress,
    disabled: disabled || loading,
    delayPressIn,
    delayPressOut,
    delayLongPress,
    hitSlop,
    pressRetentionOffset,
    accessible,
    accessibilityLabel,
    accessibilityHint,
    accessibilityRole,
    testID,
  };
  
  // PERFORMANCE: Sử dụng Pressable với ripple cho Android
  if (useRipple && Platform.OS === 'android') {
    const rippleConfig = {};
    if (rippleColor !== undefined) rippleConfig.color = rippleColor;
    if (rippleBorderless !== undefined) rippleConfig.borderless = rippleBorderless;
    
    return (
      <Animated.View style={animationStyles}>
        <Pressable
          style={containerStyles}
          android_ripple={rippleConfig}
          {...commonProps}
        >
          {renderContent()}
        </Pressable>
      </Animated.View>
    );
  }
  
  // UI/UX: Default TouchableOpacity
  return (
    <Animated.View style={animationStyles}>
      <TouchableOpacity
        style={containerStyles}
        activeOpacity={activeOpacity}
        {...commonProps}
      >
        {renderContent()}
      </TouchableOpacity>
    </Animated.View>
  );
};

export default Button;