import React, { useMemo, useState } from 'react';
import { Text, View } from 'react-native';
import { HelpCircle } from 'lucide-react-native';

import type { SuperagentToolRendererProps } from '../../types';
import { ToolWidgetRow } from '../primitives/ToolWidgetRow';
import { toolWidgetStyles } from '../primitives/toolWidgetStyles';
import { getSettledWidgetStatus, getWidgetStatus, parseToolArgs } from '../toolWidgetUtils';
import { answeredQuestionRows, persistedAnswers } from './answersUtils';
import { parseClarifyingQuestions } from './questionsUtils';

/**
 * The settled summary in the transcript, collapsed by default. Renders nothing
 * while the call is waiting — the question itself lives in the composer slot
 * (ClarifyingQuestionsCard), and web suppresses its duplicate the same way.
 */
export function ClarifyingQuestionsWidget({ isLastAssistantMessage, toolCall }: SuperagentToolRendererProps) {
  const args = useMemo(() => parseToolArgs(toolCall), [toolCall]);
  const questions = useMemo(() => parseClarifyingQuestions(args), [args]);
  const [expanded, setExpanded] = useState(false);

  if (getWidgetStatus(toolCall.status) === 'waiting') return null;

  const status = getSettledWidgetStatus(toolCall, isLastAssistantMessage);
  const rows = answeredQuestionRows(questions, persistedAnswers(toolCall.user_input));
  const showNumbers = rows.length > 1;
  const note =
    rows.length > 0
      ? `${rows.length} ${rows.length === 1 ? 'answer' : 'answers'}`
      : status === 'success' || status === 'stopped'
        ? 'skipped'
        : null;

  return (
    <ToolWidgetRow
      expanded={expanded}
      icon={HelpCircle}
      note={note}
      onToggle={rows.length > 0 ? () => setExpanded((current) => !current) : undefined}
      status={status}
      title={questions.length > 1 ? 'Asked clarifying questions' : 'Asked a clarifying question'}
    >
      <View style={toolWidgetStyles.answeredQuestionList}>
        {rows.map((row, index) => (
          <View key={index}>
            <Text style={toolWidgetStyles.answeredQuestionText}>
              {showNumbers ? `${index + 1}. ` : ''}{row.question}
            </Text>
            {row.answerText ? <Text style={toolWidgetStyles.optionLabel}>{row.answerText}</Text> : null}
          </View>
        ))}
      </View>
    </ToolWidgetRow>
  );
}
