'use client' import { RequireAuth } from '@/components/auth/RequireAuth' import { useAuth } from '@/contexts/AuthContext' import { Header } from '@/components/header' import { Footer } from '@/components/footer' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Skeleton } from '@/components/ui/skeleton' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import Link from 'next/link' import { useQuery } from '@tanstack/react-query' import { useState, useMemo } from 'react' import { BookOpen, Edit3, Eye, Heart, TrendingUp, Clock, Users, Plus, RefreshCw, Trash2 } from 'lucide-react' // Types matching the API response from /api/dashboard interface DashboardStats { totalTopics: number publishedTopics: number draftTopics: number totalViews: number } interface UserTopic { id: string title: string slug: string publishedAt: number isDraft: boolean views?: number excerpt: string tags: { name: string }[] } interface DashboardResponse { success: boolean data: { stats: DashboardStats userTopics: UserTopic[] } } type FilterType = 'all' | 'published' | 'drafts' // Fetch dashboard data from the API const fetchDashboardData = async (): Promise => { const response = await fetch('/api/dashboard', { method: 'GET', headers: { 'Content-Type': 'application/json', }, credentials: 'include', // Include cookies for authentication }) if (!response.ok) { const errorData = await response.json().catch(() => ({ error: { message: 'Unknown error' } })) throw new Error(errorData.error?.message || `HTTP ${response.status}: Failed to fetch dashboard data`) } return response.json() } function DashboardContent() { const { user } = useAuth() const [filterType, setFilterType] = useState('all') const [deletingTopic, setDeletingTopic] = useState(null) // Use TanStack Query for data fetching with automatic caching and refetching const { data: dashboardData, isLoading, error, refetch, isRefetching, } = useQuery({ queryKey: ['dashboard', user?.id], queryFn: fetchDashboardData, enabled: !!user, // Only fetch when user is authenticated staleTime: 0, // Always consider data stale - fetch fresh data gcTime: 0, // Don't cache data retry: (failureCount, error: any) => { // Don't retry on authentication errors if (error.message.includes('401') || error.message.includes('Unauthorized')) { return false } return failureCount < 3 }, }) // Extract data from the response const stats = dashboardData?.data?.stats const userTopics = dashboardData?.data?.userTopics || [] // Filter topics based on the selected filter type const filteredTopics = useMemo(() => { switch (filterType) { case 'published': return userTopics.filter(topic => !topic.isDraft) case 'drafts': return userTopics.filter(topic => topic.isDraft) default: return userTopics } }, [userTopics, filterType]) // Handle topic deletion const handleDeleteTopic = async (topicId: string, topicTitle: string) => { if (!confirm(`Are you sure you want to delete "${topicTitle}"? This action cannot be undone.`)) { return } try { setDeletingTopic(topicId) const response = await fetch(`/api/topic?id=${topicId}`, { method: 'DELETE', credentials: 'include', }) const result = await response.json() if (!response.ok || !result.success) { throw new Error(result.error?.message || 'Failed to delete topic') } // Refetch dashboard data to update the UI refetch() // Optional: Show success message // You can add a toast notification here if you have a toast system } catch (error) { console.error('Failed to delete topic:', error) alert(`Failed to delete topic: ${error instanceof Error ? error.message : 'Unknown error'}`) } finally { setDeletingTopic(null) } } // Handle loading state if (isLoading) { return (
{Array.from({ length: 4 }).map((_, i) => ( ))}
{Array.from({ length: 3 }).map((_, i) => (
))}
) } // Handle error state if (error) { return (

Failed to Load Dashboard

{error.message || 'An unexpected error occurred'}

) } return (
{/* Header */}

Dashboard

Welcome back, {user?.name}! Here's your topics overview.

{/* Stats Cards */}

{stats?.totalTopics || 0}

Total Topics

{stats?.publishedTopics || 0}

Published

{stats?.totalViews?.toLocaleString() || '0'}

Total Views

0

Total Likes

{/* Content Grid */}
{/* Recent Topics with Filter */}
Recent Topics Your latest topics
{filteredTopics.length === 0 ? (

{filterType === 'all' ? 'No topics yet. Start creating your first topic!' : filterType === 'drafts' ? 'No draft topics found.' : 'No published topics found.'}

) : (
{filteredTopics.map((topic) => (

{topic.title}

{new Date(topic.publishedAt).toLocaleDateString()}

{topic.isDraft ? 'Draft' : 'Published'}

{topic.excerpt}

{!topic.isDraft && (
{topic.views || 0}
)}
))}
)}
{/* Quick Actions - Cleaned up */} Quick Actions Get things done faster
) } export default function DashboardPage() { return (
) }