import React, { useCallback } from 'react';
import {
  LLWidgetSubmitButtonComponent,
  LLWidgetSubmitButtonProps,
} from '../LLWidgetFooter';
import {
  useIsEndWidgetUIPhase,
  useIsWidgetDisabled,
  useUserSliderMagnitude,
  useWidget,
  useWidgetActions,
  useWidgetSubmitAction,
} from '../../hooks';
import { roundTo } from '../../utils';

export type LLEmojiSliderWidgetSubmitButtonProps = LLWidgetSubmitButtonProps & {
  onPress?: (arg: { magnitude: number }) => void;
};

export function LLEmojiSliderWidgetSubmitButton({
  widgetId,
  styles,
  onPress,
}: LLEmojiSliderWidgetSubmitButtonProps) {
  const widget = useWidget({ widgetId });
  const magnitude = useUserSliderMagnitude({ widgetId });
  const widgetDisabled = useIsWidgetDisabled({ widgetId });
  const isEndWidgetUIPhase = useIsEndWidgetUIPhase({ widgetId });
  const { updateWidgetAverageMagnitude } = useWidgetActions({ widgetId });
  const { onInteractionSubmit } = useWidgetSubmitAction({ widgetId });

  const widgetEngagementCount = widget?.engagement_count;
  const widgetAverageMagnitude = widget?.average_magnitude;

  const onSubmit = useCallback(() => {
    onPress?.({ magnitude });
    const interactionItem = { magnitude: `${magnitude}` };
    onInteractionSubmit({ interactionItem }).then(() => {
      if (
        widgetAverageMagnitude === undefined ||
        widgetEngagementCount === undefined
      ) {
        return;
      }
      updateWidgetAverageMagnitude({
        widgetId,
        averageMagnitude: `${getUpdatedAverageMagnitude({
          userMagnitude: magnitude,
          widgetEngagementCount,
          widgetAverageMagnitude: parseFloat(widgetAverageMagnitude),
        })}`,
      });
    });
  }, [magnitude, widgetEngagementCount, widgetAverageMagnitude]);

  if (isEndWidgetUIPhase) {
    return undefined;
  }

  const disabled = widgetDisabled || magnitude === undefined;

  return (
    <LLWidgetSubmitButtonComponent
      disabled={disabled}
      onPress={onSubmit}
      styles={styles}
    />
  );
}

function getUpdatedAverageMagnitude({
  widgetAverageMagnitude,
  widgetEngagementCount,
  userMagnitude,
}): number {
  return roundTo(
    (widgetEngagementCount * widgetAverageMagnitude + userMagnitude) /
      (widgetEngagementCount + 1),
    3
  );
}
