import React, { useCallback, useState } from 'react';
import { StyleSheet, View, ViewStyle, TextStyle } from 'react-native';
import {
  useDebounce,
  useIsWidgetDisabled,
  useStyles,
  useWidget,
  useWidgetActions,
  useWidgetInteractedAnalytics,
  useWidgetInteractions,
} from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import {
  LLTextAskWidgetInput,
  LLTextAskWidgetInputProps,
} from './LLTextAskWidgetInput';
import { LLText } from '../LLText';

export type LLTextAskWidgetBodyStyles = {
  container: ViewStyle;
  askText: TextStyle;
};

export type LLTextAskWidgetBodyProps =
  ComponentStyleProp<LLTextAskWidgetBodyStyles> & {
    widgetId: string;
    InputComponent?: typeof LLTextAskWidgetInput;
    InputComponentStyles?: LLTextAskWidgetInputProps['styles'];
  };

export function LLTextAskWidgetBody({
  widgetId,
  InputComponent = LLTextAskWidgetInput,
  InputComponentStyles,
  styles: stylesProp,
}: LLTextAskWidgetBodyProps) {
  const styles = useStyles({
    componentStylesFn: getTextAskWidgetBodyStyles,
    stylesProp,
  });
  const widget = useWidget({ widgetId });
  const [inputText, setInputText] = useState(undefined);
  const widgetInteractions = useWidgetInteractions({ widgetId });
  const isWidgetDisabled = useIsWidgetDisabled({ widgetId });
  const { updateTextAskInputTextAction } = useWidgetActions({ widgetId });
  const { trackWidgetInteractedAction } = useWidgetInteractedAnalytics({
    widgetId,
  });

  const debouncedTrackInteraction = useDebounce({
    callback: trackWidgetInteractedAction,
    timer: 1000,
  });

  const onTextAskInputHandler = useCallback(
    (updatedText: string) => {
      setInputText(updatedText);
      updateTextAskInputTextAction({ widgetId, inputText: updatedText });

      debouncedTrackInteraction({ interactionItem: { text: updatedText } });
    },
    [updateTextAskInputTextAction, widgetId, debouncedTrackInteraction]
  );

  if (!widget) {
    return undefined;
  }

  const { prompt } = widget;
  const widgetInteraction = widgetInteractions?.[0];
  const inputDisabled = isWidgetDisabled || !!widgetInteraction;
  return (
    <View style={styles.container}>
      <LLText style={styles.askText}>{prompt}</LLText>
      <InputComponent
        value={widgetInteraction?.text ?? inputText}
        disabled={inputDisabled}
        onChange={onTextAskInputHandler}
        styles={InputComponentStyles}
      />
    </View>
  );
}

const getTextAskWidgetBodyStyles: LLComponentStyleFn<
  LLTextAskWidgetBodyStyles
> = ({ theme }) =>
  StyleSheet.create({
    container: {
      display: 'flex',
      flexDirection: 'column',
      marginBottom: 16,
      paddingHorizontal: 16,
    },
    askText: {
      color: theme.text,
      fontSize: 12,
      marginBottom: 16,
    },
  });
