import { notFound, redirect } from "next/navigation";
import { api } from "@/server/api/client";
import { TRPCError } from "@trpc/server";
import DayView from "@/components/dashboard/days/DayView";
import { getServerAuthSession } from "@/server/auth";
import LoadingSpinner from "@/components/ui/spinner";
import { useTimezone } from "@/lib/userLocalSettings/client";
import { getUserLocalSettings } from "@/lib/userLocalSettings/userLocalSettings";

export default async function DayPage({ params }: { params: { dateQuery: string }; }) {
    const session = await getServerAuthSession();
    if (!session) {
        redirect("/");
    }

    let day;

    try {
        day = await api.days.get({
            dateQuery: (await params).dateQuery,
            timezone: (await getUserLocalSettings()).timezone,
        });
    } catch (e) {
        if (e instanceof TRPCError) {
            if (e.code == "NOT_FOUND") {
                notFound();
            }
        }
        throw e;
    }

    return (
        <div className="container">
            {
                day == undefined ?
                    <LoadingSpinner /> :
                    <DayView
                        day={day}
                    />
            }
        </div>
    );
}
