import { useDeleteBookmark } from "~/bookmark/api"
import { Button } from "~/components/button"
import { Dialog, DialogTitle, DialogBody, DialogActionRow } from "~/components/dialog"
import { LoadingSpinner } from "~/components/loading-spinner"
import { useMnemonics } from "~/hooks/use-mnemonics"
import { useBookmarkPageStore, ActiveDialog } from "../-store"

function DeleteBookmarkDialog() {
	// biome-ignore lint/style/noNonNullAssertion: this cannot be null when delete bookmark dialog is visible
	const bookmark = useBookmarkPageStore((state) => state.bookmarkToBeDeleted!)
	const setActiveDialog = useBookmarkPageStore((state) => state.setActiveDialog)
	const deleteBookmarkMutation = useDeleteBookmark()

	useMnemonics(
		{
			y: proceed,
			n: cancel,
		},
		{ ignore: () => false },
	)

	async function proceed() {
		try {
			await deleteBookmarkMutation.mutateAsync({ bookmark })
			setActiveDialog(ActiveDialog.None)
		} catch (error) {
			console.error(error)
		}
	}

	function cancel() {
		setActiveDialog(ActiveDialog.None)
	}

	function body() {
		switch (deleteBookmarkMutation.status) {
			case "pending":
				return (
					<p>
						Deleting <LoadingSpinner />
					</p>
				)
			case "idle":
				return (
					<p>
						The bookmark titled:
						<br />
						<br />
						<strong>
							<em>"{bookmark.title}"</em>
						</strong>
						<br />
						<br />
						will be deleted. Proceed?
					</p>
				)
			case "error":
				return <p className="text-red-500">Failed to delete the bookmark!</p>
		}
	}

	function title() {
		switch (deleteBookmarkMutation.status) {
			case "pending":
				return "PLEASE WAIT"
			case "idle":
				return "CONFIRM"
			case "error":
				return "ERROR OCCURRED"
		}
	}

	return (
		<Dialog>
			<DialogTitle>{title()}</DialogTitle>
			<DialogBody>{body()}</DialogBody>
			<DialogActionRow>
				<Button disabled={deleteBookmarkMutation.isPending} onClick={proceed}>
					{deleteBookmarkMutation.isError ? "Retry" : "Proceed"} (y)
				</Button>
				<Button disabled={deleteBookmarkMutation.isPending} onClick={cancel}>
					Cancel (n)
				</Button>
			</DialogActionRow>
		</Dialog>
	)
}

export { DeleteBookmarkDialog }
