import React, { useCallback, useState } from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import {
  useStyles,
  useWidgetActions,
  useWidgetChoices,
  useWidgetInteractedAnalytics,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import {
  LLWidgetChoiceOption,
  LLWidgetChoiceOptionProps,
} from '../LLWidgetOption';
import { IWidgetChoiceItem } from '@livelike/javascript';

export type LLQuizWidgetBodyStyles = {
  bodyContainer: ViewStyle;
};

export type LLQuizWidgetBodyProps =
  ComponentStyleProp<LLQuizWidgetBodyStyles> & {
    widgetId: string;
    ChoiceOptionComponent?: typeof LLWidgetChoiceOption;
    ChoiceOptionComponentStyles?: LLWidgetChoiceOptionProps['OptionComponentStyles'];
  };

export function LLQuizWidgetBody({
  widgetId,
  styles: stylesProp,
  ChoiceOptionComponent = LLWidgetChoiceOption,
  ChoiceOptionComponentStyles,
}: LLQuizWidgetBodyProps) {
  const [selectedOptionIndex, setSelectedOptionIndex] = useState(-1);
  const styles = useStyles({
    componentStylesFn: getQuizWidgetBodyStyles,
    stylesProp,
  });
  const widgetChoices = useWidgetChoices({ widgetId });
  const { updateSelectedOptionIndexAction } = useWidgetActions({ widgetId });
  const { trackWidgetInteractedAction } = useWidgetInteractedAnalytics({
    widgetId,
  });
  const onOptionHandler = useCallback(
    (selectedOptionIndex: number) => {
      setSelectedOptionIndex(selectedOptionIndex);
      updateSelectedOptionIndexAction({
        widgetId,
        selectedOptionIndex,
      });
      trackWidgetInteractedAction<IWidgetChoiceItem>({
        interactionItem: widgetChoices[selectedOptionIndex],
      });
    },
    [widgetId, widgetChoices]
  );

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

  return (
    <View style={styles.bodyContainer}>
      {widgetChoices?.map((choice, index) => (
        <ChoiceOptionComponent
          key={choice.id}
          optionIndex={index}
          widgetId={widgetId}
          selectedOptionIndex={selectedOptionIndex}
          onOptionChange={onOptionHandler}
          OptionComponentStyles={ChoiceOptionComponentStyles}
        />
      ))}
    </View>
  );
}

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