import React, { useState } from 'react'; import { supabase } from '../firebaseClient'; import type { ProblemItem, ProblemSolution } from '../types/reviewTypes'; interface CreateProblemFormProps { onClose: () => void; onSuccess: () => void; initialProblem?: ProblemItem | null; mode?: 'create' | 'edit'; } interface ExampleItem { input: string; output: string; explanation?: string; } const COMMON_PATTERNS = [ 'Arrays & Hashing', 'Two Pointers', 'Sliding Window', 'Stack', 'Binary Search', 'Linked List', 'Trees', 'Tries', 'Heap / Priority Queue', 'Backtracking', 'Graphs', 'Advanced Graphs', '1-D Dynamic Programming', '2-D Dynamic Programming', 'Greedy', 'Intervals', 'Math & Geometry', 'Bit Manipulation' ]; function generateSolutionId(): string { if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') { return `sol-${crypto.randomUUID()}`; } return `sol-${Date.now()}`; } export default function CreateProblemForm({ onClose, onSuccess, initialProblem, mode = initialProblem ? 'edit' : 'create' }: CreateProblemFormProps) { const isEditMode = mode === 'edit' || Boolean(initialProblem); // Navigation / Tab const [activeTab, setActiveTab] = useState<'form' | 'preview'>('form'); // URL / Quick import const [urlQuery, setUrlQuery] = useState(''); const [fetchingUrl, setFetchingUrl] = useState(false); // Form Fields const [newFileName, setNewFileName] = useState(() => { if (initialProblem?.name) return initialProblem.name; try { const draft = localStorage.getItem('algospaced_prefill_draft'); if (draft) return JSON.parse(draft).name || ''; } catch { /* ignore invalid json */ } return ''; }); const [newFileProblemNumber, setNewFileProblemNumber] = useState(() => { if (initialProblem?.problem_number !== undefined && initialProblem?.problem_number !== null) { return initialProblem.problem_number; } return ''; }); const [newFilePattern, setNewFilePattern] = useState(() => { if (initialProblem?.pattern) return initialProblem.pattern; try { const draft = localStorage.getItem('algospaced_prefill_draft'); if (draft) return JSON.parse(draft).pattern || ''; } catch { /* ignore invalid json */ } return 'Arrays & Hashing'; }); const [newFileDifficulty, setNewFileDifficulty] = useState<'Easy' | 'Medium' | 'Hard'>(() => { if (initialProblem?.difficulty === 'Easy' || initialProblem?.difficulty === 'Medium' || initialProblem?.difficulty === 'Hard') { return initialProblem.difficulty; } return 'Medium'; }); const [newFileOptimalTime, setNewFileOptimalTime] = useState(() => initialProblem?.optimal_time || 'O(N)'); const [newFileOptimalSpace, setNewFileOptimalSpace] = useState(() => initialProblem?.optimal_space || 'O(1)'); const [newFileDescription, setNewFileDescription] = useState(() => initialProblem?.description || ''); const [newFileExamples, setNewFileExamples] = useState(() => { if (initialProblem?.examples && Array.isArray(initialProblem.examples) && initialProblem.examples.length > 0) { return initialProblem.examples.map((ex: { input?: unknown; output?: unknown; explanation?: string } | string) => typeof ex === 'string' ? { input: ex, output: '', explanation: '' } : { input: String(ex?.input ?? ''), output: String(ex?.output ?? ''), explanation: ex?.explanation || '' } ); } return [{ input: '', output: '', explanation: '' }]; }); const [newFileConstraints, setNewFileConstraints] = useState(() => { if (initialProblem?.constraints) { if (Array.isArray(initialProblem.constraints)) return initialProblem.constraints.join('\n'); return String(initialProblem.constraints); } return ''; }); const [newFileHowToSolve, setNewFileHowToSolve] = useState( () => (initialProblem as { how_to_solve?: string } | undefined)?.how_to_solve || '' ); const [newFileCode, setNewFileCode] = useState(() => { if (initialProblem?.reference_code) return initialProblem.reference_code; try { const draft = localStorage.getItem('algospaced_prefill_draft'); if (draft) return JSON.parse(draft).code || ''; } catch { /* ignore invalid json */ } return ''; }); // Multi-solution state const [solutions, setSolutions] = useState(() => { if (initialProblem?.solutions && Array.isArray(initialProblem.solutions) && initialProblem.solutions.length > 0) { return initialProblem.solutions.map((s, idx) => ({ id: s.id || `sol-${idx + 1}`, name: s.name || `Method ${idx + 1}`, pattern: s.pattern || initialProblem.pattern || 'Arrays & Hashing', time_complexity: s.time_complexity || initialProblem.optimal_time || 'O(N)', space_complexity: s.space_complexity || initialProblem.optimal_space || 'O(1)', code: s.code || '', explanation: s.explanation || '', is_optimal: s.is_optimal ?? (idx === 0) })); } let initCode = initialProblem?.reference_code || ''; let initPattern = initialProblem?.pattern || 'Arrays & Hashing'; try { const draft = localStorage.getItem('algospaced_prefill_draft'); if (draft) { const parsed = JSON.parse(draft); if (parsed.code && !initCode) initCode = parsed.code; if (parsed.pattern && !initPattern) initPattern = parsed.pattern; } } catch { /* ignore invalid json */ } return [ { id: 'sol-1', name: 'Optimal Method', pattern: initPattern, time_complexity: initialProblem?.optimal_time || 'O(N)', space_complexity: initialProblem?.optimal_space || 'O(1)', code: initCode, explanation: (initialProblem as { how_to_solve?: string } | undefined)?.how_to_solve || '', is_optimal: true } ]; }); const [activeSolutionIdx, setActiveSolutionIdx] = useState(0); const activeSolution = solutions[activeSolutionIdx] || solutions[0] || { id: 'sol-1', name: 'Method 1', pattern: 'Arrays & Hashing', time_complexity: 'O(N)', space_complexity: 'O(1)', code: '', explanation: '', is_optimal: true }; const updateActiveSolution = (updates: Partial) => { setSolutions(prev => { const next = [...prev]; const targetIdx = activeSolutionIdx < next.length ? activeSolutionIdx : 0; next[targetIdx] = { ...next[targetIdx], ...updates }; if (updates.is_optimal) { next.forEach((s, idx) => { if (idx !== targetIdx) s.is_optimal = false; }); if (next[targetIdx].time_complexity) setNewFileOptimalTime(next[targetIdx].time_complexity); if (next[targetIdx].space_complexity) setNewFileOptimalSpace(next[targetIdx].space_complexity); if (next[targetIdx].pattern) setNewFilePattern(next[targetIdx].pattern); } return next; }); }; const addSolution = () => { const nextNum = solutions.length + 1; const newSol: ProblemSolution = { id: generateSolutionId(), name: `Method ${nextNum}`, pattern: newFilePattern || 'Arrays & Hashing', time_complexity: 'O(N)', space_complexity: 'O(1)', code: '', explanation: '', is_optimal: solutions.length === 0 }; setSolutions(prev => [...prev, newSol]); setActiveSolutionIdx(solutions.length); }; const removeSolution = (idxToRemove: number) => { if (solutions.length <= 1) return; setSolutions(prev => { const next = prev.filter((_, i) => i !== idxToRemove); if (!next.some(s => s.is_optimal)) { next[0].is_optimal = true; } return next; }); if (activeSolutionIdx >= solutions.length - 1) { setActiveSolutionIdx(Math.max(0, solutions.length - 2)); } }; // Dual-write & Status const [syncToGDoc, setSyncToGDoc] = useState(true); const [createError, setCreateError] = useState(''); const [createSuccess, setCreateSuccess] = useState(''); const [creating, setCreating] = useState(false); // AI loading flags const [loadingIntuition, setLoadingIntuition] = useState(false); const [loadingComments, setLoadingComments] = useState(false); const [prefilling, setPrefilling] = useState(false); React.useEffect(() => { if (!isEditMode) { localStorage.removeItem('algospaced_prefill_draft'); } }, [isEditMode]); const getHeaders = async () => { const { data: { session } } = await supabase.auth.getSession(); const token = session ? session.access_token : 'sandbox'; const customKey = localStorage.getItem('algospaced_custom_api_key') || localStorage.getItem('sandbox_gemini_api_key') || ''; const customProvider = localStorage.getItem('algospaced_custom_ai_provider') || 'default'; const headers: Record = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }; if (customProvider && customProvider !== 'default' && customKey && customKey.trim()) { headers['x-custom-api-key'] = customKey.trim(); headers['x-gemini-api-key'] = customKey.trim(); headers['x-ai-provider'] = customProvider; } return headers; }; // 1. Fetch LeetCode Details via URL or Title const handleFetchLeetCode = async () => { if (!urlQuery.trim()) return; setFetchingUrl(true); setCreateError(''); try { const headers = await getHeaders(); const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/fetch-leetcode`, { method: 'POST', headers, body: JSON.stringify({ query: urlQuery.trim() }) }); if (res.ok) { const data = await res.json(); if (data.problem_number !== undefined && data.problem_number !== null) { setNewFileProblemNumber(data.problem_number); } if (data.title) setNewFileName(data.title); if (data.difficulty) setNewFileDifficulty(data.difficulty as 'Easy' | 'Medium' | 'Hard'); if (data.pattern) setNewFilePattern(data.pattern); if (data.optimal_time) setNewFileOptimalTime(data.optimal_time); if (data.optimal_space) setNewFileOptimalSpace(data.optimal_space); if (data.description) setNewFileDescription(data.description); if (data.how_to_solve) setNewFileHowToSolve(data.how_to_solve); if (data.starter_code && !newFileCode.trim()) setNewFileCode(data.starter_code); setSolutions(prev => { const next = [...prev]; const active = { ...next[activeSolutionIdx] }; if (data.pattern) active.pattern = data.pattern; if (data.optimal_time) active.time_complexity = data.optimal_time; if (data.optimal_space) active.space_complexity = data.optimal_space; if (data.how_to_solve) active.explanation = data.how_to_solve; if (data.starter_code && !active.code?.trim()) active.code = data.starter_code; next[activeSolutionIdx] = active; return next; }); if (Array.isArray(data.examples) && data.examples.length > 0) { setNewFileExamples(data.examples); } if (Array.isArray(data.constraints)) { setNewFileConstraints(data.constraints.join('\n')); } else if (typeof data.constraints === 'string') { setNewFileConstraints(data.constraints); } } else { const errData = await res.json(); setCreateError(errData.detail || 'Failed to fetch LeetCode problem data.'); } } catch { setCreateError('Fetch request failed due to connection error.'); } finally { setFetchingUrl(false); } }; // 1b. AI Prefill based on Problem Title / Code const handlePrefill = async () => { const codeToUse = activeSolution.code || newFileCode; if (!newFileName.trim() && !codeToUse.trim()) return; setPrefilling(true); setCreateError(''); try { const headers = await getHeaders(); const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/prefill`, { method: 'POST', headers, body: JSON.stringify({ name: newFileName, code: codeToUse }) }); if (res.ok) { const data = await res.json(); if (data.problem_number !== undefined && data.problem_number !== null) { setNewFileProblemNumber(data.problem_number); } if (data.title && !newFileName) setNewFileName(data.title); if (data.pattern) setNewFilePattern(data.pattern); if (data.difficulty) setNewFileDifficulty(data.difficulty as 'Easy' | 'Medium' | 'Hard'); if (data.optimal_time) setNewFileOptimalTime(data.optimal_time); if (data.optimal_space) setNewFileOptimalSpace(data.optimal_space); if (data.description) setNewFileDescription(data.description); if (data.reference_code && !codeToUse.trim()) setNewFileCode(data.reference_code); setSolutions(prev => { const next = [...prev]; const active = { ...next[activeSolutionIdx] }; if (data.pattern) active.pattern = data.pattern; if (data.optimal_time) active.time_complexity = data.optimal_time; if (data.optimal_space) active.space_complexity = data.optimal_space; if (data.reference_code && !active.code?.trim()) active.code = data.reference_code; next[activeSolutionIdx] = active; return next; }); } else { const errData = await res.json(); setCreateError(errData.detail || 'Prefill failed.'); } } catch { setCreateError('Prefill request failed due to connection error.'); } finally { setPrefilling(false); } }; // 2. AI Assist: Generate "How to solve?" Intuition const handleGenerateIntuition = async () => { const codeToUse = activeSolution.code || newFileCode; if (!newFileName.trim() && !codeToUse.trim()) { setCreateError('Please enter a problem name or code first.'); return; } setLoadingIntuition(true); setCreateError(''); try { const headers = await getHeaders(); const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/assist-field`, { method: 'POST', headers, body: JSON.stringify({ field: 'intuition', title: newFileName, code: codeToUse, description: newFileDescription }) }); if (res.ok) { const data = await res.json(); if (data.how_to_solve) { setNewFileHowToSolve(data.how_to_solve); updateActiveSolution({ explanation: data.how_to_solve }); } } else { const errData = await res.json(); setCreateError(errData.detail || 'Failed to generate intuition.'); } } catch { setCreateError('Intuition generator failed due to connection error.'); } finally { setLoadingIntuition(false); } }; // 3. AI Assist: Format Code with Step-by-Step Comments const handleFormatCode = async () => { const codeToUse = activeSolution.code || newFileCode; if (!codeToUse.trim()) { setCreateError('Please enter some Python code to format.'); return; } setLoadingComments(true); setCreateError(''); try { const headers = await getHeaders(); const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/assist-field`, { method: 'POST', headers, body: JSON.stringify({ field: 'comments', title: newFileName, code: codeToUse }) }); if (res.ok) { const data = await res.json(); if (data.formatted_code) { setNewFileCode(data.formatted_code); updateActiveSolution({ code: data.formatted_code }); } } else { const errData = await res.json(); setCreateError(errData.detail || 'Failed to format code.'); } } catch { setCreateError('Code formatter failed due to connection error.'); } finally { setLoadingComments(false); } }; // 4. Submit Problem (Dual-write to Database & Google Docs) const handleCreateProblem = async (e: React.FormEvent) => { e.preventDefault(); if (!newFileName.trim()) { setCreateError('Problem name cannot be empty'); return; } setCreating(true); setCreateError(''); setCreateSuccess(''); try { const headers = await getHeaders(); const constraintsList = newFileConstraints .split('\n') .map(c => c.trim()) .filter(Boolean); const optimalSol = solutions.find(s => s.is_optimal) || solutions[0]; const finalPattern = optimalSol?.pattern || newFilePattern.trim() || 'General'; const finalCode = optimalSol?.code || newFileCode; const finalHowToSolve = optimalSol?.explanation || newFileHowToSolve; const finalOptimalTime = newFileOptimalTime || optimalSol?.time_complexity || 'O(N)'; const finalOptimalSpace = newFileOptimalSpace || optimalSol?.space_complexity || 'O(1)'; let res: Response; if (isEditMode && initialProblem) { const targetId = initialProblem.id || (initialProblem.problem_number ? String(initialProblem.problem_number) : '') || newFileName.trim(); res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/${encodeURIComponent(targetId)}`, { method: 'PUT', headers, body: JSON.stringify({ name: newFileName.trim(), pattern: finalPattern, difficulty: newFileDifficulty, reference_code: finalCode, description: newFileDescription, problem_number: newFileProblemNumber === '' ? null : Number(newFileProblemNumber), optimal_time: finalOptimalTime, optimal_space: finalOptimalSpace, examples: newFileExamples.filter(ex => ex.input.trim() || ex.output.trim()), constraints: constraintsList, how_to_solve: finalHowToSolve, solutions: solutions }) }); } else { res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/create`, { method: 'POST', headers, body: JSON.stringify({ name: newFileName.trim(), pattern: finalPattern, difficulty: newFileDifficulty, reference_code: finalCode, description: newFileDescription, problem_number: newFileProblemNumber === '' ? null : Number(newFileProblemNumber), optimal_time: finalOptimalTime, optimal_space: finalOptimalSpace, examples: newFileExamples.filter(ex => ex.input.trim() || ex.output.trim()), constraints: constraintsList, how_to_solve: finalHowToSolve, sync_to_gdoc: syncToGDoc, solutions: solutions }) }); } const data = await res.json(); if (res.ok && (data.success || data.problem_id)) { setCreateSuccess(isEditMode ? 'Problem updated successfully!' : 'Problem saved and synced successfully!'); setTimeout(() => { onSuccess(); onClose(); }, 1000); } else { setCreateError(data.detail || (isEditMode ? 'Failed to update problem.' : 'Failed to create problem.')); } } catch { setCreateError('Connection timed out.'); } finally { setCreating(false); } }; const addExample = () => { setNewFileExamples([...newFileExamples, { input: '', output: '', explanation: '' }]); }; const removeExample = (idx: number) => { if (newFileExamples.length <= 1) return; setNewFileExamples(newFileExamples.filter((_, i) => i !== idx)); }; const updateExample = (idx: number, field: keyof ExampleItem, val: string) => { const next = [...newFileExamples]; next[idx] = { ...next[idx], [field]: val }; setNewFileExamples(next); }; return (
{/* Top Header & Tab Bar */}
✦

{isEditMode ? 'Edit Problem Specification' : 'Problem & Note Studio'}

{isEditMode && ( EDIT MODE )}
{/* Tab Switcher */}
{/* Quick LeetCode Fetch Bar */}
setUrlQuery(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleFetchLeetCode(); } }} placeholder="Paste LeetCode URL (e.g. https://leetcode.com/problems/two-sum/) or Title..." className="flex-1 bg-white border-2 border-ink-black px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-medium" />
{/* Messages */} {createError && (
⚠️ {createError}
)} {createSuccess && (
βœ… {createSuccess}
)} {/* Main Body */}
{activeTab === 'form' ? ( <> {/* Row 1: Problem #, Title, Difficulty */}
setNewFileProblemNumber(e.target.value === '' ? '' : Number(e.target.value))} placeholder="e.g. 1" className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-bold" />
setNewFileName(e.target.value)} placeholder="e.g. Two Sum" className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-bold" />
{/* Row 2: Target Optimal Complexities (Active Recall Shielded on Review) */}
(hidden behind spoiler on review)
setNewFileOptimalTime(e.target.value)} placeholder="e.g. O(N)" className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-bold" />
(hidden behind spoiler on review)
setNewFileOptimalSpace(e.target.value)} placeholder="e.g. O(1)" className="bg-white border-2 border-ink-black p-1.5 text-xs outline-none focus:ring-1 focus:ring-primary-purple font-mono font-bold" />
{/* Row 3: Problem Description */}