import React from 'react';
import {
  Image,
  TouchableHighlight,
  StyleSheet,
  ViewStyle,
  ImageStyle,
} from 'react-native';
import {
  useWidgetOptions,
  useIsWidgetDisabled,
  useStyles,
  useTheme,
  useCheerMeterOnOptionPress,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';

export type LLCheerMeterWidgetOptionStyles = {
  optionContainer: ViewStyle;
  optionImage: ImageStyle;
};

export type LLCheerMeterWidgetOptionProps =
  ComponentStyleProp<LLCheerMeterWidgetOptionStyles> & {
    widgetId: string;
    optionIndex: number;
    /** Throttle time in milliseconds used to throttle option press interaction */
    throttleTime?: number;
  };

const THROTTLE_TIME = 3000;

export function LLCheerMeterWidgetOption({
  widgetId,
  optionIndex,
  throttleTime = THROTTLE_TIME,
  styles: stylesProp,
}: LLCheerMeterWidgetOptionProps) {
  const { theme } = useTheme();
  const styles = useStyles({
    componentStylesFn: getCheerMeterWidgetOptionStyles,
    stylesProp,
  });
  const widgetOptions = useWidgetOptions({ widgetId });
  const isWidgetDisabled = useIsWidgetDisabled({ widgetId });
  const widgetOption = widgetOptions?.[optionIndex];

  const onOptionPress = useCheerMeterOnOptionPress({
    widgetId,
    optionIndex,
    throttleTime,
  });

  if (!widgetOptions || !widgetOption || !widgetOption.image_url) {
    return undefined;
  }

  return (
    <TouchableHighlight
      onPress={onOptionPress}
      disabled={isWidgetDisabled}
      style={styles.optionContainer}
      activeOpacity={1}
      underlayColor={theme.widgetSelectedOption}
    >
      <Image
        source={{ uri: widgetOption.image_url }}
        style={styles.optionImage}
      ></Image>
    </TouchableHighlight>
  );
}

const getCheerMeterWidgetOptionStyles: LLComponentStyleFn<LLCheerMeterWidgetOptionStyles> =
  ({ theme }) =>
    StyleSheet.create({
      optionContainer: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 18,
        flex: 1,
      },
      optionImage: {
        width: 75,
        height: 60,
      },
    });
