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

export type SegmentedControlOption<T extends string> = {
  value: T;
  label: string;
  icon?: React.ReactNode;
};

export type SegmentedControlProps<T extends string> = {
  options: Array<SegmentedControlOption<T>>;
  value: T;
  onChange: (value: T) => void;
  testID?: string;
};

/** e.g. the car / bicycle / walking profile switch on Route preview. */
export function SegmentedControl<T extends string>({
  options,
  value,
  onChange,
  testID,
}: SegmentedControlProps<T>): React.JSX.Element {
  return (
    <View style={styles.track} testID={testID}>
      {options.map((option) => {
        const selected = option.value === value;
        return (
          <Pressable
            key={option.value}
            onPress={() => onChange(option.value)}
            accessibilityRole="button"
            accessibilityState={{ selected }}
            style={({ pressed }) => [
              styles.segment,
              selected && styles.segmentSelected,
              pressed && !selected && styles.segmentPressed,
            ]}
          >
            {option.icon}
            <Text
              style={[styles.label, selected ? styles.labelSelected : styles.labelUnselected]}
              numberOfLines={1}
            >
              {option.label}
            </Text>
          </Pressable>
        );
      })}
    </View>
  );
}

const styles = StyleSheet.create({
  track: {
    flexDirection: "row",
    backgroundColor: theme.surfaceAlt,
    borderRadius: radius.pill,
    padding: 4,
  },
  segment: {
    flex: 1,
    minHeight: minTouchTarget - 8,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    gap: spacing[1],
    borderRadius: radius.pill,
  },
  segmentSelected: {
    backgroundColor: theme.surface,
    ...theme.shadow,
  },
  segmentPressed: {
    backgroundColor: theme.border,
  },
  label: {
    fontSize: typeScale.label.fontSize,
    fontWeight: typeScale.label.fontWeight,
  },
  labelSelected: {
    color: theme.textPrimary,
  },
  labelUnselected: {
    color: theme.textSecondary,
  },
});
