import React, { useCallback, useState } from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import {
  useStyles,
  useWidgetActions,
  useWidgetInteractedAnalytics,
  useWidgetOptions,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import { LLWidgetVoteOption, LLWidgetVoteOptionProps } from '../LLWidgetOption';
import { IWidgetOptionItem } from '@livelike/javascript';

export type LLVoteWidgetBodyStyles = {
  bodyContainer: ViewStyle;
};

export type LLVoteWidgetBodyProps =
  ComponentStyleProp<LLVoteWidgetBodyStyles> & {
    widgetId: string;
    VoteOptionComponent?: typeof LLWidgetVoteOption;
    VoteOptionComponentStyles?: LLWidgetVoteOptionProps['OptionComponentStyles'];
  };

export function LLVoteWidgetBody({
  widgetId,
  styles: stylesProp,
  VoteOptionComponent = LLWidgetVoteOption,
  VoteOptionComponentStyles,
}: LLVoteWidgetBodyProps) {
  const [selectedOptionIndex, setSelectedOptionIndex] = useState(-1);
  const styles = useStyles({
    componentStylesFn: getVoteWidgetBodyStyles,
    stylesProp,
  });
  const widgetOptions = useWidgetOptions({ widgetId });
  const { updateSelectedOptionIndexAction } = useWidgetActions({ widgetId });
  const { trackWidgetInteractedAction } = useWidgetInteractedAnalytics({
    widgetId,
  });
  const onOptionHandler = useCallback(
    (selectedOptionIndex: number) => {
      setSelectedOptionIndex(selectedOptionIndex);
      updateSelectedOptionIndexAction({
        widgetId,
        selectedOptionIndex,
      });
      trackWidgetInteractedAction<IWidgetOptionItem>({
        interactionItem: widgetOptions[selectedOptionIndex],
      });
    },
    [widgetId, widgetOptions]
  );

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

  return (
    <View style={styles.bodyContainer}>
      {widgetOptions.map((option, index) => (
        <VoteOptionComponent
          key={option.id}
          optionIndex={index}
          widgetId={widgetId}
          selectedOptionIndex={selectedOptionIndex}
          onOptionChange={onOptionHandler}
          OptionComponentStyles={VoteOptionComponentStyles}
        />
      ))}
    </View>
  );
}

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