import React, { useState, useEffect } from 'react';
import FeedbackWeighting from './FeedbackWeighting';
const PromptDisplay = () => {
const [prompts, setPrompts] = useState([]); // Changed to array to handle multiple prompts
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [selectedIndex, setSelectedIndex] = useState(null);
const [viewMode, setViewMode] = useState('history'); // 'history' or 'drawn'
const [poolStats, setPoolStats] = useState({
total: 0,
target: 20,
sessions: 0,
needsRefill: true
});
const [showFeedbackWeighting, setShowFeedbackWeighting] = useState(false);
const [fillPoolLoading, setFillPoolLoading] = useState(false);
const [drawButtonDisabled, setDrawButtonDisabled] = useState(false);
useEffect(() => {
fetchMostRecentPrompt();
fetchPoolStats();
}, []);
const fetchMostRecentPrompt = async () => {
setLoading(true);
setError(null);
setDrawButtonDisabled(false); // Re-enable draw button when returning to history view
try {
// Try to fetch from actual API first
const response = await fetch('/api/v1/prompts/history');
if (response.ok) {
const data = await response.json();
// API returns array directly, not object with 'prompts' key
if (Array.isArray(data) && data.length > 0) {
// Get the most recent prompt (first in array, position 0)
// Show only one prompt from history
setPrompts([{ text: data[0].text, position: data[0].position }]);
setViewMode('history');
} else {
// No history yet, show placeholder
setPrompts([{ text: "No recent prompts in history. Draw some prompts to get started!", position: 0 }]);
}
} else {
// API not available, use mock data
setPrompts([{ text: "Write about a time when you felt completely at peace with yourself and the world around you. What were the circumstances that led to this feeling, and how did it change your perspective on life?", position: 0 }]);
}
} catch (err) {
console.error('Error fetching prompt:', err);
// Fallback to mock data
setPrompts([{ text: "Imagine you could have a conversation with your future self 10 years from now. What questions would you ask, and what advice do you think your future self would give you?", position: 0 }]);
} finally {
setLoading(false);
}
};
const handleDrawPrompts = async () => {
setDrawButtonDisabled(true); // Disable the button when clicked
setLoading(true);
setError(null);
setSelectedIndex(null);
try {
// Draw 3 prompts from pool (Task 4)
const response = await fetch('/api/v1/prompts/draw?count=3');
if (response.ok) {
const data = await response.json();
// Draw API returns object with 'prompts' array
if (data.prompts && data.prompts.length > 0) {
// Show all drawn prompts
const drawnPrompts = data.prompts.map((text, index) => ({
text,
position: index
}));
setPrompts(drawnPrompts);
setViewMode('drawn');
} else {
setError('No prompts available in pool. Please fill the pool first.');
}
} else {
setError('Failed to draw prompts. Please try again.');
}
} catch (err) {
setError('Failed to draw prompts. Please try again.');
} finally {
setLoading(false);
}
};
const handleAddToHistory = async (index) => {
if (index < 0 || index >= prompts.length) {
setError('Invalid prompt index');
return;
}
try {
const promptText = prompts[index].text;
// Send the prompt to the API to add to history
const response = await fetch('/api/v1/prompts/select', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt_text: promptText }),
});
if (response.ok) {
const data = await response.json();
// Mark as selected and show success
setSelectedIndex(index);
// Refresh the page to show the updated history and pool stats
// The default view shows the most recent prompt from history (position 0)
fetchMostRecentPrompt();
fetchPoolStats();
setDrawButtonDisabled(false); // Re-enable draw button after selection
} else {
const errorData = await response.json();
setError(`Failed to add prompt to history: ${errorData.detail || 'Unknown error'}`);
}
} catch (err) {
setError('Failed to add prompt to history');
}
};
const fetchPoolStats = async () => {
try {
const response = await fetch('/api/v1/prompts/stats');
if (response.ok) {
const data = await response.json();
setPoolStats({
total: data.total_prompts || 0,
target: data.target_pool_size || 20,
sessions: data.available_sessions || 0,
needsRefill: data.needs_refill || true
});
}
} catch (err) {
console.error('Error fetching pool stats:', err);
}
};
const handleFillPool = async () => {
// Start pool refill immediately (uses active words 6-11)
setFillPoolLoading(true);
setError(null);
try {
const response = await fetch('/api/v1/prompts/fill-pool', { method: 'POST' });
if (response.ok) {
const data = await response.json();
console.log('Pool refill started:', data);
// Pool refill started successfully, now show feedback weighting UI
setShowFeedbackWeighting(true);
} else {
const errorData = await response.json();
throw new Error(errorData.detail || `Failed to start pool refill: ${response.status}`);
}
} catch (err) {
console.error('Error starting pool refill:', err);
setError(`Failed to start pool refill: ${err.message}`);
} finally {
setFillPoolLoading(false);
}
};
const handleFeedbackComplete = async (feedbackData) => {
// After feedback is submitted, refresh the UI
setShowFeedbackWeighting(false);
// Refresh the prompt and pool stats
fetchMostRecentPrompt();
fetchPoolStats();
};
const handleFeedbackCancel = () => {
setShowFeedbackWeighting(false);
};
if (showFeedbackWeighting) {
return (
{promptObj.text}
{viewMode === 'history' ? 'Most Recent Prompt from History' : `${prompts.length} Drawn Prompts`}: {viewMode === 'history' ? ' This is the latest prompt from your history. Using it helps the AI learn your preferences.' : ' Select a prompt to use for journaling. The AI will learn from your selection.'}
Tip: The prompt pool needs regular refilling. Check the stats panel to see how full it is.
There are no prompts in history or pool. Get started by filling the pool.