import React from "react";
import {
  ActivityIndicator,
  Pressable,
  StyleProp,
  StyleSheet,
  Text,
  ViewStyle,
} from "react-native";
import { minTouchTarget, radius, spacing, theme, typeScale } from "../theme";

export type ButtonVariant = "primary" | "secondary" | "destructive";

export type ButtonProps = {
  label: string;
  onPress: () => void;
  variant?: ButtonVariant;
  disabled?: boolean;
  loading?: boolean;
  fullWidth?: boolean;
  style?: StyleProp<ViewStyle>;
  accessibilityLabel?: string;
  testID?: string;
};

/**
 * Filled signal pill / tonal secondary / destructive button.
 * Never mix variants within one action group (UI spec rule).
 */
export function Button({
  label,
  onPress,
  variant = "primary",
  disabled = false,
  loading = false,
  fullWidth = false,
  style,
  accessibilityLabel,
  testID,
}: ButtonProps): React.JSX.Element {
  const isDisabled = disabled || loading;

  return (
    <Pressable
      onPress={onPress}
      disabled={isDisabled}
      accessibilityRole="button"
      accessibilityState={{ disabled: isDisabled, busy: loading }}
      accessibilityLabel={accessibilityLabel ?? label}
      testID={testID}
      style={({ pressed }) => [
        styles.base,
        variantStyles[variant].container,
        fullWidth && styles.fullWidth,
        isDisabled && styles.disabled,
        pressed && !isDisabled && variantStyles[variant].pressed,
        style,
      ]}
    >
      {loading ? (
        <ActivityIndicator
          size="small"
          color={variantStyles[variant].text.color}
        />
      ) : (
        <Text
          style={[
            styles.label,
            variantStyles[variant].text,
            isDisabled && styles.disabledText,
          ]}
          numberOfLines={1}
        >
          {label}
        </Text>
      )}
    </Pressable>
  );
}

const styles = StyleSheet.create({
  base: {
    minHeight: minTouchTarget,
    borderRadius: radius.pill,
    paddingHorizontal: spacing[6],
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "row",
  },
  fullWidth: {
    alignSelf: "stretch",
  },
  label: {
    fontSize: typeScale.label.fontSize,
    fontWeight: typeScale.label.fontWeight,
  },
  disabled: {
    opacity: 0.5,
  },
  disabledText: {},
});

const variantStyles: Record<
  ButtonVariant,
  { container: ViewStyle; pressed: ViewStyle; text: { color: string } }
> = {
  primary: {
    container: { backgroundColor: theme.signal },
    pressed: { backgroundColor: theme.signalPressed },
    text: { color: theme.textOnSignal },
  },
  secondary: {
    container: {
      backgroundColor: theme.surfaceAlt,
      borderWidth: 1,
      borderColor: theme.border,
    },
    pressed: { backgroundColor: theme.border },
    text: { color: theme.textPrimary },
  },
  destructive: {
    container: { backgroundColor: theme.destructive },
    pressed: { backgroundColor: theme.destructivePressed },
    text: { color: theme.onDestructive },
  },
};
