import React from "react";
import {
  IButtonProps,
  usePropsResolution,
  useStyledSystemPropsResolver,
} from "native-base";
import { Pressable as NButton, Text } from "react-native";
import debounce from "lodash.debounce";
import type { GestureResponderEvent } from "react-native";

export const Button: React.FC<
  IButtonProps & {
    debounceDuration?: number;
  }
> = (props) => {
  const { children, onPress, debounceDuration, isDisabled, _icon, ...rest } =
    props;
  const stylesss = usePropsResolution("Button", rest);
  const [buttonStyle, other] = useStyledSystemPropsResolver(stylesss);
  const [textStyle] = useStyledSystemPropsResolver(other._text);
  console.log({ stylesss, buttonStyle, textStyle });

  const onPressDebounce = debounce(
    (event: GestureResponderEvent) => onPress?.(event),
    debounceDuration ?? 500,
    {
      leading: true,
      trailing: false,
    }
  );

  return (
    <NButton
      disabled={isDisabled}
      onPress={onPressDebounce}
      style={[buttonStyle]}
      {...rest}
    >
      {!props.isLoading && React.isValidElement(children) ? (
        children
      ) : (
        <Text style={[textStyle]}>{children}</Text>
      )}
    </NButton>
  );
};

export default Button;
