'use client' import { useState, useEffect } from 'react' import { useTranslations, useLocale } from 'next-intl' import { useAuth } from '@/hooks/use-auth' import { ProtectedRoute } from '@/components/auth/protected-route' import { Container, Box, Typography, Card, CardContent, CardActions, Button, Chip, CircularProgress, Alert, Tabs, Tab, LinearProgress, IconButton } from '@mui/material' import Grid from '@mui/material/Grid' import { MenuBook, PlayArrow, Pause, CheckCircle, Add, CalendarToday, TrendingUp, Delete, Settings } from '@mui/icons-material' import Link from 'next/link' import { useRouter } from 'next/navigation' interface ReadingPlan { id: string name: string description: string duration: number difficulty: string type: string } interface UserPlan { id: string name: string startDate: string targetEndDate: string status: string currentDay: number completedDays: number streak: number longestStreak: number plan?: ReadingPlan } export default function ReadingPlansPage() { const { user } = useAuth() const locale = useLocale() const router = useRouter() const t = useTranslations('readingPlans') const [loading, setLoading] = useState(true) const [availablePlans, setAvailablePlans] = useState([]) const [userPlans, setUserPlans] = useState([]) const [error, setError] = useState('') const [tabValue, setTabValue] = useState(0) useEffect(() => { loadData() }, [locale]) const loadData = async () => { setLoading(true) setError('') try { const token = localStorage.getItem('authToken') // Load available plans const plansRes = await fetch(`/api/reading-plans?language=${locale}`) const plansData = await plansRes.json() if (plansData.success) { setAvailablePlans(plansData.plans) } // Load user's plans if authenticated if (token) { const userPlansRes = await fetch('/api/user/reading-plans?status=ALL', { headers: { 'Authorization': `Bearer ${token}` } }) const userPlansData = await userPlansRes.json() if (userPlansData.success) { setUserPlans(userPlansData.plans) } } } catch (err) { console.error('Error loading reading plans:', err) setError('Failed to load reading plans') } finally { setLoading(false) } } const enrollInPlan = async (planId: string) => { const token = localStorage.getItem('authToken') if (!token) { router.push(`/${locale}/login`) return } try { const response = await fetch('/api/user/reading-plans', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ planId }) }) const data = await response.json() if (data.success) { loadData() // Reload data setTabValue(1) // Switch to My Plans tab } else { setError(data.error || 'Failed to enroll in plan') } } catch (err) { console.error('Error enrolling in plan:', err) setError('Failed to enroll in plan') } } const updatePlanStatus = async (planId: string, status: string) => { const token = localStorage.getItem('authToken') if (!token) return try { const response = await fetch(`/api/user/reading-plans/${planId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ status }) }) const data = await response.json() if (data.success) { loadData() // Reload data } else { setError(data.error || 'Failed to update plan') } } catch (err) { console.error('Error updating plan:', err) setError('Failed to update plan') } } const deletePlan = async (planId: string) => { if (!confirm('Are you sure you want to delete this reading plan? This action cannot be undone.')) { return } const token = localStorage.getItem('authToken') if (!token) return try { const response = await fetch(`/api/user/reading-plans/${planId}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }) const data = await response.json() if (data.success) { loadData() // Reload data } else { setError(data.error || 'Failed to delete plan') } } catch (err) { console.error('Error deleting plan:', err) setError('Failed to delete plan') } } const getDifficultyColor = (difficulty: string) => { switch (difficulty.toLowerCase()) { case 'beginner': return 'success' case 'intermediate': return 'warning' case 'advanced': return 'error' default: return 'default' } } const getStatusColor = (status: string) => { switch (status) { case 'ACTIVE': return 'primary' case 'COMPLETED': return 'success' case 'PAUSED': return 'warning' case 'CANCELLED': return 'error' default: return 'default' } } if (loading) { return ( ) } return ( {/* Header */} Reading Plans Stay consistent in your Bible reading with structured reading plans {error && ( setError('')}> {error} )} {/* Tabs */} setTabValue(v)}> {/* Available Plans Tab */} {tabValue === 0 && ( {availablePlans.map((plan) => ( {plan.name} } /> {plan.description} ))} {availablePlans.length === 0 && ( No reading plans available for this language yet. )} )} {/* My Plans Tab */} {tabValue === 1 && ( {userPlans.map((userPlan) => { const progress = userPlan.completedDays / (userPlan.plan?.duration || 365) * 100 return ( {userPlan.name} Progress {userPlan.completedDays} / {userPlan.plan?.duration || 365} days Current Streak {userPlan.streak} days Best Streak {userPlan.longestStreak} days {userPlan.status === 'ACTIVE' && ( updatePlanStatus(userPlan.id, 'PAUSED')} title="Pause" > )} {userPlan.status === 'PAUSED' && ( updatePlanStatus(userPlan.id, 'ACTIVE')} title="Resume" > )} {userPlan.status !== 'COMPLETED' && ( deletePlan(userPlan.id)} title="Delete" color="error" > )} ) })} {userPlans.length === 0 && ( You haven't enrolled in any reading plans yet. )} )} ) }