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

export type LLTextAskWidgetSubmitButtonProps = LLWidgetSubmitButtonProps & {
  onPress?: (arg: { inputText: string }) => void;
};

export function LLTextAskWidgetSubmitButton({
  widgetId,
  styles,
  onPress,
}: LLTextAskWidgetSubmitButtonProps) {
  const { onInteractionSubmit } = useWidgetSubmitAction({ widgetId });
  const inputText = useTextAskInputText({ widgetId });
  const widgetDisabled = useIsWidgetDisabled({ widgetId });
  const isEndWidgetUIPhase = useIsEndWidgetUIPhase({ widgetId });

  const onSubmit = useCallback(() => {
    onPress?.({ inputText });
    const interactionItem = { text: inputText };
    onInteractionSubmit({ interactionItem }).then(() => {
      if (!inputText) {
        return;
      }
    });
  }, [inputText]);

  if (isEndWidgetUIPhase) {
    return undefined;
  }

  const disabled = widgetDisabled || !inputText;

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