import {
  StyleSheet,
  TouchableOpacity,
  ActivityIndicator,
  type TouchableOpacityProps,
} from 'react-native';
import { useTheme } from '../hooks/ThemeProvider';
import type { Theme, RsButtonStyle, RsTextStyle } from '../styles/types';
import Colors from '../styles/colors';
import { useMemo } from 'react';
import RsText from './RsText';

const RsButton: React.FC<
  RsButtonStyle & RsTextStyle & TouchableOpacityProps
> = ({
  primary = true,
  fontSize = 24,
  fontWeight = 'Bold',
  width = '100%',
  title = 'Ramses Button',
  isLoading = false,
  disabled = false,
  style,
  onPress = () => {},
  textStyle,
}) => {
  const theme = useTheme();
  const styles = useMemo(
    () =>
      generateStyles(theme, {
        primary,
        fontSize,
        fontWeight,
        width,
        disabled,
        isLoading,
      }),
    [theme, primary, fontSize, fontWeight, width, disabled, isLoading]
  );

  return (
    <TouchableOpacity
      style={[styles.button, style]}
      onPress={onPress}
      disabled={disabled || isLoading}
      activeOpacity={0.75}
    >
      {isLoading ? (
        <ActivityIndicator
          size="small"
          color={
            primary
              ? theme.Text.primaryButtonText
              : theme.Text.secondaryButtonText
          }
        />
      ) : (
        <RsText
          style={textStyle!}
          text={title}
          fontSize={fontSize}
          fontWeight={fontWeight}
          color={
            primary
              ? theme.Text.primaryButtonText
              : theme.Text.secondaryButtonText
          }
        />
      )}
    </TouchableOpacity>
  );
};

export default RsButton;

const generateStyles = (
  theme: Theme,
  style: RsButtonStyle & RsTextStyle & { disabled: boolean }
) =>
  StyleSheet.create({
    button: {
      backgroundColor: style.primary
        ? style.disabled || style.isLoading
          ? Colors.gray6
          : theme.Background.primaryButton
        : theme.Background.secondaryButton,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 10,
      borderWidth: 1,
      borderRadius: 10,
      borderColor:
        style.disabled || style.isLoading
          ? Colors.gray6
          : style.primary
            ? theme.Borders.primaryButton
            : theme.Borders.secondaryButton,
      width: style.width || '100%',
      height: 48,
    },
  });
