import React from 'react';
import { Keyboard, ScrollView, Text, TextInput, View } from 'react-native';
import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from 'lucide-react-native';

import { conversationStyles } from '../../features/conversation/conversationStyles';
import { themedColor } from '../../theme';
import type { SuperagentToolCall, SuperagentToolRendererProps } from '../../types';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import {
  FallbackActionCard,
  SelectableOptionRow,
  TinyIconButton,
  WidgetActionButton,
} from '../widgets/interactiveWidgetParts';
import { changeCustomText, getRegularOptions, isOptionSelected, selectOption } from './questionsUtils';
import { useClarifyingQuestions } from './useClarifyingQuestions';

/**
 * The clarification form, rendered in place of the composer while a question is
 * pending (ConversationChat) as it is on web — so the question can't scroll away,
 * its free-text field gets the composer's keyboard handling, and the user can't
 * start a turn the backend has parked behind this answer.
 */
export function ClarifyingQuestionsCard({
  isCollapsed = false,
  isKeyboardVisible,
  maxHeight,
  onToggleCollapsed,
  submitToolCallInput,
  toolCall,
}: {
  /** Minimized to just the question — owned by the caller, which swaps in the composer. */
  isCollapsed?: boolean;
  /** Hides the description and nav row while typing "Something else", to free up space above the keyboard. */
  isKeyboardVisible?: boolean;
  /** Caps the whole card so it can't push its nav row off-screen; only the option list scrolls. */
  maxHeight?: number;
  onToggleCollapsed?: () => void;
  submitToolCallInput: SuperagentToolRendererProps['submitToolCallInput'];
  toolCall: SuperagentToolCall;
}) {
  const {
    canAct,
    collapseForKeyboard,
    currentIndex,
    customInputRef,
    error,
    goBack,
    goNext,
    isComplete,
    isFirst,
    isLast,
    isSubmitting,
    onCustomInputBlur,
    onCustomInputFocus,
    pressCustomRow,
    question,
    questions,
    scrollRef,
    skipCurrent,
    somethingElse,
    state,
    submitAnswers,
    updateCurrent,
  } = useClarifyingQuestions({ isKeyboardVisible, submitToolCallInput, toolCall });

  if (!question) {
    return (
      <FallbackActionCard
        buttonLabel="Continue"
        error={error}
        isSubmitting={isSubmitting}
        message="I couldn't put together the options for this question. Tap Continue and I'll proceed with a sensible default."
        onPress={canAct ? submitAnswers : undefined}
      />
    );
  }

  const options = getRegularOptions(question);

  return (
    <View style={[toolWidgetStyles.clarifyingCard, maxHeight ? { maxHeight } : null]}>
      <View style={toolWidgetStyles.interactiveHeader}>
        <Text style={toolWidgetStyles.interactiveTitle}>{question.question || 'A quick question'}</Text>
        <TinyIconButton
          accessibilityLabel={isCollapsed ? 'Expand question' : 'Minimize question'}
          disabled={false}
          icon={isCollapsed ? ChevronUp : ChevronDown}
          onPress={onToggleCollapsed ?? (() => {})}
        />
      </View>

      {isCollapsed ? null : (
      <ScrollView keyboardShouldPersistTaps="handled" ref={scrollRef} style={toolWidgetStyles.optionScroll}>
        <View style={toolWidgetStyles.optionList}>
          {question.description ? (
            <Text style={toolWidgetStyles.clarifyingQuestionDescription}>{question.description}</Text>
          ) : null}
          {options.map((option) => (
            <SelectableOptionRow
              disabled={isSubmitting}
              key={option.label}
              label={option.label}
              multi={question.multi_select}
              onPress={() => {
                // keyboardShouldPersistTaps="handled" lets this row's press through without
                // dismissing the "Something else" input first — do it explicitly.
                Keyboard.dismiss();
                updateCurrent(selectOption(question, state, option.label));
              }}
              selected={isOptionSelected(question, state, option.label)}
              subtitle={option.description ?? option.subtitle ?? null}
            />
          ))}

          <SelectableOptionRow
            centered
            disabled={isSubmitting}
            multi={question.multi_select}
            onPress={pressCustomRow}
            selected={somethingElse}
          >
            <TextInput
              editable={!isSubmitting}
              onBlur={onCustomInputBlur}
              onChangeText={(text) => updateCurrent(changeCustomText(question, state, text))}
              onFocus={onCustomInputFocus}
              placeholder="Write your own answer here"
              ref={customInputRef}
              placeholderTextColor={themedColor('#6F6F76')}
              style={[conversationStyles.toolApprovalInput, toolWidgetStyles.clarifyingCustomInput]}
              value={state.customText}
            />
          </SelectableOptionRow>
        </View>
      </ScrollView>
      )}

      {collapseForKeyboard || isCollapsed ? null : (
        <View style={toolWidgetStyles.wizardNavRow}>
          <View style={toolWidgetStyles.wizardNavGroup}>
            {questions.length > 1 ? (
              <>
                <TinyIconButton
                  accessibilityLabel="Previous question"
                  disabled={isSubmitting || isFirst}
                  icon={ChevronLeft}
                  onPress={goBack}
                />
                <Text style={toolWidgetStyles.interactiveCounter}>{currentIndex + 1}/{questions.length}</Text>
                <TinyIconButton
                  accessibilityLabel="Next question"
                  disabled={isSubmitting || isLast}
                  icon={ChevronRight}
                  // Advancing past an unanswered question is a skip, so the answer
                  // isn't submitted (see skipCurrent).
                  onPress={isComplete ? goNext : skipCurrent}
                />
              </>
            ) : null}
          </View>
          <View style={toolWidgetStyles.wizardNavGroup}>
            <WidgetActionButton
              disabled={isSubmitting || (isLast && !canAct)}
              isSubmitting={false}
              label="Skip"
              onPress={skipCurrent}
              small
            />
            <WidgetActionButton
              disabled={isSubmitting || !isComplete || (isLast && !canAct)}
              isSubmitting={isLast && isSubmitting}
              label={isLast ? 'Send' : 'Next'}
              onPress={isLast ? submitAnswers : goNext}
              primary
              small
            />
          </View>
        </View>
      )}

      {error ? <Text style={conversationStyles.toolApprovalError}>{error}</Text> : null}
    </View>
  );
}
