import { StatsCard } from "@/components/dashboard/stats-card"
import { UrlFormCard } from "@/components/dashboard/url-form-card"
import { getSession } from "@/lib/auth/session"
import { getDashboardStats } from "@/lib/dashboard/stats"
import { LinkIcon, MousePointerClick, TrendingUp } from "lucide-react"

export default async function Dashboard() {
    const { session, redirect } = await getSession()

    if (!session) {
        redirect("/sign-in")
    }

    const stats = await getDashboardStats()

    // Determine the most visited URL display value
    const mostVisitedDisplay = stats.mostVisitedUrl
        ? stats.mostVisitedUrl.visitCount > 0
            ? `${stats.mostVisitedUrl.title || stats.mostVisitedUrl.slug || "Untitled"} (${stats.mostVisitedUrl.visitCount})`
            : "No visits"
        : "No URLs"

    return (
        <div className="p-6">
            <h1 className="text-2xl font-bold text-foreground mb-4 block">Dashboard</h1>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
                <StatsCard
                    title="Shortened URLs"
                    value={stats.totalUrls}
                    icon={<LinkIcon className="h-4 w-4 text-muted-foreground" />}
                    description="Total number of shortened links"
                />
                <StatsCard
                    title="Total Visits"
                    value={stats.totalVisits}
                    icon={<MousePointerClick className="h-4 w-4 text-muted-foreground" />}
                    description="Combined visits across all links"
                />
                <StatsCard
                    title="Most Visited URL"
                    value={mostVisitedDisplay}
                    icon={<TrendingUp className="h-4 w-4 text-muted-foreground" />}
                    description="Most popular shortened link"
                />
            </div>

            <UrlFormCard />
        </div>
    )
}
