import React from 'react';
import { View, StyleSheet, ViewStyle, TextStyle } from 'react-native';
import { useStyles } from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import { IWidgetOptionItem } from '@livelike/javascript';
import { LLText } from '../LLText';

export type LLCheerMeterWidgetResultStyles = {
  resultContainer: ViewStyle;
  optionContainer: ViewStyle;
  leftOptionContainer: ViewStyle;
  rightOptionContainer: ViewStyle;
  optionText: TextStyle;
};

export type LLCheerMeterWidgetResultProps =
  ComponentStyleProp<LLCheerMeterWidgetResultStyles> & {
    widgetId: string;
    widgetOptions: IWidgetOptionItem[];
  };

export function LLCheerMeterWidgetResult({
  widgetOptions,
  styles: stylesProp,
}: LLCheerMeterWidgetResultProps) {
  const styles = useStyles({
    componentStylesFn: getCheerMeterWidgetResultStyles,
    stylesProp,
  });

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

  const totalCount = widgetOptions.reduce(
    (total, option) => total + option.vote_count,
    0
  );
  return (
    <View style={styles.resultContainer}>
      {widgetOptions.map((option, index) => (
        <View
          style={[
            { width: `${Math.round((option.vote_count / totalCount) * 100)}%` },
            !totalCount && { flex: 1 },
            styles.optionContainer,
            index === 0
              ? styles.leftOptionContainer
              : styles.rightOptionContainer,
          ]}
          key={option.id}
        >
          <LLText
            style={styles.optionText}
            numberOfLines={1}
            ellipsizeMode={'tail'}
          >
            {option.description}
          </LLText>
        </View>
      ))}
    </View>
  );
}

const getCheerMeterWidgetResultStyles: LLComponentStyleFn<
  LLCheerMeterWidgetResultStyles
> = ({ theme }) =>
  StyleSheet.create({
    resultContainer: {
      display: 'flex',
      flexDirection: 'row',
      marginTop: 4,
    },
    optionContainer: {
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      height: 30,
      paddingHorizontal: 6,
    },
    leftOptionContainer: {
      borderTopLeftRadius: 4,
      borderBottomLeftRadius: 4,
      backgroundColor: theme.correct,
    },
    rightOptionContainer: {
      borderTopRightRadius: 4,
      borderBottomRightRadius: 4,
      backgroundColor: theme.incorrect,
    },
    optionText: {
      color: theme.correctIncorrectText,
    },
  });
