import type { ViewStyle } from 'react-native';
import { Pressable, Text, StyleSheet, View } from 'react-native';
import { ArrowRight } from 'lucide-react-native';
import { color, radius, spacing, typography } from '../theme';
import { naviTheme } from '../theme/naviTheme';

interface Props {
  label: string;
  onPress?: () => void | Promise<void>;
  variant?: 'primary' | 'secondary' | 'ghost';
  style?: ViewStyle;
  disabled?: boolean;
  rightIcon?: boolean;
}

export function PrimaryButton({ label, onPress, variant = 'primary', style, disabled, rightIcon }: Props) {
  const palette =
    variant === 'primary'
      ? { bg: color.blue[600], fg: color.bg[0] }
      : variant === 'secondary'
        ? { bg: color.bg[100], fg: color.ink[900] }
        : { bg: 'transparent', fg: color.blue[600] };

  function handlePress() {
    try {
      const result = onPress?.();
      if (result && typeof result.catch === 'function') {
        void result.catch(() => undefined);
      }
    } catch {
      // Screen-level handlers own user-visible errors. This only prevents
      // native promise failures from surfacing as unhandled rejection toasts.
    }
  }

  return (
    <Pressable
      accessibilityRole="button"
      onPress={handlePress}
      disabled={disabled}
      style={[
        styles.btn,
        variant === 'primary' ? naviTheme.shadows.buttonBlue : null,
        { backgroundColor: palette.bg, opacity: disabled ? 0.5 : 1 },
        style,
      ]}
    >
      <View style={styles.content}>
        <Text style={[styles.label, { color: palette.fg }]}>{label}</Text>
        {rightIcon ? <ArrowRight size={18} color={palette.fg} strokeWidth={2.5} /> : null}
      </View>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  btn: {
    height: 54,
    borderRadius: radius.xl,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: spacing[6],
  },
  content: {
    alignItems: 'center',
    flexDirection: 'row',
    gap: spacing[2],
    justifyContent: 'center',
  },
  label: {
    fontSize: typography.scale.button.size,
    fontWeight: typography.scale.button.weight as '600',
  },
});
