page.tsx344 lines, 12 KB
| 1 | "use client"; |
| 2 | |
| 3 | import { |
| 4 | Card, |
| 5 | CardContent, |
| 6 | CardDescription, |
| 7 | CardFooter, |
| 8 | CardHeader, |
| 9 | CardTitle, |
| 10 | } from "@/components/ui/card"; |
| 11 | import { |
| 12 | ChartConfig, |
| 13 | ChartContainer, |
| 14 | ChartTooltip, |
| 15 | ChartTooltipContent, |
| 16 | } from "@/components/ui/chart"; |
| 17 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; |
| 18 | import { getUserUrls } from "@/server/actions/urls/get-user-urls"; |
| 19 | import { Loader2, TrendingDown, TrendingUp } from "lucide-react"; |
| 20 | import { useSession } from "next-auth/react"; |
| 21 | import { redirect } from "next/navigation"; |
| 22 | import { useEffect, useMemo, useState } from "react"; |
| 23 | import { |
| 24 | Bar, |
| 25 | BarChart, |
| 26 | CartesianGrid, |
| 27 | Cell, |
| 28 | Label, |
| 29 | Pie, |
| 30 | PieChart, |
| 31 | XAxis, |
| 32 | } from "recharts"; |
| 33 | |
| 34 | interface Url { |
| 35 | id: number; |
| 36 | originalUrl: string; |
| 37 | shortCode: string; |
| 38 | createdAt: Date; |
| 39 | clicks: number; |
| 40 | } |
| 41 | |
| 42 | export default function StatsPage() { |
| 43 | const { data: session, status } = useSession(); |
| 44 | const [userUrls, setUserUrls] = useState<Url[]>([]); |
| 45 | const [loading, setLoading] = useState(true); |
| 46 | |
| 47 | useEffect(() => { |
| 48 | if (status === "unauthenticated") { |
| 49 | redirect("/login"); |
| 50 | } |
| 51 | |
| 52 | if (status === "authenticated" && session?.user?.id) { |
| 53 | const fetchUserUrls = async () => { |
| 54 | try { |
| 55 | if (!session?.user?.id) return; |
| 56 | const response = await getUserUrls(session.user.id); |
| 57 | if (response.success && response.data) { |
| 58 | setUserUrls(response.data); |
| 59 | } |
| 60 | } catch (error) { |
| 61 | console.error("Error fetching user URLs", error); |
| 62 | } finally { |
| 63 | setLoading(false); |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | fetchUserUrls(); |
| 68 | } |
| 69 | }, [session, status]); |
| 70 | |
| 71 | // calculate total clicks |
| 72 | const totalClicks = userUrls.reduce((sum, url) => sum + url.clicks, 0); |
| 73 | |
| 74 | // calculate average clicks per URL |
| 75 | const avgClicks = |
| 76 | userUrls.length > 0 |
| 77 | ? Math.round((totalClicks / userUrls.length) * 10) / 10 |
| 78 | : 0; |
| 79 | |
| 80 | // get top performing URL |
| 81 | const topUrls = [...userUrls].sort((a, b) => b.clicks - a.clicks).slice(0, 5); |
| 82 | |
| 83 | // prepare data for the bar chart with numeric values |
| 84 | const barChartData = useMemo(() => { |
| 85 | return topUrls.map((url, index) => ({ |
| 86 | url: url.shortCode, |
| 87 | clicks: url.clicks, |
| 88 | originalUrl: url.originalUrl, |
| 89 | })); |
| 90 | }, [topUrls]); |
| 91 | |
| 92 | // prepare data for the pie chart with numerc values |
| 93 | const pieChartData = useMemo(() => { |
| 94 | return topUrls.map((url, index) => ({ |
| 95 | browser: url.shortCode, |
| 96 | vistors: url.clicks, |
| 97 | fill: `hsl(var(--chart-${index + 1}))`, |
| 98 | })); |
| 99 | }, [topUrls]); |
| 100 | |
| 101 | // bar chart config |
| 102 | const barChartConfig = { |
| 103 | clicks: { |
| 104 | label: "Clicks", |
| 105 | color: "hsl(var(--chart-1))", |
| 106 | }, |
| 107 | ...topUrls.reduce((acc, url, index) => { |
| 108 | acc[url.shortCode] = { |
| 109 | label: url.shortCode, |
| 110 | color: `hsl(var(--chart-${index + 1}))`, |
| 111 | }; |
| 112 | return acc; |
| 113 | }, {} as ChartConfig), |
| 114 | }; |
| 115 | |
| 116 | // pie chart config |
| 117 | const pieChartConfig = { |
| 118 | visitors: { |
| 119 | label: "Clicks", |
| 120 | }, |
| 121 | ...topUrls.reduce((acc, url, index) => { |
| 122 | acc[url.shortCode] = { |
| 123 | label: url.shortCode, |
| 124 | color: `hsl(var(--chart-${index + 1}))`, |
| 125 | }; |
| 126 | return acc; |
| 127 | }, {} as ChartConfig), |
| 128 | }; |
| 129 | |
| 130 | if (status === "loading" || loading) { |
| 131 | return ( |
| 132 | <div className="flex justify-center items-center min-h-[400px]"> |
| 133 | <Loader2 className="size-8 animate-spin" /> |
| 134 | </div> |
| 135 | ); |
| 136 | } |
| 137 | |
| 138 | return ( |
| 139 | <> |
| 140 | <h1 className="text-3xl font-bold mb-8 text-center">URL Statistics</h1> |
| 141 | |
| 142 | <div className="grid gap-8 md:grid-cols-3 mb-8"> |
| 143 | <Card className="shadow-sm"> |
| 144 | <CardHeader className="pb-2"> |
| 145 | <CardTitle>Total URLs</CardTitle> |
| 146 | <CardDescription>Number of URLs you've created</CardDescription> |
| 147 | </CardHeader> |
| 148 | <CardContent> |
| 149 | <p className="text-3xl font-bold">{userUrls.length}</p> |
| 150 | </CardContent> |
| 151 | </Card> |
| 152 | |
| 153 | <Card className="shadow-sm"> |
| 154 | <CardHeader className="pb-2"> |
| 155 | <CardTitle>Total Clicks</CardTitle> |
| 156 | <CardDescription>Total clicks acroos all URLs</CardDescription> |
| 157 | </CardHeader> |
| 158 | <CardContent> |
| 159 | <p className="text-3xl font-bold">{totalClicks}</p> |
| 160 | </CardContent> |
| 161 | </Card> |
| 162 | |
| 163 | <Card className="shadow-sm"> |
| 164 | <CardHeader className="pb-2"> |
| 165 | <CardTitle>Average Clicks</CardTitle> |
| 166 | <CardDescription>Average clicks per URL</CardDescription> |
| 167 | </CardHeader> |
| 168 | <CardContent> |
| 169 | <p className="text-3xl font-bold">{avgClicks}</p> |
| 170 | </CardContent> |
| 171 | </Card> |
| 172 | </div> |
| 173 | |
| 174 | <Card className="shadow-sm"> |
| 175 | <CardHeader> |
| 176 | <CardTitle>Top Performing URLs</CardTitle> |
| 177 | <CardDescription>Top 5 URLs with most clicks</CardDescription> |
| 178 | </CardHeader> |
| 179 | <CardContent> |
| 180 | {barChartData.length > 0 ? ( |
| 181 | <Tabs defaultValue="bar" className="w-full"> |
| 182 | <TabsList className="mb-4"> |
| 183 | <TabsTrigger value="bar">Bar Chart</TabsTrigger> |
| 184 | <TabsTrigger value="pie">Pie Chart</TabsTrigger> |
| 185 | </TabsList> |
| 186 | <TabsContent value="bar" className="min-h-[400px] mt-4"> |
| 187 | <Card> |
| 188 | <CardHeader> |
| 189 | <CardTitle>URL Perfomance</CardTitle> |
| 190 | <CardDescription> |
| 191 | Top 5 URLs with most clicks |
| 192 | </CardDescription> |
| 193 | </CardHeader> |
| 194 | <CardContent> |
| 195 | <ChartContainer config={barChartConfig}> |
| 196 | <BarChart accessibilityLayer data={barChartData}> |
| 197 | <CartesianGrid vertical={false} /> |
| 198 | <XAxis |
| 199 | dataKey="url" |
| 200 | tickLine={false} |
| 201 | tickMargin={10} |
| 202 | axisLine={false} |
| 203 | /> |
| 204 | <ChartTooltip |
| 205 | cursor={false} |
| 206 | content={ |
| 207 | <ChartTooltipContent |
| 208 | indicator="dashed" |
| 209 | labelFormatter={(label) => `URL: ${label}`} |
| 210 | /> |
| 211 | } |
| 212 | /> |
| 213 | <Bar dataKey={"clicks"} radius={4}> |
| 214 | {barChartData.map((entry, index) => ( |
| 215 | <Cell |
| 216 | key={`cell-${index}`} |
| 217 | fill={`hsl(var(--chart-${index + 1}))`} |
| 218 | /> |
| 219 | ))} |
| 220 | </Bar> |
| 221 | </BarChart> |
| 222 | </ChartContainer> |
| 223 | </CardContent> |
| 224 | <CardFooter className="flex-col items-start gap-2 text-sm"> |
| 225 | <div className="flex gap-2 font-medium leading-none"> |
| 226 | {avgClicks > 5 ? ( |
| 227 | <> |
| 228 | Trending up by {((avgClicks / 5) * 100).toFixed(1)}% |
| 229 | this month{" "} |
| 230 | <TrendingUp className="size-4 text-green-500" /> |
| 231 | </> |
| 232 | ) : ( |
| 233 | <> |
| 234 | Coudl improve with only {5 - avgClicks} more clicks{" "} |
| 235 | <TrendingDown className="size-4 text-amber-500" /> |
| 236 | </> |
| 237 | )} |
| 238 | </div> |
| 239 | <div className="leading-none text-muted-foreground"> |
| 240 | Showing click count for your top {topUrls.length} URLs |
| 241 | </div> |
| 242 | </CardFooter> |
| 243 | </Card> |
| 244 | </TabsContent> |
| 245 | <TabsContent value="pie" className="min-h-[400px] mt-4"> |
| 246 | <Card className="flex flex-col"> |
| 247 | <CardHeader className="items-center pb-0"> |
| 248 | <CardTitle>URL Clicks Distrubtion</CardTitle> |
| 249 | <CardDescription> |
| 250 | Top {topUrls.length} URLs with most clicks |
| 251 | </CardDescription> |
| 252 | </CardHeader> |
| 253 | <CardContent className="flex-1 pb-0"> |
| 254 | <ChartContainer |
| 255 | config={pieChartConfig} |
| 256 | className="mx-auto aspect-square max-h-[350px]" |
| 257 | > |
| 258 | <PieChart> |
| 259 | <ChartTooltip |
| 260 | cursor={false} |
| 261 | content={<ChartTooltipContent hideLabel />} |
| 262 | /> |
| 263 | <Pie |
| 264 | data={pieChartData} |
| 265 | dataKey="vistors" |
| 266 | nameKey="browser" |
| 267 | innerRadius={60} |
| 268 | strokeWidth={5} |
| 269 | > |
| 270 | <Label |
| 271 | content={({ viewBox }) => { |
| 272 | if ( |
| 273 | viewBox && |
| 274 | "cx" in viewBox && |
| 275 | "cy" in viewBox |
| 276 | ) { |
| 277 | return ( |
| 278 | <text |
| 279 | x={viewBox.cx} |
| 280 | y={viewBox.cy} |
| 281 | textAnchor="middle" |
| 282 | dominantBaseline={"middle"} |
| 283 | > |
| 284 | <tspan |
| 285 | x={viewBox.cx} |
| 286 | y={viewBox.cy} |
| 287 | className="fill-foreground text-3xl font-bold" |
| 288 | > |
| 289 | {totalClicks.toLocaleString()} |
| 290 | </tspan> |
| 291 | <tspan |
| 292 | x={viewBox.cx} |
| 293 | y={(viewBox.cy || 20) + 20} |
| 294 | className="fill-muted-foreground text-xs mb-2" |
| 295 | > |
| 296 | Total Clicks |
| 297 | </tspan> |
| 298 | </text> |
| 299 | ); |
| 300 | } |
| 301 | }} |
| 302 | ></Label> |
| 303 | </Pie> |
| 304 | </PieChart> |
| 305 | </ChartContainer> |
| 306 | </CardContent> |
| 307 | <CardFooter className="flex-col gap-2 text-sm"> |
| 308 | <div className="flex items-center gap-2 font-medium leading-none"> |
| 309 | {userUrls.length > 0 && ( |
| 310 | <> |
| 311 | {avgClicks > 5 ? ( |
| 312 | <> |
| 313 | Trending up by{" "} |
| 314 | {((avgClicks / 5) * 100).toFixed(1)}% this month{" "} |
| 315 | <TrendingUp className="size-4 text-green-500" /> |
| 316 | </> |
| 317 | ) : ( |
| 318 | <> |
| 319 | Could improve with only {5 - avgClicks} more |
| 320 | clicks{" "} |
| 321 | <TrendingDown className="size-4 text-amber-500" /> |
| 322 | </> |
| 323 | )} |
| 324 | </> |
| 325 | )} |
| 326 | </div> |
| 327 | <div className="leading-none text-muted-foreground"> |
| 328 | Showing click count for your top {topUrls.length} URLs |
| 329 | </div> |
| 330 | </CardFooter> |
| 331 | </Card> |
| 332 | </TabsContent> |
| 333 | </Tabs> |
| 334 | ) : ( |
| 335 | <div className="text-center py-8 text-muted-foreground"> |
| 336 | No URL data available yet. Create some short URLs to see the |
| 337 | stats. |
| 338 | </div> |
| 339 | )} |
| 340 | </CardContent> |
| 341 | </Card> |
| 342 | </> |
| 343 | ); |
| 344 | } |