import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardHeader,
} from "../../../components/ui/card";
import { api } from "../../../lib/apiHelper";
import { getActiveLoadingOrders } from "../../../lib/queries/getActiveDockScanners";
import { getActiveDockScanners } from "../../../lib/queries/getActiveLoadingOrders";

export const Route = createFileRoute("/warehouse/dockdoorscanning/")({
	component: RouteComponent,
});

export const finishLoadingOrder = async (
	loadingOrder: string,
	dockId: string,
	refetch: any,
	refetchActiveLoading: any,
	clear?: boolean,
) => {
	try {
		const res = await api.post(
			"/dockDoor/finishOrder",
			{
				loadingOrder: loadingOrder,
				dockId: dockId,
				clear,
			},
			{ validateStatus: (status) => status < 500 },
		);

		if (!res.data.success) {
			toast.error(res.data.message);
			refetch();
			refetchActiveLoading();
			return;
		}
		toast.info(res.data.message);
		refetch();
		refetchActiveLoading();
	} catch (error) {
		console.log(error);
		toast.error(`Encountered error: ${JSON.stringify(error)}`);
	}
};

function RouteComponent() {
	const { data, isLoading, refetch } = useSuspenseQuery(
		getActiveDockScanners(),
	);
	const { data: loadingPlanItems, refetch: refetchActiveLoading } =
		useSuspenseQuery(getActiveLoadingOrders());
	const navigate = useNavigate();

	if (isLoading) {
		return (
			<div className="flex justify-center-safe">
				<p>Loading active dock scanners....</p>
			</div>
		);
	}

	return (
		<div className="flex flex-col ">
			<div className="flex justify-center-safe">
				<p className="text-2xl underline">
					Select a dock you would like to work with
				</p>
			</div>
			<div className="flex justify-center gap-3 mt-5">
				{!isLoading &&
					data.length > 0 &&
					data.map((i: any) => {
						const loadingPlan =
							i.currentLoadingOrder !== ""
								? loadingPlanItems.filter(
										(x: any) => x.id === Number(i.currentLoadingOrder),
									)
								: [];
						// console.log(loadingPlan);
						// console.log(loadingPlanItems);
						return (
							<Card
								key={i.id}
								className="max-w-96"
								onClick={() => {
									if (i.currentLoadingOrder === "") {
										navigate({
											to: "/warehouse/dockdoorscanning/$dock",
											params: { dock: i.dockId },
											search: {
												name: i.name,
											},
										});
									}
								}}
							>
								<CardHeader className="text-center">{i.name}</CardHeader>
								<CardDescription>
									For Abbott loads reminder: 3 lots per load max.
								</CardDescription>

								{i.currentLoadingOrder !== "" ? (
									<CardContent>
										<div className="flex flex-col gap-2">
											Current loading order: {i.currentLoadingOrder}
										</div>

										<div>
											{loadingPlan && loadingPlan.length !== 0 ? (
												<>
													<p>{`${loadingPlan[0].loadingPlanItems[0].articleId} - ${loadingPlan[0].loadingPlanItems[0].articleDescription}`}</p>
													<p>
														Current Loaded :{" "}
														{
															loadingPlan[0].loadingPlanItems[0]
																.loadedQuantityLUs
														}{" "}
														/{" "}
														{
															loadingPlan[0].loadingPlanItems[0]
																.plannedQuantityLUs
														}
													</p>
													Check Scans:{" "}
													<Link
														to={"/warehouse/dockdoorscanning/scans/$dockScans"}
														params={{ dockScans: i.dockId }}
														className="underline"
													>
														CLICK HERE
													</Link>
												</>
											) : (
												<>
													<p>The Current Loading order is invalid</p>
													<p>
														{" "}
														It appears it could have been finished via another
														process
													</p>
													<div className="m-2 flex justify-center">
														<Button
															onClick={() =>
																finishLoadingOrder(
																	i.currentLoadingOrder,
																	i.dockId,
																	refetch,
																	refetchActiveLoading,
																	true,
																)
															}
														>
															Clear {i.currentLoadingOrder}
														</Button>
													</div>
												</>
											)}
										</div>
									</CardContent>
								) : (
									<CardContent>
										No active loading orders please click me to select an order
									</CardContent>
								)}
							</Card>
						);
					})}
			</div>
		</div>
	);
}
