import { ZHour } from "@lifetracker/shared/types/days";
import React from "react";
import spacetime from "spacetime";
import { api } from "@/server/api/client";
import { EditableHourCode } from "@/components/dashboard/hours/EditableHourCode";
import { useUpdateHour } from "@lifetracker/shared-react/hooks/days";
import { useToast } from "@/components/ui/use-toast";
import { getHourFromTime } from "@lifetracker/shared/utils/hours";

async function fetchDays(view: string, dateQuery: string) {
    const timezone = await api.users.getTimezone();

    const today = spacetime(dateQuery ?? "today");
    const firstDay = today.subtract(3, "day").last("week").startOf("week");

    const days = [];
    for (let i = 0; i < 20; i++) {
        const dayDate = firstDay.add(i, "day").format("iso-short");
        console.log(dayDate);
        const dayRes = await api.days.get({
            dateQuery: dayDate,
            timezone: timezone,
        });
        days.push(dayRes);
    }

    return days;
}

export default async function TimelinePage({ params }: { params: { view: string, dateQuery: string }; }) {
    const { view = "month", dateQuery } = await params;
    const days = await fetchDays(view, dateQuery);

    return (
        <>
            <div className="grid" style={{ "gridTemplateColumns": "repeat(25, 1fr)" }}>
                <div className="flex items-center">Date</div>
                {Array.from({ length: 24 }, (_, i) => (
                    <div key={i} className="flex text-center items-center justify-center font-mono">
                        {getHourFromTime(i, "twelves")}
                    </div>
                ))}
            </div>
            {days.map((day, index) => (
                <div
                    key={index}
                    className="grid"
                    style={{ "gridTemplateColumns": "repeat(25, 1fr)" }}
                >
                    <div className="text-right font-mono">
                        {spacetime(day.date).format("{iso-month}/{date-pad}")}
                    </div>
                    {day.hours.map((hour, i) => (
                        <EditableHourCode
                            key={i}
                            originalText={hour.categoryCode}
                            hour={hour}
                            i={i}
                        />
                        // <div key={i}
                        //     datetime={day.date + "T" + hour.time + ":00:00"}
                        //     className="flex items-center justify-center font-mono"
                        //     style={{
                        //         backgroundColor: hour.background ?? "white",
                        //         color: hour.foreground ?? "black",
                        //     }}
                        // >
                        //     {hour.categoryCode ?? "_"}
                        // </div>
                    ))}
                </div>

            ))}
        </>
    );
}