import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import { Trash } from "lucide-react";
import { Suspense, useState } from "react";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
import { Spinner } from "../../../components/ui/spinner";
import { api } from "../../../lib/apiHelper";
import { authClient } from "../../../lib/auth-client";
import { getArticleLinks } from "../../../lib/queries/getArticleLinks";
import LstTable from "../../../lib/tableStuff/LstTable";
import SearchableHeader from "../../../lib/tableStuff/SearchableHeader";
import SkellyTable from "../../../lib/tableStuff/SkellyTable";
import NewArticleLink from "./-components/NewArticleLink";

export const Route = createFileRoute("/transportation/opendock/")({
	beforeLoad: async ({ location }) => {
		const { data: session } = await authClient.getSession();
		//const allowedRole = ["systemAdmin", "admin", "manager"];

		const canAccess = await authClient.admin.hasPermission({
			permissions: {
				openDock: ["create"],
			},
		});

		if (!session?.user) {
			throw redirect({
				to: "/",
				search: {
					redirect: location.href,
				},
			});
		}

		//if (!allowedRole.includes(session.user.role as string)) {

		if (!canAccess) {
			throw redirect({
				to: "/",
			});
		}

		return { user: session.user };
	},
	component: RouteComponent,
});

const ArticleLinkTable = () => {
	const { data, refetch } = useSuspenseQuery(getArticleLinks());

	const columnHelper = createColumnHelper<any>();

	const columns = [
		columnHelper.accessor("av", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Article" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("description", {
			header: ({ column }) => (
				<SearchableHeader
					column={column}
					title="Description"
					searchable={true}
				/>
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("customer", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Customer" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => (
				<span>
					{i.row.original.customer} - {i.row.original.customerDescription}
				</span>
			),
		}),
		columnHelper.accessor("loadType", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Load Type" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("dock", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Dock" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("deleteUser", {
			header: ({ column }) => (
				<SearchableHeader
					column={column}
					title="Delete Link"
					searchable={false}
				/>
			),
			filterFn: "includesString",
			cell: (i) => {
				// biome-ignore lint: just removing the lint for now to get this going will maybe fix later
				const [activeToggle, setActiveToggle] = useState(false);

				const onTrigger = async () => {
					setActiveToggle(true);

					try {
						const res = await api.delete(
							`/opendock/articleCheck/${i.row.original.id}`,

							{
								withCredentials: true,
								timeout: 5000,
								validateStatus: () => true,
							},
						);

						if (res.data.success) {
							toast.success(`AV: ${i.row.original.av} was deleted.`);
							refetch();
							setActiveToggle(false);
						}

						if (!res.data.success) {
							toast.error(
								`AV: ${i.row.original.av} encountered an error when trying to delete: ${res.data.message}`,
							);
							refetch();
							setActiveToggle(false);
						}
					} catch (error) {
						setActiveToggle(false);
						console.error(error);
					}
				};

				return (
					<div>
						<div className="flex items-center space-x-2">
							<Button
								variant="destructive"
								disabled={activeToggle}
								onClick={onTrigger}
							>
								{activeToggle ? (
									<span>
										<Spinner />
									</span>
								) : (
									<span>
										<Trash />
									</span>
								)}
							</Button>
						</div>
					</div>
				);
			},
		}),
	];
	return (
		<div className="">
			<div>
				<div className="flex justify-end m-2">
					<Suspense
						fallback={
							<div>
								<p>Loading...</p>
							</div>
						}
					>
						<NewArticleLink refetch={refetch} />
					</Suspense>
				</div>
				<div>
					<LstTable data={data} columns={columns} pageSize={50} />
				</div>
			</div>
		</div>
	);
};
function RouteComponent() {
	return (
		<Suspense fallback={<SkellyTable />}>
			<ArticleLinkTable />
		</Suspense>
	);
}
