import { createFileRoute, useNavigate } from "@tanstack/react-router"
import { useCallback } from "react"
import { useLogOut } from "~/auth"
import { Button } from "~/components/button"
import { useMnemonics } from "~/hooks/use-mnemonics"
import { BookmarkList } from "./-bookmark-list"
import { ActiveDialog, LayoutMode, useBookmarkPageStore } from "./-store"
import { fetchApi, useAuthenticatedQuery } from "~/api"
import { LoadingSpinner } from "~/components/loading-spinner"
import { ActionBar } from "./-action-bar"

export const Route = createFileRoute("/bookmarks/")({
	component: RouteComponent,
})

function RouteComponent() {
	return (
		<main className="w-full flex justify-center">
			<BookmarkListPane />
			<ActionBar className="fixed left-0 right-0 bottom-0" />
		</main>
	)
}

function BookmarkListPane() {
	return (
		<div className="flex flex-col py-16 container max-w-3xl md:flex-row lg:py-32">
			<header className="mb-4 md:mb-0 md:mr-16 text-start">
				<h1 className="font-bold text-start">
					<span className="invisible md:hidden">&nbsp;&gt;&nbsp;</span>
					YOUR BOOKMARKS
				</h1>
			</header>
			<div className="flex-1">
				<BookmarkListContainer />
			</div>
		</div>
	)
}

function BookmarkListContainer() {
	const { data: bookmarks, status } = useAuthenticatedQuery(["bookmarks"], () =>
		fetchApi("/bookmarks").then((res) => res.json()),
	)
	const handleBookmarkListItemAction = useBookmarkPageStore((state) => state.handleBookmarkListItemAction)

	switch (status) {
		case "success":
			return (
				<BookmarkList
					className="-mt-2"
					alwaysExpandItem={false}
					bookmarks={bookmarks}
					onItemAction={handleBookmarkListItemAction}
				/>
			)

		case "pending":
			return (
				<p>
					Loading <LoadingSpinner />
				</p>
			)

		case "error":
			return <p>error loading bookmarks</p>
	}
}
