import React, { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { useParams, useNavigate } from 'react-router-dom'
import { topicAPI, learningAPI, progressAPI } from '../../services/api'
import {
BookOpen,
ArrowLeft,
Sparkles,
Play,
ChevronRight,
Lightbulb
} from 'lucide-react'
import LessonViewer from './LessonViewer'
import CodePlayground from './CodePlayground'
import toast from 'react-hot-toast'
const Learn = () => {
const { topicId } = useParams()
const navigate = useNavigate()
const [topics, setTopics] = useState([])
const [selectedTopic, setSelectedTopic] = useState(null)
const [lesson, setLesson] = useState(null)
const [loading, setLoading] = useState(false)
const [generatingLesson, setGeneratingLesson] = useState(false)
useEffect(() => {
loadTopics()
}, [])
useEffect(() => {
if (topicId) {
loadTopicAndLesson(parseInt(topicId))
}
}, [topicId])
const loadTopics = async () => {
try {
const response = await topicAPI.getAll()
setTopics(response.data)
} catch (error) {
toast.error('Failed to load topics')
}
}
const loadTopicAndLesson = async (id) => {
try {
setLoading(true)
const topicResponse = await topicAPI.getById(id)
setSelectedTopic(topicResponse.data)
} catch (error) {
toast.error('Failed to load topic')
} finally {
setLoading(false)
}
}
const handleGenerateLesson = async () => {
if (!selectedTopic) return
setGeneratingLesson(true)
const loadingToast = toast.loading('AI is generating your personalized lesson...')
try {
const response = await learningAPI.generateLesson(selectedTopic.id)
setLesson(response.data)
toast.success('Lesson generated successfully!', { id: loadingToast })
} catch (error) {
toast.error('Failed to generate lesson', { id: loadingToast })
} finally {
setGeneratingLesson(false)
}
}
const handleSelectTopic = (topic) => {
setSelectedTopic(topic)
setLesson(null)
navigate(`/learn/${topic.id}`)
}
const handleNextTopic = async () => {
try {
const response = await progressAPI.getNextTopic(selectedTopic?.id)
if (response.data) {
handleSelectTopic(response.data)
}
} catch (error) {
toast.error('No more recommendations')
}
}
if (!selectedTopic && !topicId) {
return (
AI-powered personalized lessons await you
{topic.description}
Choose a Topic to Learn
{topic.name}
{selectedTopic.category}
{selectedTopic.description}