"use client";
import { useEffect, useState } from "react";
import { signOut, useSession } from "next-auth/react";
import { SessionsLineChart, CategoriesBarChart } from "../../components/Charts";
import DashboardSettings from "./settings";
import UserManagement from "./users";
import { Company, MetricsResult } from "../../lib/types";
interface MetricsCardProps {
label: string;
value: string | number | null | undefined;
}
function MetricsCard({ label, value }: MetricsCardProps) {
return (
{value ?? "-"}
{label}
);
}
// Safely wrapped component with useSession
function DashboardContent() {
const { data: session } = useSession();
const [metrics, setMetrics] = useState(null);
const [company, setCompany] = useState(null);
const [, setLoading] = useState(false);
const [csvUrl, setCsvUrl] = useState("");
const [refreshing, setRefreshing] = useState(false);
const isAdmin = session?.user?.role === "admin";
const isAuditor = session?.user?.role === "auditor";
useEffect(() => {
// Fetch metrics, company, and CSV URL on mount
const fetchData = async () => {
setLoading(true);
const res = await fetch("/api/dashboard/metrics");
const data = await res.json();
setMetrics(data.metrics);
setCompany(data.company);
setCsvUrl(data.csvUrl);
setLoading(false);
};
fetchData();
}, []);
async function handleRefresh() {
if (isAuditor) return; // Prevent auditors from refreshing
try {
setRefreshing(true);
const res = await fetch("/api/admin/refresh-sessions", {
method: "POST",
headers: { "Content-Type": "application/json" },
});
if (res.ok) {
// Refetch metrics
const metricsRes = await fetch("/api/dashboard/metrics");
const data = await metricsRes.json();
setMetrics(data.metrics);
}
} finally {
setRefreshing(false);
}
}
if (!metrics || !company) {
return Loading dashboard...
;
}
return (
{/* Header with company info */}
{company.name}
Dashboard updated{" "}
{new Date(metrics.lastUpdated || Date.now()).toLocaleString()}
{refreshing ? "Refreshing..." : "Refresh Data"}
signOut()}
>
Sign Out
{/* Metrics Cards */}
{/* Charts Row */}
Sessions by Day
Categories
{/* Admin Controls */}
{isAdmin && (
<>
>
)}
);
}
// Our exported component
export default function DashboardPage() {
// We don't use useSession here to avoid the error outside the provider
return ;
}