import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { format } from "date-fns";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardFooter,
	CardHeader,
} from "../../../components/ui/card";
import { Separator } from "../../../components/ui/separator";
import { api } from "../../../lib/apiHelper";
import { getActiveLoadingOrders } from "../../../lib/queries/getActiveDockScanners";
import { getActiveDockScanners } from "../../../lib/queries/getActiveLoadingOrders";
import { finishLoadingOrder } from "./index";

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

export const startOrder = async (
	loadingOrder: string,
	dockId: string,
	refetch: any,
	refetchActiveLoading: any,
) => {
	try {
		const res = await api.post(
			"/dockDoor/startLoad",
			{
				loadingOrder: String(loadingOrder),
				dockId: dockId,
			},
			{ validateStatus: (status) => status < 500 },
		);

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

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

	const dockData = data.filter((i: any) => i.dockId === dock);
	const loadingPlans = loadingPlanItems.filter(
		(l: any) => l.dockId === Number(dock),
	);

	return (
		<div className="flex flex-col">
			<div className="flex justify-center">
				<p>Please select an active loading order for {dockData[0].name}</p>
			</div>
			<div className="flex justify-center mt-5 gap-2">
				{loadingPlans && loadingPlans.length > 0 ? (
					<div>
						{loadingPlans.map((i: any) => {
							return (
								<Card key={i.id} className="max-w-96">
									<CardHeader>
										Loading order ID: {i.id}{" "}
										<p>
											Loading Date: {format(i.loadingDate, "MM/dd/yyyy HH:mm")}
										</p>
									</CardHeader>
									<CardDescription className="">
										<p className="p-3">
											Below are the loading order details please validate the
											loading order you are selecting before pressing start.
										</p>
									</CardDescription>
									{/* Mapping the items out so in case we have more than 1 it will display correctly */}
									<CardContent>
										{i?.loadingPlanItems?.map((l: any) => {
											return (
												<div key={i.id}>
													<p>Loading Sequence {l.loadingSequence}</p>
													<p>
														Article: {l.articleId} - {l.articleDescription}
													</p>
													<p>
														Current loaded: {l.loadedQuantityLUs}/
														{l.plannedQuantityLUs}
													</p>
													{l.remark !== "" && <p>Remark: {l.remark}</p>}

													{i?.loadingPlanItems.length > 1 && (
														<Separator className="m-2" />
													)}
												</div>
											);
										})}
									</CardContent>
									<CardFooter>
										<div className="flex flex-row justify-between">
											<Button
												onClick={() =>
													startOrder(i.id, dock, refetch, refetchActiveLoading)
												}
												disabled={
													dockData[0].currentLoadingOrder !== "" ? true : false
												}
											>
												Start Loading
											</Button>
											<Button
												onClick={() =>
													navigate({
														to: "/warehouse/dockdoorscanning/scans/$dockScans",
														params: { dockScans: dock },
													})
												}
											>
												Scan progress
											</Button>
											<Button
												onClick={() =>
													finishLoadingOrder(
														String(i.id),
														dock,
														refetch,
														refetchActiveLoading,
													)
												}
												disabled={
													dockData[0].currentLoadingOrder === "" ? true : false
												}
											>
												Finish Loading
											</Button>
										</div>
									</CardFooter>
								</Card>
							);
						})}
					</div>
				) : (
					<div>
						<p>There are know loading orders currently active.</p>
						<p>
							Head over to Outbound deliveries to create a loading order to
							start the flow
						</p>
					</div>
				)}
			</div>
		</div>
	);
}
