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

export type SearchPillProps = {
  placeholder?: string;
  onPress: () => void;
  onSettingsPress: () => void;
  /** Custom gear/settings glyph; falls back to a plain dot. */
  settingsIcon?: React.ReactNode;
  testID?: string;
};

/**
 * Floating pill over the map (S3): "Search here" with a gear icon in the
 * pill's trailing edge for Settings. Tapping the body opens the search
 * sheet (S4); the gear is a separate hit target.
 */
export function SearchPill({
  placeholder = "Search here",
  onPress,
  onSettingsPress,
  settingsIcon,
  testID,
}: SearchPillProps): React.JSX.Element {
  return (
    <View style={styles.container} testID={testID}>
      <Pressable
        onPress={onPress}
        accessibilityRole="search"
        accessibilityLabel={placeholder}
        style={({ pressed }) => [styles.body, pressed && styles.bodyPressed]}
      >
        <Text style={styles.placeholder} numberOfLines={1}>
          {placeholder}
        </Text>
      </Pressable>
      <Pressable
        onPress={onSettingsPress}
        accessibilityRole="button"
        accessibilityLabel="Settings"
        hitSlop={8}
        style={({ pressed }) => [styles.gear, pressed && styles.gearPressed]}
      >
        {settingsIcon ?? <View style={styles.gearDot} />}
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: theme.surface,
    borderRadius: radius.pill,
    paddingLeft: spacing[4],
    paddingRight: spacing[2],
    minHeight: minTouchTarget,
    ...theme.shadow,
  },
  body: {
    flex: 1,
    justifyContent: "center",
    minHeight: minTouchTarget,
  },
  bodyPressed: {
    opacity: 0.7,
  },
  placeholder: {
    fontSize: typeScale.body.fontSize,
    color: theme.textSecondary,
  },
  gear: {
    width: minTouchTarget - 8,
    height: minTouchTarget - 8,
    borderRadius: radius.pill,
    alignItems: "center",
    justifyContent: "center",
  },
  gearPressed: {
    backgroundColor: theme.surfaceAlt,
  },
  gearDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: theme.textSecondary,
  },
});
