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, Trash2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
	Select,
	SelectContent,
	SelectGroup,
	SelectItem,
	SelectLabel,
	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;
	palletComplete: string;
	canceled: 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("locationMovedTo", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Location Moved to</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() === "" ? "Pending Move" : getValue()}</span>;
			},
		}),
		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("palletComplete", {
			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 [p, setP] = useState(`${getValue()}`);
				const okToCompleteStats = [2, 4, 5];
				return (
					<>
						{okToCompleteStats.includes(row.original.palletStatus) ? (
							<Select
								//value={"return to warehouse"}
								onValueChange={async (value) => {
									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(row.original.runningNr),
										palletStatusText: 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 placeholder="Complete Selection" />
								</SelectTrigger>
								<SelectContent>
									<SelectGroup>
										<SelectLabel>Location to drop off</SelectLabel>
										<SelectItem value="return to warehouse">
											Return to Warehouse
										</SelectItem>
										<SelectItem value="rework">Rework</SelectItem>
										<SelectItem value="grind">Grind</SelectItem>
										<SelectItem value="scrap">Scrap</SelectItem>
									</SelectGroup>
								</SelectContent>
							</Select>
						) : (
							<span>Pending move</span>
						)}
					</>
				);
			},
		}),
	];

	let adminColumns: any = [];
	if (
		userAccess("quality", ["systemAdmin", "admin", "supervisor", "manager"])
	) {
		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()}`);
					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>
						</>
					);
				},
			}),
			columnHelper.accessor("palletComplete", {
				header: ({ column }) => {
					return (
						<Button
							variant="ghost"
							onClick={() =>
								column.toggleSorting(column.getIsSorted() === "asc")
							}
						>
							<span className="flex flex-row gap-2">Cancel</span>
							{column.getIsSorted() === "asc" ? (
								<ArrowUp className="ml-2 h-4 w-4" />
							) : (
								<ArrowDown className="ml-2 h-4 w-4" />
							)}
						</Button>
					);
				},
				cell: ({ row }) => {
					return (
						<>
							<Button
								//value={"return to warehouse"}
								variant="destructive"
								onClick={async () => {
									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(row.original.runningNr),
										palletStatusText: "canceled",
									};

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

										//console.log(res.data);

										if (res.data.success) {
											toast.success(
												`${row.original.runningNr} was just canceled`,
											);
											refetch();
										}

										if (!res.data.success) {
											toast.error(res.data.message);
										}
									} catch (error) {
										console.log(error);
										toast.error("Encountered and error please try again");
									}
								}}
							>
								<Trash2 className="w-[24px] h-[24px]" />
							</Button>
						</>
					);
				},
			}),
		];
	}
	if (isLoading) {
		return <div className="m-auto">Loading user data</div>;
	}
	return <TableNoExpand data={data} columns={adminColumns} />;
}
