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

export type LLLoadActionButtonStyles = {
  buttonContainer: ViewStyle;
  button: ViewStyle;
  disabledbutton: ViewStyle;
  buttonText: TextStyle;
  disabledButtonText: TextStyle;
};

export type LLLoadActionButtonProps =
  ComponentStyleProp<LLLoadActionButtonStyles> & {
    widgetId: string;
  };

export type LLLoadActionButtonComponentProps =
  ComponentStyleProp<LLLoadActionButtonStyles> & {
    label?: string;
    actionInProgressLabel?: string;
    onPress: () => Promise<unknown>;
  };

export function LLLoadActionButtonComponent({
  onPress,
  label,
  actionInProgressLabel,
  styles: stylesProp,
}: LLLoadActionButtonComponentProps) {
  const loadMoreStyles = useStyles({
    componentStylesFn: getLoadMoreButtonStyles,
    stylesProp,
  });
  const { theme } = useTheme();
  const [isLoading, setIsLoading] = useState(false);

  const onLoad = useCallback(() => {
    setIsLoading(true);
    onPress().finally(() => {
      setIsLoading(false);
    });
  }, [setIsLoading, onPress]);

  return (
    <View style={loadMoreStyles.buttonContainer}>
      <TouchableHighlight
        disabled={isLoading}
        onPress={onLoad}
        style={[
          loadMoreStyles.button,
          isLoading && loadMoreStyles.disabledbutton,
        ]}
        underlayColor={theme.primaryPressedButtonBackground}
        activeOpacity={1}
      >
        <LLText
          style={[
            loadMoreStyles.buttonText,
            isLoading && loadMoreStyles.disabledButtonText,
          ]}
        >
          {isLoading ? actionInProgressLabel : label}
        </LLText>
      </TouchableHighlight>
    </View>
  );
}

const getLoadMoreButtonStyles: LLComponentStyleFn<LLLoadActionButtonStyles> = ({
  theme,
}) =>
  StyleSheet.create({
    buttonContainer: {
      display: 'flex',
      justifyContent: 'center',
      width: '100%',
      alignItems: 'center',
    },
    button: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      width: 190,
      height: 40,
      borderRadius: 8,
      marginBottom: 16,
      backgroundColor: theme.primaryButtonBackground,
    },
    disabledbutton: {
      backgroundColor: theme.disabledButtonBackground,
      width: 210,
    },
    buttonText: {
      fontSize: 14,
      color: theme.text,
    },
    disabledButtonText: {
      color: theme.disabledButtonText,
    },
  });
