import {
	Flex,
	Modal,
	Text
} from "@mantine/core";
import { Button } from "@/shadcn/components/ui/button";
import { useForm } from "@mantine/form";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getRouteApi } from "@tanstack/react-router";
import { useEffect } from "react";
import { notifications } from "@mantine/notifications";
import FormResponseError from "@/errors/FormResponseError";
import createInputComponents from "@/utils/createInputComponents";
import { assessmentRequestQueryOptions, createAssessmentRequest } from "../queries/assessmentRequestQueries";

/**
 * Change this
 */
const routeApi = getRouteApi("/_dashboardLayout/assessmentRequest/");

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

	const navigate = routeApi.useNavigate();

	const searchParams = routeApi.useSearch();

	const isModalOpen = Boolean(searchParams.create);

	const formType = "create";

	const userQuery = useQuery(assessmentRequestQueryOptions(0, 10));

	const modalTitle = <b>Konfirmasi</b>

	
	const form = useForm({
		initialValues: {
			respondentsId: "",
			name: "",
		},
	});

	// used to get the respondentId of the currently logged in user
	// and then set respondentsId in the form to create an assessment request
	useEffect(() => {
		const data = userQuery.data;

		if (!data) {
			form.reset();
			return;
		}

		form.setValues({
			respondentsId: data.data[0].respondentId ?? "",
			name: data.data[0].name ?? "",
		});

		form.setErrors({});
	}, [userQuery.data]);

	// Mutation function to create a new assessment request and refresh query after success
	const mutation = useMutation({
		mutationKey: ["usersMutation"],
		mutationFn: async (options: { action: "create"; data: { respondentsId: string } }) => {
		console.log("called");
		  if (options.action === "create") {
			return await createAssessmentRequest(options.data);
		  }
		},
		// auto refresh after mutation
		onSuccess: () => {
			// force a query-reaction to retrieve the latest data
			queryClient.invalidateQueries({ queryKey: ["assessmentRequest"] });
		
			notifications.show({
			  message: "Permohonan Asesmen berhasil dibuat!",
			  color: "green",
			});
		
			// close modal
			navigate({ search: {} });
		  },
		onError: (error: unknown) => {
		  console.log(error);
	  
		  if (error instanceof FormResponseError) {
			form.setErrors(error.formErrors);
			return;
		  }
	  
		  if (error instanceof Error) {
			notifications.show({
			  message: error.message,
			  color: "red",
			});
		  }
		},
	  });
	  
	// Handle submit form, mutate data to server and close modal after success
	  const handleSubmit = async (values: typeof form.values) => {
	  
		if (formType === "create") {
		  try {
			await mutation.mutateAsync({
			  action: "create",
			  data: {
				respondentsId: values.respondentsId,
			  },
			});
		  } catch (error) {
			console.error(error);
		  }
		}
	  
		queryClient.invalidateQueries({ queryKey: ["users"] });
		navigate({ search: {} });
	  };
	  

	return (
		<Modal
			opened={isModalOpen}
			onClose={() => navigate({ search: {} })}
			title= {modalTitle} 
			size="md"
		>	
			<form onSubmit={form.onSubmit((values) => handleSubmit(values))}>

				<Text>Apakah anda yakin ingin membuat Permohonan Asesmen Baru?</Text>

				{/* Fields to display data will be sent but only respondentId  */}
				{createInputComponents({
					disableAll: mutation.isPending,
					readonlyAll: formType === "create",
					inputs: [
						{
							type: "text",
							label: "Respondent ID",
							...form.getInputProps("respondentsId"),
							hidden: true,	
						},
						{
							type: "text",
							label: "Name",
							...form.getInputProps("name"),
							hidden: true,
						},
					],
				})}

				{/* Buttons */}
				<Flex justify="flex-end" align="center" gap="sm" mt="lg">
					<Button
						variant="outline"
						type="button"
						onClick={() => navigate({ search: {} })}
						disabled={mutation.isPending}
					>
						Tidak
					</Button>
						<Button
							type="submit"
							isLoading={mutation.isPending}
						>
							Buat Permohonan
						</Button>
				</Flex>
			</form>
		</Modal>
	);
}
