import React from 'react';
import {
  StyleSheet,
  ViewStyle,
  TextStyle,
  TouchableHighlight,
  View,
  ActivityIndicator,
} from 'react-native';
import { useApi, useStyles, useTheme } from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import { LLText } from '../LLText';

export type LLWidgetsLoadMoreButtonStyles = {
  container: ViewStyle;
  buttonContainer: ViewStyle;
  disabledButtonContainer: ViewStyle;
  buttonText: TextStyle;
  disabledButtonText: TextStyle;
  loadingIndicator: TextStyle;
};

export type LLWidgetsLoadMoreButtonProps =
  ComponentStyleProp<LLWidgetsLoadMoreButtonStyles> & {
    disabled?: boolean;
    label?: string;
    onPress: () => Promise<void>;
  };

export function LLWidgetsLoadMoreButton({
  disabled,
  onPress,
  label = 'Load More',
  styles: stylesProp,
}: LLWidgetsLoadMoreButtonProps) {
  const { theme } = useTheme();
  const loadMoreButtonStyles = useStyles({
    componentStylesFn: getWidgetSubmitButtonStyles,
    stylesProp,
  });
  const { isLoading, onApi } = useApi(() => onPress());
  const onPressHandler = () => {
    onApi();
  };
  return (
    <View style={loadMoreButtonStyles.container}>
      <TouchableHighlight
        disabled={disabled || isLoading}
        onPress={onPressHandler}
        style={[
          loadMoreButtonStyles.buttonContainer,
          (disabled || isLoading) &&
            loadMoreButtonStyles.disabledButtonContainer,
        ]}
        underlayColor={theme.primaryPressedButtonBackground}
        activeOpacity={1}
      >
        {isLoading ? (
          <ActivityIndicator
            size={'small'}
            color={theme.disabledButtonText}
            style={loadMoreButtonStyles.loadingIndicator}
          />
        ) : (
          <LLText
            style={[
              loadMoreButtonStyles.buttonText,
              disabled && loadMoreButtonStyles.disabledButtonText,
            ]}
          >
            {label}
          </LLText>
        )}
      </TouchableHighlight>
    </View>
  );
}

const getWidgetSubmitButtonStyles: LLComponentStyleFn<
  LLWidgetsLoadMoreButtonStyles
> = ({ theme }) =>
  StyleSheet.create({
    container: {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      width: '100%',
      marginVertical: 8,
    },
    buttonContainer: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      width: 120,
      height: 32,
      borderRadius: 4,
      marginLeft: 16,
      marginBottom: 16,
      backgroundColor: theme.primaryButtonBackground,
    },
    disabledButtonContainer: {
      backgroundColor: theme.disabledButtonBackground,
    },
    buttonText: {
      fontSize: 14,
    },
    disabledButtonText: {
      color: theme.disabledButtonText,
    },
    loadingIndicator: {},
  });
