import { createFileRoute } from "@tanstack/react-router"
import { BookmarkList } from "./-bookmark-list"
import { useBookmarkPageStore } from "./-store"
import { fetchApi, useAuthenticatedQuery } from "~/api"
import { LoadingSpinner } from "~/components/loading-spinner"
import { BookmarkListActionBar } from "./-action-bar"

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

function RouteComponent() {
	return (
		<main className="w-full flex justify-center">
			<BookmarkListPane />
			<BookmarkListActionBar 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 searchParamsString = new URLSearchParams(Route.useSearch()).toString()
	const { data: bookmarks, status } = useAuthenticatedQuery(
		searchParamsString ? ["bookmarks", searchParamsString] : ["bookmarks"],
		async () => {
			const res = await fetchApi(searchParamsString ? `/bookmarks?${searchParamsString}` : "/bookmarks")
			return await 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>
	}
}
