import { Schema as S } from "@effect/schema"
import { createLazyFileRoute } from "@tanstack/react-router"
import { JsonifiableTodo } from "@todo-tests/common/data"
import { Option, flow, identity } from "effect"
import { IObservableArray, observable } from "mobx"
import { observer } from "mobx-react-lite"
import { useState } from "react"
import { Todo } from "../data"
import { VTodo } from "../todo/VTodo"
import { trpc } from "../trpc/trpc"


const decodeTodos = flow(
    S.decodeSync(
        S.mutable(S.Array(
            JsonifiableTodo.pipe(S.compose(Todo))
        ))
    ),

    observable.array,
)


export const Index = observer(() => {

    const [todos, setTodos] = useState<IObservableArray<Todo>>(observable.array())

    trpc.todos.changes.useSubscription(undefined, {
        onData: data => {
            setTodos(decodeTodos(data))
        }
    })

    return (
        <div className="flex flex-col gap-1 items-stretch">
            {todos.map(todo => (
                <VTodo
                    key={Option.match(todo.id, {
                        onSome: identity,
                        onNone: () => todo.order,
                    })}

                    todo={todo}
                />
            ))}
        </div>
    )

})

export const Route = createLazyFileRoute("/")({ component: Index })
