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

export type ListRowProps = {
  title: string;
  subtitle?: string;
  leading?: React.ReactNode;
  trailing?: React.ReactNode;
  onPress?: () => void;
  destructive?: boolean;
  testID?: string;
};

/** Grouped-list row for Settings / Territories — not a bare switch on white. */
export function ListRow({
  title,
  subtitle,
  leading,
  trailing,
  onPress,
  destructive = false,
  testID,
}: ListRowProps): React.JSX.Element {
  const titleColor = destructive ? theme.destructive : theme.textPrimary;

  const inner = (
    <View style={styles.row}>
      {leading ? <View style={styles.leading}>{leading}</View> : null}
      <View style={styles.textColumn}>
        <Text style={[styles.title, { color: titleColor }]} numberOfLines={1}>
          {title}
        </Text>
        {subtitle ? (
          <Text style={styles.subtitle} numberOfLines={1}>
            {subtitle}
          </Text>
        ) : null}
      </View>
      {trailing ? <View style={styles.trailing}>{trailing}</View> : null}
    </View>
  );

  if (!onPress) {
    return (
      <View style={styles.container} testID={testID}>
        {inner}
      </View>
    );
  }

  return (
    <Pressable
      onPress={onPress}
      accessibilityRole="button"
      testID={testID}
      style={({ pressed }) => [styles.container, pressed && styles.pressed]}
    >
      {inner}
    </Pressable>
  );
}

const styles = StyleSheet.create({
  container: {
    minHeight: minTouchTarget,
    backgroundColor: theme.surface,
    justifyContent: "center",
    paddingHorizontal: spacing[4],
  },
  pressed: {
    backgroundColor: theme.surfaceAlt,
  },
  row: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: spacing[3],
    gap: spacing[3],
  },
  leading: {
    width: 28,
    alignItems: "center",
  },
  textColumn: {
    flex: 1,
  },
  title: {
    fontSize: typeScale.body.fontSize,
    fontWeight: "500",
  },
  subtitle: {
    marginTop: 2,
    fontSize: typeScale.caption.fontSize,
    color: theme.textSecondary,
  },
  trailing: {
    marginLeft: spacing[2],
  },
});
