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 { api } from "../../../../../lib/axiosAPI";

const modules: string[] = [
	"users",
	"system",
	"ocp",
	"siloAdjustments",
	"demandManagement",
	"logistics",
	"helperCommands",
	"production",
	"quality",
	"eom",
	"forklifts",
];

const roles: string[] = [
	"systemAdmin",
	"admin",
	"manager",
	"supervisor",
	"tester",
	"user",
	"viewer",
];

export default function ExpandedRow({ row }: { row: any }) {
	const user = row.original;
	const existingRolesMap = Object.fromEntries(
		(user.roles || []).map((r: { module: string; role: string }) => [
			r.module,
			r.role,
		]),
	);

	// local state for selections
	const [selectedRoles, setSelectedRoles] = useState<Record<string, string>>(
		() =>
			Object.fromEntries(
				modules.map((m) => [m, existingRolesMap[m] || "viewer"]),
			),
	);

	const onSubmitRole = async (module: string) => {
		const role = selectedRoles[module];
		// console.log("Saving module role:", {
		// 	module,
		// 	role,
		// 	user,
		// });
		try {
			const result = await api.patch(`/api/admin/users/${user.id}/grant`, {
				module: module,
				role: role,
			});

			if (result.status === 200) {
				toast.success(
					`${user.username} was just granted ${role} on module ${module}`,
				);
			}
		} catch (error) {
			console.log(error);
			toast.error(
				"There was an error granting the user a role if this continues please contact your admin.",
			);
		}
	};

	const handleSelectChange = (module: string, value: string) => {
		setSelectedRoles((prev) => ({ ...prev, [module]: value }));
	};

	const onDeleteRole = async (module: string) => {
		try {
			const result = await api.patch(`/api/admin/users/${user.id}/revoke`, {
				module: module,
			});

			if (result.status === 200) {
				toast.success(`${user.username} no longer has access to ${module}`);
				setSelectedRoles((prev) => ({ ...prev, [module]: "viewer" }));
			}
		} catch (error) {
			console.log(error);
			toast.error(
				"There was an error granting the user a role if this continues please contact your admin.",
			);
		}
	};

	return (
		<div className="p-4 bg-muted w-128">
			<div className="">
				{modules.map((i) => {
					return (
						<div
							key={i}
							className="flex flex-row items-center justify-between gap-4 border-b py-2"
						>
							<span className="text-sm font-medium capitalize w-40">{i}</span>

							<Select
								value={selectedRoles[i]}
								onValueChange={(v) => handleSelectChange(i, v)}
							>
								<SelectTrigger className="w-40">
									<SelectValue placeholder="Select role" />
								</SelectTrigger>
								<SelectContent>
									{roles.map((r) => (
										<SelectItem key={r} value={r}>
											{r}
										</SelectItem>
									))}
								</SelectContent>
							</Select>

							<Button onClick={() => onSubmitRole(i)} size="sm">
								Grant
							</Button>
							<Button
								onClick={() => onDeleteRole(i)}
								size="sm"
								variant="destructive"
							>
								Revoke
							</Button>
						</div>
					);
				})}
			</div>
		</div>
	);
}
