import React, { useCallback, useState } from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import {
  useDebounce,
  useStyles,
  useWidgetActions,
  useWidgetInteractedAnalytics,
  useWidgetOptions,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import {
  LLNumberPredictionWidgetOption,
  LLNumberPredictionWidgetOptionProps,
} from './LLNumberPredictionWidgetOption';

export type LLNumberPredictionWidgetBodyStyles = {
  bodyContainer: ViewStyle;
};

export type LLNumberPredictionWidgetBodyProps =
  ComponentStyleProp<LLNumberPredictionWidgetBodyStyles> & {
    widgetId: string;
    OptionComponent?: typeof LLNumberPredictionWidgetOption;
    OptionComponentStyles?: LLNumberPredictionWidgetOptionProps['styles'];
  };

export function LLNumberPredictionWidgetBody({
  widgetId,
  styles: stylesProp,
  OptionComponent = LLNumberPredictionWidgetOption,
}: LLNumberPredictionWidgetBodyProps) {
  const [numberOptions, setNumberOptions] = useState([]);
  const styles = useStyles({
    componentStylesFn: getNumberPredictionWidgetBodyStyles,
    stylesProp,
  });
  const widgetOptions = useWidgetOptions({ widgetId });
  const { updateNumberPredictionOptionAction } = useWidgetActions({ widgetId });
  const { trackWidgetInteractedAction } = useWidgetInteractedAnalytics({
    widgetId,
  });
  const debouncedTrackInteraction = useDebounce({
    callback: trackWidgetInteractedAction,
    timer: 500,
  });
  const onOptionInputHandler = useCallback(
    (numberOption, index) => {
      const newNumberOptions = [...numberOptions];
      newNumberOptions.splice(index, 1, numberOption);
      setNumberOptions(newNumberOptions);
      updateNumberPredictionOptionAction({
        widgetId,
        numberOption,
        optionIndex: index,
      });
      debouncedTrackInteraction({
        interactionItem: {
          value: numberOption,
          widgetOption: widgetOptions[index],
        },
      });
    },
    [numberOptions, widgetId, widgetOptions, debouncedTrackInteraction]
  );

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

  return (
    <View style={styles.bodyContainer}>
      {widgetOptions.map((option, index) => (
        <OptionComponent
          key={option.id}
          optionIndex={index}
          widgetId={widgetId}
          numberOption={numberOptions[index]}
          onOptionInputChange={onOptionInputHandler}
        />
      ))}
    </View>
  );
}

const getNumberPredictionWidgetBodyStyles: LLComponentStyleFn<
  LLNumberPredictionWidgetBodyStyles
> = ({ theme }) =>
  StyleSheet.create({
    bodyContainer: {
      display: 'flex',
      flexDirection: 'column',
      marginHorizontal: 16,
      marginBottom: 14,
    },
  });
