import { useQuery, useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, redirect } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import { formatInTimeZone } from "date-fns-tz";
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 { opendockApt } from "../../../lib/queries/openDockApt";
import { permissionQuery } from "../../../lib/queries/permsCheck";
import LstTable from "../../../lib/tableStuff/LstTable";
import SearchableHeader from "../../../lib/tableStuff/SearchableHeader";
import SkellyTable from "../../../lib/tableStuff/SkellyTable";

export const Route = createFileRoute("/transportation/opendock/releases")({
	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 OpendockApts = () => {
	const { data, refetch } = useSuspenseQuery(opendockApt());
	const { data: canReadOpenDock = false } = useQuery(
		permissionQuery({
			openDock: ["update"],
		}),
	);

	const columnHelper = createColumnHelper<any>();

	const columns = [
		columnHelper.accessor("release", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Release" searchable={true} />
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor(
			(row) =>
				row.appointment.customFields.find((x: any) => x.label === "Article")
					?.value ?? "",
			{
				id: "article",
				header: ({ column }) => (
					<SearchableHeader column={column} title="Article" searchable={true} />
				),
				filterFn: "includesString",
				cell: (i) => i.getValue(),
			},
		),
		columnHelper.accessor("appointment.status", {
			header: ({ column }) => (
				<SearchableHeader
					column={column}
					title="Current Opendock status"
					searchable={true}
				/>
			),
			filterFn: "includesString",
			cell: (i) => i.getValue(),
		}),
		columnHelper.accessor("upd_date", {
			header: ({ column }) => (
				<SearchableHeader column={column} title="Last Updated" />
			),
			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>;
			},
		}),
	];

	if (canReadOpenDock) {
		columns.push(
			columnHelper.accessor("deleteRelease", {
				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/${i.row.original.id}`,

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

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

							if (!res.data.success) {
								toast.error(
									`Release: ${i.row.original.release} 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 ||
										i.row.original.appointment.status !== "Scheduled"
									}
									onClick={onTrigger}
								>
									{activeToggle ? (
										<span>
											<Spinner />
										</span>
									) : (
										<span>
											<Trash />
										</span>
									)}
								</Button>
							</div>
						</div>
					);
				},
			}),
		);
	}
	return (
		<div>
			<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 />}>
			<OpendockApts />
		</Suspense>
	);
}
