import React, { useEffect, useState, useCallback } from "react"; import { View, Text, TouchableOpacity, StyleSheet, ActivityIndicator, } from "react-native"; import type { OperoChatStyles, OperoSampleQuestionsProps, OperoChatError, } from "../types"; import { log } from "../utils/helpers"; interface QuestionState { questions: string[]; loading: boolean; error: string | null; } export const OperoSampleQuestions: React.FC = ({ apiKey, apiEndpoint, userEmail, userRole, filters, questionCount = 3, onQuestionPress, onError, customStyles, }) => { const [state, setState] = useState({ questions: [], loading: true, error: null, }); const fetchQuestions = useCallback(async () => { try { setState((prev) => ({ ...prev, loading: true, error: null })); const headers: Record = { "Content-Type": "application/json", "X-API-Key": apiKey, ...(userEmail && { "X-User-Email": userEmail }), ...(userRole && { "X-User-Role": userRole }), }; const response = await fetch(`${apiEndpoint}/generate-questions`, { method: "POST", headers, body: JSON.stringify({ question_count: questionCount, ...(filters && { filters }), }), }); if (!response.ok) { const errorText = await response.text(); let errorMessage = "Failed to load questions"; let errorType: OperoChatError["type"] = "api"; try { const errorData = JSON.parse(errorText); if (errorData.detail) { errorMessage = errorData.detail; } // Determine error type based on status code if (response.status === 401 || response.status === 403) { errorType = "auth"; } else if (response.status === 422) { errorType = "validation"; } } catch (parseError) { // If we can't parse the error, use the raw text errorMessage = errorText || errorMessage; } // Propagate error to main error system if (onError) { onError({ type: errorType, message: errorMessage, details: { status: response.status, statusText: response.statusText, }, }); } throw new Error(errorMessage); } const data = await response.json(); if (data.success && Array.isArray(data.questions)) { setState({ questions: data.questions, loading: false, error: null, }); log(`Loaded ${data.questions.length} sample questions`, "info"); } else { throw new Error("Invalid response format from questions API"); } } catch (error) { const errorMessage = error instanceof Error ? error.message : "Failed to load questions"; setState({ questions: [], loading: false, error: errorMessage, }); log(`Failed to load sample questions: ${errorMessage}`, "error"); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [apiKey, userEmail, apiEndpoint, filters, questionCount]); useEffect(() => { fetchQuestions(); }, [fetchQuestions]); const handleQuestionPress = (question: string) => { onQuestionPress(question); }; // Don't render anything if there's an error or no questions if (state.error || (!state.loading && state.questions.length === 0)) { return null; } const styles = createStyles(customStyles); return ( Suggested questions {state.loading ? ( Loading suggestions... ) : ( {state.questions.map((question, index) => ( handleQuestionPress(question)} activeOpacity={0.7} > {question} ))} )} ); }; const createStyles = (customStyles?: OperoChatStyles) => StyleSheet.create({ container: { padding: 20, paddingTop: 24, backgroundColor: customStyles?.backgroundColor || "#ffffff", }, headerContainer: { marginBottom: 16, }, title: { fontSize: 20, fontWeight: "600", color: customStyles?.textColor || "#1f2937", textAlign: "center", }, loadingContainer: { flexDirection: "row", alignItems: "center", justifyContent: "center", paddingVertical: 32, }, loadingText: { fontSize: 14, color: customStyles?.textColor || "#6b7280", marginLeft: 8, }, questionsContainer: { gap: 12, }, questionButton: { backgroundColor: customStyles?.backgroundColor || "#ffffff", paddingHorizontal: 20, paddingVertical: 16, borderRadius: 12, borderWidth: 1, borderColor: customStyles?.primaryColor ? `${customStyles.primaryColor}30` : "#e5e7eb", shadowColor: "#000", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.08, shadowRadius: 4, elevation: 2, }, questionText: { fontSize: 15, color: customStyles?.textColor || "#374151", textAlign: "left", lineHeight: 22, fontWeight: "500", }, });