import client from "@/honoClient";
import { Button, Flex, Modal, Text } from "@mantine/core";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getRouteApi, useSearch } from "@tanstack/react-router";
import { deleteQuestion } from "../queries/questionQueries";
import { notifications } from "@mantine/notifications";
import fetchRPC from "@/utils/fetchRPC";

const routeApi = getRouteApi("/_dashboardLayout/questions/");

export default function QuestionDeleteModal() {
	const queryClient = useQueryClient();

	const searchParams = useSearch({ from: "/_dashboardLayout/questions/" }) as {
		delete: string;
	};

	const questionId = searchParams.delete;
	const navigate = routeApi.useNavigate();

	const questionQuery = useQuery({
		queryKey: ["questions", questionId],
		queryFn: async () => {
			if (!questionId) return null;
			return await fetchRPC(
				client.questions[":id"].$get({
					param: {
						id: questionId,
					},
					query: {},
				})
			);
		},
	});

	const mutation = useMutation({
		mutationKey: ["deleteQuestionMutation"],
		mutationFn: async ({ id }: { id: string }) => {
			return await deleteQuestion(id);
		},
		onError: (error: unknown) => {
			if (error instanceof Error) {
				notifications.show({
					message: error.message,
					color: "red",
				});
			}
		},
		onSuccess: () => {
			notifications.show({
				message: "Question deleted successfully.",
				color: "green",
			});
			queryClient.removeQueries({ queryKey: ["question", questionId] });
			queryClient.invalidateQueries({ queryKey: ["questions"] });
			navigate({ search: {} });
		},
	});

	const isModalOpen = Boolean(searchParams.delete && questionQuery.data);

	return (
		<Modal
			opened={isModalOpen}
			onClose={() => navigate({ search: {} })}
			title={`Delete confirmation`}
		>
			<Text size="sm">
				Are you sure you want to delete question{" "}
				<Text span fw={700}>
					"{questionQuery.data?.question}"
				</Text>
				{" "}? This action is irreversible.
			</Text>

			{/* {errorMessage && <Alert color="red">{errorMessage}</Alert>} */}
			{/* Buttons */}
			<Flex justify="flex-end" align="center" gap="lg" mt="lg">
				<Button
					variant="outline"
					onClick={() => navigate({ search: {} })}
					disabled={mutation.isPending}
				>
					Cancel
				</Button>
				<Button
					variant="subtle"
					// leftSection={<TbDeviceFloppy size={20} />}
					type="submit"
					color="red"
					loading={mutation.isPending}
					onClick={() => mutation.mutate({ id: questionId })}
				>
					Delete Question
				</Button>
			</Flex>
		</Modal>
	);
}
