import { useQuery } from "@tanstack/react-query";
import { useNavigate, useRouterState } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import axios from "axios";
import { ArrowDown, ArrowUp } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { useAuth, userAccess } from "@/lib/authClient";
import TableNoExpand from "@/lib/tableStuff/TableNoExpand";
import { getPallets } from "../../-utils/querys/quality/getPallets";

type Pallets = {
	request_id: string;
	article: string;
	description: string;
	runningNr: string;
	lotNr: string;
	warehouseAtRequest: string;
	locationAtRequest: string;
	warehouseMovedTo: string;
	locationMovedTo: string;
	durationToMove: null;
	qualityDurationToInspect: number;
	returnDurationToInspect: number;
	locationDropOff: string;
	palletStatus: number;
	palletStatusText: string;
	palletRequest: number;
	priority: number;
	add_date: Date;
	add_user: string;
	upd_date: Date;
	upd_user: string;
};

export default function QualityRequest() {
	const { data, isLoading, refetch } = useQuery(getPallets());
	const columnHelper = createColumnHelper<Pallets>();
	const { session } = useAuth();
	const navigate = useNavigate();
	const router = useRouterState();
	const currentPath = router.location.href;

	const palletCompleted = async (e: any) => {
		if (!session || !session.user) {
			toast.error("You are allowed to do this unless you are logged in");
			navigate({ to: "/login", search: { redirect: currentPath } });
			return;
		}
		const data = {
			username: session?.user.username,
			runningNr: Number(e.original.runningNr),
			palletStatusText: "return",
		};
		try {
			const res = await axios.post("/lst/old/api/quality/newrequest", data);

			//console.log(res.data);

			if (res.data.success) {
				toast.success(res.data.message);
				refetch();
			}

			if (!res.data.success) {
				toast.error(res.data.message);
			}
		} catch (error) {
			console.log(error);
			toast.error("Encountered and error please try again");
		}
	};

	const columns = [
		columnHelper.accessor("article", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Article</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		columnHelper.accessor("description", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Alias</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		columnHelper.accessor("runningNr", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Running Number</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		columnHelper.accessor("lotNr", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Lot Number</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		columnHelper.accessor("locationAtRequest", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Location At Request</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		columnHelper.accessor("locationDropOff", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Drop off Location</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
			cell: ({ getValue }) => {
				return (
					<>
						<span>{getValue() ? getValue() : "missing dropoff location"}</span>
					</>
				);
			},
		}),
		columnHelper.accessor("palletStatusText", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Pallet Status</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		columnHelper.accessor("palletRequest", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Check Completed</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
			cell: ({ row }) => {
				// if pending
				const okToCompleteStats = [2, 4, 5];
				return (
					<>
						{okToCompleteStats.includes(row.original.palletStatus) ? (
							<Button variant="outline" onClick={() => palletCompleted(row)}>
								Check Complete
							</Button>
						) : (
							<span>Pending to be completed</span>
						)}
					</>
				);
			},
		}),
	];

	let adminColumns: any = [];
	if (userAccess("quality", ["systemAdmin", "admin", "supervisor"])) {
		adminColumns = [
			...columns,
			columnHelper.accessor("priority", {
				header: ({ column }) => {
					return (
						<Button
							variant="ghost"
							onClick={() =>
								column.toggleSorting(column.getIsSorted() === "asc")
							}
						>
							<span className="flex flex-row gap-2">Priority</span>
							{column.getIsSorted() === "asc" ? (
								<ArrowUp className="ml-2 h-4 w-4" />
							) : (
								<ArrowDown className="ml-2 h-4 w-4" />
							)}
						</Button>
					);
				},
				cell: ({ row, getValue }) => {
					// if pending

					const [p, setP] = useState(`${getValue()}`);
					console.log(getValue());
					return (
						<>
							<Select
								value={p}
								onValueChange={async (value) => {
									setP(value);
									const data = {
										username: session?.user.username,
										runningNr: Number(row.original.runningNr),
										priority: value,
									};

									try {
										const res = await axios.post(
											"/lst/old/api/quality/newrequest",
											data,
										);

										//console.log(res.data);

										if (res.data.success) {
											toast.success(res.data.message);
											refetch();
										}

										if (!res.data.success) {
											toast.error(res.data.message);
										}
									} catch (error) {
										console.log(error);
										toast.error("Encountered and error please try again");
									}
								}}
							>
								<SelectTrigger
								// className={cn(
								// 	"w-[100px]",
								// 	active
								// 		? "border-green-500 text-green-600"
								// 		: "border-gray-400 text-gray-500",
								// )}
								>
									<SelectValue />
								</SelectTrigger>
								<SelectContent>
									<SelectItem value="1">Urgent</SelectItem>
									<SelectItem value="2">High</SelectItem>
									<SelectItem value="3">Medium</SelectItem>
									<SelectItem value="4">Low</SelectItem>
								</SelectContent>
							</Select>
						</>
					);
				},
			}),
		];
	}
	if (isLoading) {
		return <div className="m-auto">Loading user data</div>;
	}
	return <TableNoExpand data={data} columns={adminColumns} />;
}
