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

function DeleteBookmarkDialog({ bookmark }: { bookmark: Bookmark }) {
	const closeDialog = useBookmarkPageStore((state) => state.closeDialog)
	const deleteBookmarkMutation = useDeleteBookmark()

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

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

	function cancel() {
		closeDialog()
	}

	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 }
