import { Button, Flex, Modal, ScrollArea } from "@mantine/core";
import { useForm } from "@mantine/form";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { getRouteApi } from "@tanstack/react-router";
import { notifications } from "@mantine/notifications";
import { fetchAssessmentRequestManagementById, updateAssessmentRequestManagementStatus } from "../queries/assessmentRequestManagementQueries";
import createInputComponents from "@/utils/createInputComponents"; // Assuming you have this utility
import { useEffect } from "react";

// Define the API route for navigation
const routeApi = getRouteApi("/_dashboardLayout/assessmentRequestManagements/");

// Define allowed status values
type AssessmentStatus = "menunggu konfirmasi" | "diterima" | "ditolak" | "selesai";

interface AssessmentRequestManagementFormModalProps {
	assessmentId: string | null;
	isOpen: boolean;
	onClose: () => void;
}

export default function AssessmentRequestManagementFormModal({
	assessmentId,
	isOpen,
	onClose,
}: AssessmentRequestManagementFormModalProps) {
	const queryClient = useQueryClient();
	const navigate = routeApi.useNavigate();

	const AssessmentRequestManagementQuery = useQuery({
		queryKey: ["assessmentRequestManagements", assessmentId],
		queryFn: async () => {
			if (!assessmentId) return null;
			return await fetchAssessmentRequestManagementById(assessmentId);
		},
	});

	const form = useForm({
		initialValues: {
			tanggal: "",
			nama: "",
			posisi: "",
			pengalamanKerja: "",
			email: "",
			namaPerusahaan: "",
			alamat: "",
			nomorTelepon: "",
			username: "",
			status: "menunggu konfirmasi" as AssessmentStatus,
		},
	});

	// Populate the form once data is available
	useEffect(() => {
		if (AssessmentRequestManagementQuery.data) {
			form.setValues({
				tanggal: formatDate(AssessmentRequestManagementQuery.data.tanggal || "Data Kosong"),
				nama: AssessmentRequestManagementQuery.data.nama || "Data Kosong",
				posisi: AssessmentRequestManagementQuery.data.posisi || "Data Kosong",
				pengalamanKerja: AssessmentRequestManagementQuery.data.pengalamanKerja || "Data Kosong",
				email: AssessmentRequestManagementQuery.data.email || "Data Kosong",
				namaPerusahaan: AssessmentRequestManagementQuery.data.namaPerusahaan || "Data Kosong",
				alamat: AssessmentRequestManagementQuery.data.alamat || "Data Kosong",
				nomorTelepon: AssessmentRequestManagementQuery.data.nomorTelepon || "Data Kosong",
				username: AssessmentRequestManagementQuery.data.username || "Data Kosong",
				status: AssessmentRequestManagementQuery.data.status || "menunggu konfirmasi",
			});
		}
	}, [AssessmentRequestManagementQuery.data, form]);

	const mutation = useMutation({
		mutationKey: ["updateAssessmentRequestManagementStatusMutation"],
		mutationFn: async ({
			id,
			status,
		}: {
			id: string;
			status: AssessmentStatus;
		}) => {
			return await updateAssessmentRequestManagementStatus(id, status);
		},
		onError: (error: unknown) => {
			if (error instanceof Error) {
				notifications.show({
					message: error.message,
					color: "red",
				});
			}
		},
		onSuccess: () => {
			notifications.show({
				message: "Status Permohonan Asesmen berhasil diperbarui.",
				color: "green",
			});
			queryClient.invalidateQueries({
				queryKey: ["assessmentRequestManagements", assessmentId],
			});
			onClose();
		},
	});

	const handleStatusChange = (status: AssessmentStatus) => {
		if (assessmentId) {
			mutation.mutate({ id: assessmentId, status });
		}
	};

	const formatDate = (dateString: string | null) => {
		if (!dateString) return "Tanggal tidak tersedia";

		const date = new Date(dateString);
		if (isNaN(date.getTime())) return "Tanggal tidak valid";

		return new Intl.DateTimeFormat("id-ID", {
			hour12: true,
			minute: "2-digit",
			hour: "2-digit",
			day: "2-digit",
			month: "long",
			year: "numeric",
		}).format(date);
	};

	const { status } = form.values;

	return (
		<Modal opened={isOpen} onClose={onClose} title="Detail Permohonan Asesmen">
			<ScrollArea style={{ height: "400px", paddingRight: "15px" }} scrollbarSize={8}>
				{createInputComponents({
					disableAll: mutation.isPending,
					readonlyAll: true,
					inputs: [
						{
							type: "text",
							label: "Tanggal",
							...form.getInputProps("tanggal"),
						},
						{
							type: "text",
							label: "Nama",
							...form.getInputProps("nama"),
						},
						{
							type: "text",
							label: "Posisi",
							...form.getInputProps("posisi"),
						},
						{
							type: "text",
							label: "Pengalaman Kerja",
							...form.getInputProps("pengalamanKerja"),
						},
						{
							type: "text",
							label: "Email",
							...form.getInputProps("email"),
						},
						{
							type: "text",
							label: "Nama Perusahaan",
							...form.getInputProps("namaPerusahaan"),
						},
						{
							type: "text",
							label: "Alamat",
							...form.getInputProps("alamat"),
						},
						{
							type: "text",
							label: "Nomor Telepon",
							...form.getInputProps("nomorTelepon"),
						},
						{
							type: "text",
							label: "Username",
							...form.getInputProps("username"),
						},
						{
							type: "text",
							label: "Status",
							...form.getInputProps("status"),
						},
					],
				})}

				<Flex justify="flex-end" align="center" gap="lg" mt="lg">
					<Button variant="outline" onClick={onClose} disabled={mutation.isPending}>
						Tutup
					</Button>
					{status !== "selesai" && (
						<>
							<Button
								variant="filled"
								color="red"
								onClick={() => handleStatusChange("ditolak")}
								disabled={mutation.isPending}
							>
								Tolak
							</Button>
							<Button
								variant="filled"
								color="blue"
								onClick={() => handleStatusChange("diterima")}
								disabled={mutation.isPending}
							>
								Terima
							</Button>
						</>
					)}
				</Flex>
			</ScrollArea>
		</Modal>
	);
}
