import { useState } from "react";
import { assessmentRequestQueryOptions } from "@/modules/assessmentRequest/queries/assessmentRequestQueries";
import PageTemplate from "@/components/PageTemplate";
import { createLazyFileRoute } from "@tanstack/react-router";
import FormModal from "@/modules/assessmentRequest/modals/CreateAssessmentRequestModal";
import ExtractQueryDataType from "@/types/ExtractQueryDataType";
import { createColumnHelper } from "@tanstack/react-table";
import { Badge } from "@/shadcn/components/ui/badge";
import { Button } from "@/shadcn/components/ui/button";
import StartAssessmentModal from "@/modules/assessmentRequest/modals/ConfirmModal";

export const Route = createLazyFileRoute("/_dashboardLayout/assessmentRequest/")({
	component: UsersPage,
});

type DataType = ExtractQueryDataType<typeof assessmentRequestQueryOptions>;

const columnHelper = createColumnHelper<DataType>();

export default function UsersPage() {
	const [modalOpen, setModalOpen] = useState(false);
	const [selectedAssessmentId, setSelectedAssessmentId] = useState<string | null>(null);

	/**
	 * Function to open confirmation modal to start assessment
	 * @param {string} assessmentId ID of the assessment to be started
	 */
	const handleOpenModal = (assessmentId: string) => {
		if (!assessmentId) {
			console.error("Assessment ID is missing");
			return;
		  }
		
		setSelectedAssessmentId(assessmentId);
		setModalOpen(true);
	};

	/**
	 * Function to open assessment page in new tab
	 * @param {string} assessmentId ID of the assessment to be opened
	 */
	const handleStartAssessment = (assessmentId: string) => {
		// Redirect to new URL in new tab
		const assessmentUrl = `/assessment?id=${assessmentId}`;
		window.open(assessmentUrl, "_blank");
		setModalOpen(false);
	};

	/**
	 * Function to open assessment result page based on valid ID
	 * Used when "View Result" button is clicked
	 * @param {string} assessmentId ID of the assessment to be opened
	 */
	const handleViewResult = (assessmentId: string) => {
		// to make sure assessmentId is valid and not null
		if (!assessmentId) {
			console.error("Assessment ID is missing");
			return;
		}
		const resultUrl = `/assessmentResult?id=${assessmentId}`;
		window.location.href = resultUrl;
	  };
	  

	return (
		<>
			<PageTemplate
				title="Permohonan Asesmen"
				queryOptions={assessmentRequestQueryOptions}
				modals={[<FormModal />]}
				columnDefs={[
					columnHelper.display({
						header: "No",
						cell: (props) => props.row.index + 1,
					}),
					columnHelper.display({
						header: "Tanggal",
						cell: (props) =>
							props.row.original.tanggal
								? new Intl.DateTimeFormat("ID", {
										year: "numeric",
										month: "long",
										day: "2-digit",
										hour: "2-digit",
										minute: "2-digit",
										hour12: true,
								  }).format(new Date(props.row.original.tanggal))
								: 'N/A',
					}),
					columnHelper.display({
						header: "Status",
						cell: (props) => {
							const status = props.row.original.status;
							switch (status) {
								case "menunggu konfirmasi":
									return <Badge variant={"waiting"}>Menunggu Konfirmasi</Badge>;
								case "diterima":
									return <Badge variant={"accepted"}>Diterima</Badge>;
								case "ditolak":
									return <Badge variant={"rejected"}>Ditolak</Badge>;
								case "selesai":
									return <Badge variant={"completed"}>Selesai</Badge>;
								default:
									return <Badge variant={"outline"}>Tidak diketahui</Badge>;
							}
						},
					}),
					columnHelper.display({
						header: "Actions",
						cell: (props) => {
							const status = props.row.original.status;
							const assessmentId = props.row.original.assessmentId; // Retrieve the assessmentId from the data row

							return (
								<div className="flex gap-2">
									{/* Button Create Assessment */}
									{status === "selesai" ? (
										<Button variant={"secondary"} disabled>Mulai Asesmen</Button>
									) : status === "diterima" ? (
										<Button 
											onClick={() => handleOpenModal(assessmentId ?? '')}
										>
											Mulai Asesmen
										</Button>
									) : (
										<Button variant={"secondary"} disabled>Mulai Asesmen</Button>
									)}

									{/* Button View Result */}
									{status === "selesai" ? (
										<Button variant={"outline"} onClick={()=>handleViewResult(assessmentId ?? '')}>Lihat Hasil</Button>
									) : (
										<Button variant={"outline"} disabled>Lihat Hasil</Button>
									)}
								</div>
							);
						},
					}),
				]}
			/>
			
			{/* Confirmation Modal to Start Assessment */}
			{selectedAssessmentId && (
				<StartAssessmentModal
					assessmentId={selectedAssessmentId}
					isOpen={modalOpen}
					onClose={() => setModalOpen(false)}
					onConfirm={handleStartAssessment}
				/>
			)}
		</>
	);
}
