import React from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import {
  useLoadWidgetRewardsEffect,
  useStyles,
  useWidgetRewards,
  useWidgetRewardsEffect,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import { LLWidgetReward, LLWidgetRewardProps } from './LLWidgetReward';

export type LLWidgetRewardsStyles = {
  container: ViewStyle;
};

export type LLWidgetRewardsProps = ComponentStyleProp<LLWidgetRewardsStyles> & {
  widgetId: string;
  RewardComponent?: typeof LLWidgetReward;
  RewardComponentStyles?: LLWidgetRewardProps['styles'];
};

export function LLWidgetRewards({
  widgetId,
  RewardComponent = LLWidgetReward,
  RewardComponentStyles,
  styles: stylesProp,
}: LLWidgetRewardsProps) {
  const rewardStyles = useStyles({
    componentStylesFn: getWidgetRewardsStyles,
    stylesProp,
  });
  const widgetRewards = useWidgetRewards({ widgetId });
  const { slideInOutStyles } = useWidgetRewardsEffect({
    widgetId,
  });
  useLoadWidgetRewardsEffect({ widgetId });

  if (!widgetRewards?.length) {
    return undefined;
  }

  return (
    <View style={rewardStyles.container}>
      {widgetRewards?.map((widgetReward, index) => (
        <RewardComponent
          key={widgetReward.reward_item_id}
          multipleReward={widgetRewards.length > 1}
          widgetReward={widgetReward}
          slideInOutStyle={slideInOutStyles[index]}
          widgetId={widgetId}
          styles={RewardComponentStyles}
        />
      ))}
    </View>
  );
}

const getWidgetRewardsStyles: LLComponentStyleFn<LLWidgetRewardsStyles> = ({
  theme,
}) =>
  StyleSheet.create({
    container: {
      display: 'flex',
      flex: 1,
      alignSelf: 'center',
      height: 22,
      overflow: 'hidden',
      flexDirection: 'column',
      marginBottom: 16,
      marginLeft: 16,
    },
  });
