import React, { useCallback, useRef } from 'react';
import { Animated, Pressable, StyleSheet, Text } from 'react-native';
import { useTheme } from '../theme';

interface ButtonProps {
  label: string;
  onPress: () => void;
  variant?: 'primary' | 'secondary' | 'danger';
  disabled?: boolean;
}

/** 按钮（主题化，并有触控动效）。primary=主题色，secondary=次级容器，danger=错误色。 */
export function Button({ label, onPress, variant = 'primary', disabled }: ButtonProps) {
  const { theme } = useTheme();
  const scale = useRef(new Animated.Value(1)).current;

  const handlePressIn = useCallback(() => {
    Animated.spring(scale, {
      toValue: 0.96,
      useNativeDriver: true,
      tension: 180,
      friction: 7,
    }).start();
  }, [scale]);

  const handlePressOut = useCallback(() => {
    Animated.spring(scale, {
      toValue: 1.0,
      useNativeDriver: true,
      tension: 180,
      friction: 7,
    }).start();
  }, [scale]);

  const bg = variant === 'primary' ? theme.colors.accent
    : variant === 'danger' ? theme.colors.error
    : theme.colors.bgTertiary;
  const fg = variant === 'secondary' ? theme.colors.fgPrimary : theme.colors.fgInverse;
  
  return (
    <Pressable
      accessibilityRole="button"
      accessibilityLabel={label}
      accessibilityState={{ disabled: !!disabled }}
      onPress={onPress}
      onPressIn={handlePressIn}
      onPressOut={handlePressOut}
      disabled={disabled}
      style={{ marginTop: 6 }}
    >
      <Animated.View
        style={[
          styles.button,
          {
            backgroundColor: bg,
            borderRadius: theme.radii.xl, // Bento 大圆角 xl (24px)
            opacity: disabled ? 0.5 : 1,
            borderWidth: variant === 'secondary' ? StyleSheet.hairlineWidth : 0,
            borderColor: theme.colors.border,
            transform: [{ scale }],
          },
        ]}
      >
        <Text style={[styles.text, { color: fg }]}>{label}</Text>
      </Animated.View>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: { paddingVertical: 12, paddingHorizontal: 16, alignItems: 'center' },
  text: { fontWeight: '700', fontSize: 16 },
});
