import { Reffuse } from "@/reffuse"
import { createFileRoute } from "@tanstack/react-router"
import { Console, DateTime, Effect, Ref, Schedule, SubscriptionRef } from "effect"
import { useMemo } from "react"


export const Route = createFileRoute("/time")({
    component: Time
})

function Time() {

    const runtime = Reffuse.useRuntime()

    const timeRef = useMemo(() => DateTime.now.pipe(
        Effect.flatMap(SubscriptionRef.make),
        runtime.runSync,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    ), [])

    // Reffuse.useFork(Effect.addFinalizer(() => Console.log("Component unmounted.")).pipe(
    //     Effect.flatMap(() => DateTime.now),
    //     Effect.flatMap(v => Ref.set(timeRef, v)),
    //     Effect.repeat(Schedule.spaced("1 second")),
    // ))
    Reffuse.useFork(DateTime.now.pipe(
        Effect.flatMap(v => Ref.set(timeRef, v)),
        Effect.repeat(Schedule.intersect(
            Schedule.forever,
            Schedule.spaced("1 second"),
        )),
    ))

    const [time] = Reffuse.useRefState(timeRef)


    return (
        <div className="container mx-auto">
            <p className="text-center">
                {DateTime.format(time, {
                    hour: "numeric",
                    minute: "numeric",
                    second: "numeric",
                })}
            </p>
        </div>
    )

}
