import { useQuery, useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import { formatInTimeZone } from "date-fns-tz";
import { toast } from "sonner";
import { Button } from "../../../../components/ui/button";
import { useSocketRoom } from "../../../../hooks/socket.io.hook";
import { api } from "../../../../lib/apiHelper";
import { useAppForm } from "../../../../lib/formSutff";
import { getActiveLoadingOrders } from "../../../../lib/queries/getActiveDockScanners";
import { getActiveDockScanners } from "../../../../lib/queries/getActiveLoadingOrders";
import { permissionQuery } from "../../../../lib/queries/permsCheck";
import LstTable from "../../../../lib/tableStuff/LstTable";
import SearchableHeader from "../../../../lib/tableStuff/SearchableHeader";
import { finishLoadingOrder } from "..";

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

function RouteComponent() {
	const { dockScans } = Route.useParams();
	const { data: logs, clearRoom } = useSocketRoom<any>(
		`dockDoorLoading:${dockScans}`,
	);
	const { data, refetch } = useSuspenseQuery(getActiveDockScanners());
	const { data: loadingPlanItems, refetch: refetchActiveLoading } =
		useSuspenseQuery(getActiveLoadingOrders());

	const { data: canReadWarehouse = false } = useQuery(
		permissionQuery({
			warehouse: ["delete"],
		}),
	);
	const columnHelper = createColumnHelper<any>();

	const column = [
		columnHelper.accessor("loadingOrder", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Loading Order" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("loadingUnit", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Loading Unit" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("loadingUnitStatus", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Status" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("message", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Message" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("upd_date", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Scanned At" />
			),
			filterFn: "includesString",
			cell: (i) => {
				function isDateValid(date: any) {
					return date instanceof Date && !isNaN(date.getTime());
				}

				const trueDate = isDateValid(new Date(i.getValue()))
					? formatInTimeZone(
							i.getValue(),
							`${window.LST_CONFIG?.timezone}`,
							"MM/dd/yyyy HH:mm:ss",
						)
					: "invalid time";

				return <span>{trueDate}</span>;
			},
		}),
		columnHelper.accessor("status", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Status" />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
	];

	const form = useAppForm({
		defaultValues: {
			runningNo: "",
			dockId: data[0].dockId,
		},
		onSubmit: async ({ value }) => {
			try {
				const res = await api.post("/dockDoor/loadUnit", value, {
					validateStatus: (status) => status < 500,
				});

				refetchActiveLoading();
				form.reset();
				if (!res.data.success) {
					toast.error(res.data.data.message);
					return;
				}

				toast.success(res.data.message);
			} catch (error) {
				console.log(error);
			}
		},
	});

	const loadingPlan =
		data[0].currentLoadingOrder !== ""
			? loadingPlanItems.filter(
					(x: any) => x.id === Number(data[0].currentLoadingOrder),
				)
			: [];

	return (
		<div>
			<div>
				<p className="text-2xl text-center">
					You are monitoring scans for {data[0].name}
				</p>

				<p className="text-center">
					Current load status:{" "}
					{loadingPlan && loadingPlan.length !== 0 ? (
						<span>
							{loadingPlan[0].loadingPlanItems[0].loadedQuantityLUs} /{" "}
							{loadingPlan[0].loadingPlanItems[0].plannedQuantityLUs}
						</span>
					) : (
						<span>"No active loading orders</span>
					)}
				</p>
			</div>
			<div className="flex flex-col">
				<div>
					<form
						onSubmit={(e) => {
							e.preventDefault();
							form.handleSubmit();
						}}
					>
						<div className="flex flex-row">
							<div className="mb-2 mr-2 max-w-48">
								<form.AppField name="runningNo">
									{(field) => (
										<field.InputField
											label="Running Number"
											inputType="text"
											required={true}
										/>
									)}
								</form.AppField>
							</div>
							<div className="flex justify-end mt-8 mr-3 ">
								<form.AppForm>
									<form.SubmitButton>Submit</form.SubmitButton>
								</form.AppForm>
							</div>
						</div>
					</form>
				</div>
				{loadingPlan && loadingPlan.length > 0 && (
					<div className="flex mb-2 gap-2">
						<Button
							type="button"
							onClick={() => {
								finishLoadingOrder(
									String(data[0].currentLoadingOrder),
									dockScans,
									refetch,
									refetchActiveLoading,
								);
								clearRoom();
							}}
							disabled={
								(loadingPlan && loadingPlan.length < 0) ||
								loadingPlan[0].loadingPlanItems[0].loadedQuantityLUs !==
									loadingPlan[0].loadingPlanItems[0].plannedQuantityLUs
							}
						>
							Finish Loading order
						</Button>
						{canReadWarehouse && (
							<Button onClick={() => clearRoom()}>Clear Table</Button>
						)}
					</div>
				)}
			</div>
			<div>
				<LstTable data={logs} columns={column} pageSize={50} />
			</div>
		</div>
	);
}
