import React, { useCallback, useMemo } from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';

import {
  useIsWidgetDisabled,
  useStyles,
  useWidget,
  useWidgetActions,
  useWidgetInteractedAnalytics,
  useWidgetInteractions,
  useWidgetOptions,
} from '../../hooks';
import { roundTo } from '../../utils';
import { LLEmojiSlider, LLEmojiSliderProps } from './LLEmojiSlider';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';

export type LLEmojiSliderWidgetBodyStyles = {
  bodyContainer: ViewStyle;
};

export type LLEmojiSliderWidgetBodyProps =
  ComponentStyleProp<LLEmojiSliderWidgetBodyStyles> & {
    widgetId: string;
    SliderComponent?: typeof LLEmojiSlider;
    SliderComponentStyles?: LLEmojiSliderProps['styles'];
  };

export function LLEmojiSliderWidgetBody({
  widgetId,
  styles: stylesProp,
  SliderComponent = LLEmojiSlider,
  SliderComponentStyles,
}: LLEmojiSliderWidgetBodyProps) {
  const styles = useStyles({
    componentStylesFn: getEmojiSliderWidgetBodyStyles,
    stylesProp,
  });
  const widget = useWidget({ widgetId });
  const widgetOptions = useWidgetOptions({ widgetId });
  const isWidgetDisabled = useIsWidgetDisabled({ widgetId });
  const widgetInteractions = useWidgetInteractions({ widgetId });
  const widgetInteraction = widgetInteractions?.[0];
  const { updateEmojiSliderMagnitudeAction } = useWidgetActions({ widgetId });
  const { trackWidgetInteractedAction } = useWidgetInteractedAnalytics({
    widgetId,
  });

  const thumbImages = useMemo(
    () =>
      widgetOptions?.map(({ image_url }, index) => {
        return {
          imageUrl: image_url,
          min: roundTo(index / widgetOptions.length, 3),
        };
      }),
    [widgetOptions]
  );

  const onSlidingCompleteHandler = useCallback(
    (magnitude) => {
      const userMagnitude = roundTo(magnitude, 3);
      updateEmojiSliderMagnitudeAction({
        widgetId,
        magnitude: userMagnitude,
      });
      trackWidgetInteractedAction<number>({ interactionItem: userMagnitude });
    },
    [widgetId]
  );

  if (!widget || !widgetOptions || !widgetOptions.length) {
    return undefined;
  }

  const sliderValue =
    widgetInteraction?.magnitude ?? parseFloat(widget.initial_magnitude);

  const average = widgetInteraction
    ? parseFloat(widget.average_magnitude)
    : undefined;

  return (
    <View style={styles.bodyContainer}>
      <SliderComponent
        onSlidingComplete={onSlidingCompleteHandler}
        value={sliderValue}
        initialValue={sliderValue}
        disabled={isWidgetDisabled}
        thumbImages={thumbImages}
        average={average}
        styles={SliderComponentStyles}
      />
    </View>
  );
}

const getEmojiSliderWidgetBodyStyles: LLComponentStyleFn<
  LLEmojiSliderWidgetBodyStyles
> = ({ theme }) =>
  StyleSheet.create({
    bodyContainer: {
      display: 'flex',
      flexDirection: 'column',
      marginBottom: 16,
      paddingHorizontal: 16,
    },
  });
