'use client';
import { createClient } from "@/utils/supabase/client";
import { useEffect, useState } from "react";
import spacetime from "spacetime";

const supabase = createClient();

export default function RealtimeDayPage({ initialDay }) {
    const [day, setDay] = useState(initialDay);

    useEffect(() => {
        if (initialDay && !day) {
            setDay(initialDay);
        }
    }, [initialDay]);

    useEffect(() => {
        const daysChannel = supabase.channel('days')
            .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'days' }, (payload) => {
                setDay(payload.new);
            }).subscribe();

        const hoursChannel = supabase.channel('hours')
            .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'hours' }, (payload) => {
                const updatedHour = payload.new;
                const prevHours = day.hours;
                const newHours = prevHours.map((hour) => {
                    if (hour.id === updatedHour.id) {
                        return updatedHour;
                    }
                    return hour;
                });
                const newDay = { ...day, hours: newHours };
                console.log(newDay);
                setDay(newDay);
            }).subscribe();

        return () => {
            daysChannel.unsubscribe();
            hoursChannel.unsubscribe();
        }
    }, [supabase])

    return (
        <>
            <h1>{spacetime(day.date).format('{month} {date-ordinal}, {year}')}</h1>
            <ul>
                <li>MOOD: {day.mood ?? "No mood set."}</li>
                <li>COMMENT: {day.comment ?? "No comment yet."}</li>
            </ul>
            <ul>
                {day.hours.map((hour) => (
                    <li key={hour.id}
                        className="p-2"
                        style={{
                            "backgroundColor": hour.category?.color?.hexcode,
                            "color": hour.category?.color?.inverse
                        }}>[{spacetime(hour.datetime).format('{time}')}] {hour.comment}</li>
                ))}

            </ul>
        </>
    )
}