import React from 'react';
import { StyleSheet, View, ViewStyle } from 'react-native';
import { useStyles, useWidgetOptions } from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import {
  LLCheerMeterWidgetOption,
  LLCheerMeterWidgetOptionProps,
} from './LLCheerMeterWidgetOption';
import {
  LLCheerMeterWidgetResult,
  LLCheerMeterWidgetResultProps,
} from './LLCheerMeterWidgetResult';
import {
  LLCheerMeterWidgetCheerCount,
  LLCheerMeterWidgetCheerCountProps,
} from './LLCheerMeterWidgetCheerCount';

export type LLCheerMeterWidgetBodyStyles = {
  bodyContainer: ViewStyle;
  optionContainer: ViewStyle;
};

export type LLCheerMeterWidgetBodyProps =
  ComponentStyleProp<LLCheerMeterWidgetBodyStyles> & {
    widgetId: string;
    ResultComponent?: typeof LLCheerMeterWidgetResult;
    ResultComponentStyles?: LLCheerMeterWidgetResultProps['styles'];
    OptionComponent?: typeof LLCheerMeterWidgetOption;
    OptionComponentStyles?: LLCheerMeterWidgetOptionProps['styles'];
    CheerCountComponent?: typeof LLCheerMeterWidgetCheerCount;
    CheerCountComponentStyles?: LLCheerMeterWidgetCheerCountProps['styles'];
  };

export function LLCheerMeterWidgetBody({
  widgetId,
  ResultComponent = LLCheerMeterWidgetResult,
  OptionComponent = LLCheerMeterWidgetOption,
  CheerCountComponent = LLCheerMeterWidgetCheerCount,
  ResultComponentStyles,
  OptionComponentStyles,
  CheerCountComponentStyles,
  styles: stylesProp,
}: LLCheerMeterWidgetBodyProps) {
  const styles = useStyles({
    componentStylesFn: getCheerMeterWidgetBodyStyles,
    stylesProp,
  });
  const widgetOptions = useWidgetOptions({ widgetId });

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

  const totalCheerCount = widgetOptions.reduce(
    (total, { vote_count }) => total + vote_count,
    0
  );

  return (
    <View style={styles.bodyContainer}>
      <ResultComponent
        widgetId={widgetId}
        widgetOptions={widgetOptions}
        styles={ResultComponentStyles}
      />
      <View style={styles.optionContainer}>
        {widgetOptions.map((option, index) => (
          <OptionComponent
            key={option.id}
            widgetId={widgetId}
            optionIndex={index}
            styles={OptionComponentStyles}
          />
        ))}
        <CheerCountComponent
          styles={CheerCountComponentStyles}
          totalCheerCount={totalCheerCount}
        />
      </View>
    </View>
  );
}

const getCheerMeterWidgetBodyStyles: LLComponentStyleFn<LLCheerMeterWidgetBodyStyles> =
  ({ theme }) =>
    StyleSheet.create({
      bodyContainer: {
        display: 'flex',
        flexDirection: 'column',
        marginHorizontal: 16,
        marginBottom: 8,
      },
      optionContainer: {
        display: 'flex',
        flexDirection: 'row',
        position: 'relative',
      },
    });
