import { n as __toESM } from "../_runtime.mjs";
import { I as require_jsx_runtime } from "../_libs/@radix-ui/react-alert-dialog+[...].mjs";
import { t as PageHeader } from "./page-header-BE1EG5aP.mjs";
import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs";
import { i as CardTitle, n as CardContent, r as CardHeader, t as Card } from "./card-BXjpJ96D.mjs";
import { a as TableHead, n as TableBody, o as TableHeader, r as TableCell, s as TableRow, t as Table } from "./table-BAceZcga.mjs";
import { t as supabase } from "./client-_1GYITl-.mjs";
import { r as useQueryClient } from "../_libs/tanstack__react-query.mjs";
import { n as useItems } from "./data-hooks--e_NaUze.mjs";
import { t as useAuth } from "./use-auth-bumQAdtQ.mjs";
import { t as Badge } from "./badge-D1Dupn2y.mjs";
import { t as Button } from "./button-BLZ6ednA.mjs";
import { t as Input } from "./input-B8Q2ztVi.mjs";
import { a as AlertDialogDescription, c as AlertDialogTitle, i as AlertDialogContent, l as AlertDialogTrigger, n as AlertDialogAction, o as AlertDialogFooter, r as AlertDialogCancel, s as AlertDialogHeader, t as AlertDialog } from "./alert-dialog-DOhnwhih.mjs";
import { n as toast } from "../_libs/sonner.mjs";
//#region node_modules/.nitro/vite/services/ssr/assets/administration-u6pisG7_.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
function Admin() {
	const { data: items = [], refetch } = useItems();
	const { isAdmin, user, roles } = useAuth();
	const qc = useQueryClient();
	const [edits, setEdits] = (0, import_react.useState)({});
	const [savingSr, setSavingSr] = (0, import_react.useState)(null);
	const [clearing, setClearing] = (0, import_react.useState)(false);
	async function saveWeight(sr_no) {
		const raw = edits[sr_no];
		if (raw === void 0) return;
		const val = raw === "" ? null : Number(raw);
		if (val !== null && Number.isNaN(val)) {
			toast.error("Invalid number");
			return;
		}
		setSavingSr(sr_no);
		const { error } = await supabase.from("items_master").update({ weightage: val }).eq("sr_no", sr_no);
		setSavingSr(null);
		if (error) {
			toast.error(error.message);
			return;
		}
		toast.success(`Updated ${sr_no}`);
		setEdits((e) => {
			const n = { ...e };
			delete n[sr_no];
			return n;
		});
		refetch();
	}
	async function clearAllData() {
		setClearing(true);
		try {
			const { error: e1 } = await supabase.from("audit_log").delete().not("id", "is", null);
			if (e1) throw e1;
			const { error: e2 } = await supabase.from("fact_progress").delete().not("id", "is", null);
			if (e2) throw e2;
			const { error: e3 } = await supabase.from("uploads").delete().not("id", "is", null);
			if (e3) throw e3;
			const { data: files } = await supabase.storage.from("aen-uploads").list("", { limit: 1e3 });
			if (files && files.length) {
				const paths = [];
				for (const f of files) if (f.name) {
					const { data: sub } = await supabase.storage.from("aen-uploads").list(f.name, { limit: 1e3 });
					if (sub && sub.length) sub.forEach((s) => paths.push(`${f.name}/${s.name}`));
					else paths.push(f.name);
				}
				if (paths.length) await supabase.storage.from("aen-uploads").remove(paths);
			}
			toast.success("All uploads, facts, and audit logs cleared");
			qc.invalidateQueries();
		} catch (err) {
			toast.error(err.message ?? "Failed to clear data");
		} finally {
			setClearing(false);
		}
	}
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "p-6 max-w-[1400px] mx-auto space-y-6",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageHeader, {
				title: "Administration",
				subtitle: "Manage master data and view role assignments."
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardTitle, { children: "Your account" }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
				className: "text-sm space-y-1",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
						className: "text-muted-foreground",
						children: "Email: "
					}), user?.email] }),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
						className: "text-muted-foreground",
						children: "Roles: "
					}), roles.join(", ") || "—"] }),
					!isAdmin && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "mt-2 text-xs text-muted-foreground",
						children: "Master-data editing is available to HQ Admins."
					})
				]
			})] }),
			isAdmin && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, {
				className: "border-destructive/40",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardTitle, {
					className: "text-destructive",
					children: "Danger zone"
				}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
					className: "flex items-center justify-between gap-4 flex-wrap",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "text-sm text-muted-foreground max-w-2xl",
						children: "Permanently delete all uploaded Excel files, parsed progress facts, and audit log entries. Master data (items, AENs, roles) is preserved."
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialog, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogTrigger, {
						asChild: true,
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
							variant: "destructive",
							disabled: clearing,
							children: clearing ? "Clearing…" : "Clear All Data"
						})
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialogContent, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialogHeader, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogTitle, { children: "Clear all data?" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogDescription, { children: "This deletes every upload, all parsed progress rows, all audit log entries, and every stored Excel file. This cannot be undone." })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(AlertDialogFooter, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogCancel, { children: "Cancel" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AlertDialogAction, {
						onClick: clearAllData,
						className: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
						children: "Yes, clear everything"
					})] })] })] })]
				})]
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardTitle, { children: [
				"Items master (",
				items.length,
				") · risk weightages"
			] }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardContent, {
				className: "p-0",
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
					className: "max-h-[65vh] overflow-auto",
					children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeader, {
						className: "sticky top-0 bg-card z-10",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "Sr No" }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "Item" }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right w-[220px]",
								children: "Weightage"
							})
						] })
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableBody, { children: items.map((i) => {
						const isGroup = i.weightage === null;
						const current = edits[i.sr_no] ?? (i.weightage === null ? "" : String(i.weightage));
						const dirty = edits[i.sr_no] !== void 0 && edits[i.sr_no] !== (i.weightage === null ? "" : String(i.weightage));
						return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								className: "text-xs text-muted-foreground",
								children: i.sr_no
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: i.name }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								className: "text-right",
								children: !isAdmin ? isGroup ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
									className: "text-xs text-muted-foreground",
									children: "group"
								}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, {
									variant: "outline",
									children: i.weightage
								}) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
									className: "flex items-center justify-end gap-2",
									children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
										type: "number",
										step: "0.01",
										className: "h-8 w-24 text-right",
										value: current,
										placeholder: isGroup ? "group" : "",
										onChange: (e) => setEdits((prev) => ({
											...prev,
											[i.sr_no]: e.target.value
										}))
									}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
										size: "sm",
										variant: dirty ? "default" : "outline",
										disabled: !dirty || savingSr === i.sr_no,
										onClick: () => saveWeight(i.sr_no),
										children: savingSr === i.sr_no ? "…" : "Save"
									})]
								})
							})
						] }, i.sr_no);
					}) })] })
				})
			})] })
		]
	});
}
//#endregion
export { Admin as component };
