import React, { useState, useEffect, useRef } from 'react'; import { useLocation } from 'react-router-dom'; import { motion, AnimatePresence } from 'framer-motion'; import { useGenerate } from '../GenerateContext'; import { FileText, Tag, Presentation, Code, FileSpreadsheet, Search, Filter, CheckCircle2, FileQuestion, UploadCloud, Loader2 } from 'lucide-react'; import { cn } from '../../../../src/utils/cn'; import { Button } from '../../../components/ui/Button'; import { supabase } from '../../../utils/supabaseClient'; import { API_BASE_URL } from '../../../utils/api'; export const SelectMaterialStep = () => { const { materials, setMaterials, setStep } = useGenerate(); const [search, setSearch] = useState(''); const [uploadedFiles, setUploadedFiles] = useState([]); const [isUploading, setIsUploading] = useState(false); const fileInputRef = useRef(null); const location = useLocation(); useEffect(() => { const fetchMaterials = async () => { try { const { data: { session } } = await supabase.auth.getSession(); if (!session) return; const res = await fetch(`${API_BASE_URL}/api/materials`, { method: "GET", headers: { 'Authorization': `Bearer ${session.access_token}` } }); if (res.ok) { const data = await res.json(); const formatted = data.map(m => ({ id: m.storage_path, name: m.file_name, type: m.file_name.split('.').pop() || 'file', tags: ['Uploaded', 'Dataset'], date: new Date(m.created_at).toLocaleDateString(), raw: m })); setUploadedFiles(formatted); // Auto-select if passed from Navigation State if (location.state?.uploadedFileId && materials.length === 0) { setMaterials([location.state.uploadedFileId]); } } } catch (error) { console.error("Error fetching materials:", error); } }; fetchMaterials(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const toggleMaterial = (id) => { if (materials.includes(id)) { setMaterials(materials.filter(m => m !== id)); } else { setMaterials([...materials, id]); } }; const toggleAll = () => { const allMaterials = [...uploadedFiles]; if (materials.length === allMaterials.length) { setMaterials([]); } else { setMaterials(allMaterials.map(m => m.id)); } }; const handleFileUpload = async (e) => { const file = e.target.files[0]; if (!file) return; setIsUploading(true); const formData = new FormData(); formData.append('file', file); try { const { data: { session } } = await supabase.auth.getSession(); const res = await fetch(`${API_BASE_URL}/upload`, { method: 'POST', headers: { 'Authorization': `Bearer ${session?.access_token || ''}` }, body: formData }); const data = await res.json(); if (data.file_id) { const newFile = { id: data.file_id, name: file.name, type: file.name.split('.').pop() || 'file', tags: ['Uploaded', 'Target'], date: 'Just now' }; setUploadedFiles(prev => [newFile, ...prev]); if (!materials.includes(data.file_id)) { setMaterials(prev => [...prev, data.file_id]); } } } catch (err) { console.error("Upload failed", err); } finally { setIsUploading(false); if (fileInputRef.current) fileInputRef.current.value = ''; } }; const getIcon = (type) => { switch (type) { case 'pdf': return ; case 'doc': return ; case 'presentation': return ; case 'code': return ; default: return ; } }; const allAvailableMaterials = [...uploadedFiles]; const filtered = allAvailableMaterials.filter(m => m.name.toLowerCase().includes(search.toLowerCase())); return (

Select Study Materials

Choose the source documents to generate AI questions from.

setSearch(e.target.value)} />
{materials.length} Selected
{filtered.map((mat) => { const isSelected = materials.includes(mat.id); return ( toggleMaterial(mat.id)} className={cn( "flex items-center gap-4 p-4 rounded-xl cursor-pointer transition-all duration-300 border hover:shadow-md group", isSelected ? "bg-blue-50/50 dark:bg-[#4F7CFF]/5 border-[#4F7CFF] shadow-[0_4px_15px_rgba(79,124,255,0.1)]" : "bg-white dark:bg-slate-800/50 border-slate-200 dark:border-slate-700 hover:border-slate-300 dark:hover:border-slate-600" )} >
{getIcon(mat.type)}

{mat.name}

Added {mat.date} {mat.type}

{mat.tags.map(tag => ( {tag} ))}
); })}
{filtered.length === 0 && (

No materials found matching your search.

)}
); };