import { redirect } from "next/navigation";
import { Separator } from "@/components/ui/separator";
import { getServerAuthSession } from "@/server/auth";
import { ZDay } from "@lifetracker/shared/types/days";
import EditableDayComment from "./EditableDayComment";
import { MoodStars } from "./MoodStars";
import Link from "next/link";
import { cn } from "@/lib/utils";
import { ArrowLeftSquare, ArrowRightSquare } from "lucide-react";
import spacetime from "spacetime";
import EditableHour from "@/components/dashboard/hours/EditableHour";
import { DayMetrics } from "./DayMetrics";
import { api } from "@/server/api/client";

export default async function DayView({
    day,
}: {
    day: ZDay;
}) {
    const session = await getServerAuthSession();
    if (!session) {
        redirect("/");
    }

    const prevDay = spacetime(day.date).subtract(1, "day").format("iso-short");
    const nextDay = spacetime(day.date).add(1, "day").format("iso-short");

    const userMetrics = await api.metrics.list();

    const groupConsecutiveHours = (day: ZDay) => {
        const result = [];
        let currentGroup = [];

        for (const hour of day.hours) {
            if (hour.categoryCode === null) {
                if (currentGroup.length > 0) {
                    result.push(currentGroup);
                    currentGroup = [];
                }

                result.push([hour]);

                continue;
            }

            if (currentGroup.length === 0 || hour.categoryCode === currentGroup[currentGroup.length - 1].categoryCode) {
                currentGroup.push(hour);
            } else {
                result.push(currentGroup);
                currentGroup = [hour];
            }
        }

        if (currentGroup.length > 0) {
            result.push(currentGroup);
        }

        return result;
    };

    const consecutiveHours = groupConsecutiveHours(day);


    return (
        <div className="flex flex-col gap-3">

            <div className="flex justify-between pr-4 flex-col gap-4 md:flex-row">
                <div className="flex">
                    <Link
                        href={`/dashboard/day/${prevDay}`}
                        className={cn(
                            "flex-0 items-center rounded-[inherit] px-3 py-2",
                        )}
                    >
                        <div className="flex w-full justify-between">
                            <ArrowLeftSquare size={18} />
                        </div>
                    </Link>
                    <span className="text-2xl flex-1 hidden lg:block">
                        {spacetime(day.date).format("{day}, {month} {date}, {year}")}
                    </span>
                    <span className="text-2xl flex-1 lg:hidden block text-center">
                        {spacetime(day.date).format("{day-short}, {month-short} {date}, {year}")}
                    </span>
                    <Link
                        href={`/dashboard/day/${nextDay}`}
                        className={cn(
                            "flex-0 items-center rounded-[inherit] px-3 py-2",
                        )}
                    >
                        <div className="flex w-full justify-between">
                            <ArrowRightSquare size={18} />
                        </div>
                    </Link>
                </div>
                <div className="flex justify-center">
                    <MoodStars
                        day={day}
                    />
                </div>
            </div>

            <Separator />
            <div className="flex justify-between pr-4 flex-col gap-4 md:flex-row">
                <div className="pl-4">
                    <EditableDayComment day={day}
                        className="text-xl"
                    />
                </div>
                <div className="pl-4">
                    <DayMetrics day={day} />
                </div>
            </div>
            <Separator />

            <ul>
                {/* {consecutiveHours.map((group, i) => (
                    group.map((hour, j) => (
                        j == 0 ? (
                            <li key={hour.time} id={"hour-" + i.toString()}>
                                <EditableHour hour={hour} i={i} j={j} hourGroup={group} metrics={userMetrics} />
                            </li>) : (
                            ""
                        )

                    ))
                ))} */}
                {
                    day.hours.map((hour, i) => (
                        <li key={hour.time} id={"hour-" + i.toString()}>
                            <EditableHour hour={hour} i={i} j={0} hourGroup={[]} metrics={userMetrics} />
                        </li>)
                    )


                }
            </ul>

        </div>
    );
}
