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

export type ChipTone = "neutral" | "signal";

export type ChipProps = {
  label: string;
  selected?: boolean;
  onPress?: () => void;
  icon?: React.ReactNode;
  tone?: ChipTone;
  testID?: string;
};

/** Small pill used for the offline badge, distance/time-delta labels, etc. */
export function Chip({
  label,
  selected = false,
  onPress,
  icon,
  tone = "neutral",
  testID,
}: ChipProps): React.JSX.Element {
  const isSignal = tone === "signal" || selected;
  const containerStyle = [
    styles.base,
    isSignal ? styles.signal : styles.neutral,
  ];
  const textStyle = [styles.label, isSignal ? styles.signalText : styles.neutralText];

  if (!onPress) {
    return (
      <View style={containerStyle} testID={testID}>
        {icon}
        <Text style={textStyle}>{label}</Text>
      </View>
    );
  }

  return (
    <Pressable
      onPress={onPress}
      accessibilityRole="button"
      accessibilityState={{ selected }}
      testID={testID}
      style={({ pressed }) => [...containerStyle, pressed && styles.pressed]}
    >
      {icon}
      <Text style={textStyle}>{label}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  base: {
    flexDirection: "row",
    alignItems: "center",
    gap: spacing[1],
    paddingHorizontal: spacing[3],
    paddingVertical: spacing[2],
    borderRadius: radius.pill,
    alignSelf: "flex-start",
  },
  neutral: {
    backgroundColor: theme.surface,
    borderWidth: 1,
    borderColor: theme.border,
  },
  signal: {
    backgroundColor: theme.signal,
  },
  label: {
    fontSize: typeScale.caption.fontSize,
    fontWeight: typeScale.label.fontWeight,
  },
  neutralText: {
    color: theme.textSecondary,
  },
  signalText: {
    color: theme.textOnSignal,
  },
  pressed: {
    opacity: 0.85,
  },
});
