import React, { useCallback } from 'react';
import {
  LLWidgetSubmitButtonComponent,
  LLWidgetSubmitButtonProps,
} from '../LLWidgetFooter';
import {
  useIsEndWidgetUIPhase,
  useIsWidgetDisabled,
  useWidgetChoices,
  useWidgetSelectedOptionIndex,
  useWidgetSubmitAction,
} from '../../hooks';

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

export function LLQuizWidgetSubmitButton({
  widgetId,
  styles,
  onPress,
}: LLQuizWidgetSubmitButtonProps) {
  const { onInteractionSubmit } = useWidgetSubmitAction({ widgetId });
  const widgetChoices = useWidgetChoices({ widgetId });
  const selectedOptionIndex = useWidgetSelectedOptionIndex({ widgetId });
  const widgetDisabled = useIsWidgetDisabled({ widgetId });
  const isEndWidgetUIPhase = useIsEndWidgetUIPhase({ widgetId });
  const onSubmit = useCallback(() => {
    if (isInvalidSelectedOptionIndex(selectedOptionIndex)) {
      return;
    }
    onPress?.({ selectedOptionIndex });
    const interactionItem = widgetChoices[selectedOptionIndex];
    onInteractionSubmit({ interactionItem });
  }, [widgetChoices, selectedOptionIndex]);

  if (isEndWidgetUIPhase) {
    return undefined;
  }

  return (
    <LLWidgetSubmitButtonComponent
      disabled={
        widgetDisabled || isInvalidSelectedOptionIndex(selectedOptionIndex)
      }
      onPress={onSubmit}
      styles={styles}
    />
  );
}

function isInvalidSelectedOptionIndex(selectedOptionIndex?: number) {
  return selectedOptionIndex === undefined || selectedOptionIndex < 0;
}
