import { router, type Href } from 'expo-router';
import type { StyleProp, ViewStyle } from 'react-native';
import { Pressable, StyleSheet, Text } from 'react-native';
import { color, spacing, typography } from '../theme';

interface Props<T extends string | Record<'pathname', string> = '/(tabs)/home'> {
  label?: string;
  fallbackHref?: Href<T>;
  onPress?: () => void;
  style?: StyleProp<ViewStyle>;
}

const DEFAULT_FALLBACK: Href<'/(tabs)/home'> = '/(tabs)/home';

export function BackButton<T extends string | Record<'pathname', string> = '/(tabs)/home'>({
  label = 'Back',
  fallbackHref,
  onPress,
  style,
}: Props<T>) {
  function handlePress() {
    if (onPress) {
      onPress();
      return;
    }
    if (router.canGoBack()) {
      router.back();
      return;
    }
    if (fallbackHref) {
      router.replace(fallbackHref);
      return;
    }
    router.replace(DEFAULT_FALLBACK);
  }

  return (
    <Pressable
      accessibilityLabel={label}
      accessibilityRole="button"
      hitSlop={12}
      onPress={handlePress}
      style={[styles.button, style]}
    >
      <Text style={styles.label}>{`< ${label}`}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: {
    alignSelf: 'flex-start',
    minHeight: 36,
    justifyContent: 'center',
    paddingRight: spacing[4],
  },
  label: {
    color: color.blue[600],
    fontSize: typography.scale.body.size,
    fontWeight: '600',
  },
});
