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 { n as CardContent, 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 { i as useUploads, t as useFactsForUpload } from "./data-hooks--e_NaUze.mjs";
import { t as useAuth } from "./use-auth-bumQAdtQ.mjs";
import { t as Button } from "./button-BLZ6ednA.mjs";
import { t as Input } from "./input-B8Q2ztVi.mjs";
import { n as toast } from "../_libs/sonner.mjs";
import { E as Download, p as Search } from "../_libs/lucide-react.mjs";
import { a as SelectValue, i as SelectTrigger, n as SelectContent, r as SelectItem, t as Select } from "./select-CYB-gyWu.mjs";
import { n as MONTHS } from "./calculations-JyW9rCxF.mjs";
import { n as utils, r as writeFileSync } from "../_libs/xlsx.mjs";
//#region node_modules/.nitro/vite/services/ssr/assets/data-sheets-pkNbMuvv.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
var EDITABLE = [
	"scope_start",
	"new_accrual",
	"cum_scope",
	"progress_month",
	"cum_progress",
	"net_balance"
];
function DataSheets() {
	const { data: uploads = [] } = useUploads();
	const [uploadId, setUploadId] = (0, import_react.useState)();
	const { data: facts = [], isLoading } = useFactsForUpload(uploadId);
	const { isAdmin, user } = useAuth();
	const qc = useQueryClient();
	const [query, setQuery] = (0, import_react.useState)("");
	const [levelFilter, setLevelFilter] = (0, import_react.useState)("all");
	const filtered = (0, import_react.useMemo)(() => {
		const q = query.toLowerCase();
		return facts.filter((r) => {
			if (levelFilter !== "all" && r.level !== levelFilter) return false;
			if (!q) return true;
			return (r.item_name ?? "").toLowerCase().includes(q) || r.item_sr_no.toLowerCase().includes(q) || r.aen.toLowerCase().includes(q) || (r.sse ?? "").toLowerCase().includes(q);
		});
	}, [
		facts,
		query,
		levelFilter
	]);
	const currentUpload = uploads.find((u) => u.id === uploadId);
	const exportXlsx = () => {
		if (!filtered.length) return;
		const sheet = utils.json_to_sheet(filtered.map((r) => ({
			Division: r.division,
			AEN: r.aen,
			SSE: r.sse ?? "",
			Level: r.level,
			"Sr No": r.item_sr_no,
			Item: r.item_name,
			Unit: r.unit,
			"Scope Start": r.scope_start,
			"New Accrual": r.new_accrual,
			"Cum Scope": r.cum_scope,
			"Progress (Month)": r.progress_month,
			"Cum Progress": r.cum_progress,
			"Net Balance": r.net_balance,
			Weightage: r.weightage,
			Month: r.month,
			Year: r.year
		})));
		const wb = utils.book_new();
		utils.book_append_sheet(wb, sheet, "Data");
		writeFileSync(wb, `${currentUpload?.division}_${currentUpload?.year}_${currentUpload?.month}.xlsx`);
	};
	const saveEdit = async (rowId, field, oldVal, newVal) => {
		if (!isAdmin) return toast.error("Only HQ Admins can edit data.");
		if (oldVal === newVal) return;
		const reason = prompt("Reason for change (required):");
		if (!reason) return;
		const { error } = await supabase.from("fact_progress").update({ [field]: newVal }).eq("id", rowId);
		if (error) return toast.error(error.message);
		await supabase.from("audit_log").insert({
			fact_id: rowId,
			user_id: user?.id,
			field_name: field,
			old_value: String(oldVal),
			new_value: String(newVal),
			reason
		});
		toast.success("Saved");
		qc.invalidateQueries();
	};
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "p-6 max-w-[1600px] mx-auto",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageHeader, {
				title: "Division Data Sheets",
				subtitle: "View and edit uploaded records. Every edit is logged with reason.",
				right: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					variant: "outline",
					onClick: exportXlsx,
					disabled: !filtered.length,
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Download, { className: "h-4 w-4 mr-2" }), "Export"]
				})
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, {
				className: "mb-4",
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
					className: "p-4 grid grid-cols-1 md:grid-cols-4 gap-3",
					children: [
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Select, {
							value: uploadId,
							onValueChange: setUploadId,
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectValue, { placeholder: "Select an upload…" }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectContent, { children: uploads.map((u) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectItem, {
								value: u.id,
								children: [
									u.division,
									" · ",
									MONTHS[u.month - 1].label,
									" ",
									u.year
								]
							}, u.id)) })]
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Select, {
							value: levelFilter,
							onValueChange: (v) => setLevelFilter(v),
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectValue, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectContent, { children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "all",
									children: "All levels"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "AEN",
									children: "AEN totals only"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "SSE",
									children: "SSE rows only"
								})
							] })]
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "relative md:col-span-2",
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
								value: query,
								onChange: (e) => setQuery(e.target.value),
								placeholder: "Search item, AEN, SSE…",
								className: "pl-9"
							})]
						})
					]
				})
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardContent, {
				className: "p-0",
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
					className: "overflow-x-auto max-h-[70vh]",
					children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeader, {
						className: "sticky top-0 z-10 bg-card",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "sticky left-0 bg-card z-20",
								children: "Item"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "Level" }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "AEN" }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "SSE" }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "Scope"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "New Accr."
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "Cum Scope"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "Progress"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "Cum Progress"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "Net Bal."
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
								className: "text-right",
								children: "Weight"
							})
						] })
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableBody, { children: [
						isLoading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
							colSpan: 11,
							className: "text-center py-8 text-sm text-muted-foreground",
							children: "Loading…"
						}) }),
						!isLoading && !uploadId && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
							colSpan: 11,
							className: "text-center py-8 text-sm text-muted-foreground",
							children: "Select an upload above."
						}) }),
						!isLoading && uploadId && filtered.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
							colSpan: 11,
							className: "text-center py-8 text-sm text-muted-foreground",
							children: "No matching rows."
						}) }),
						filtered.map((r) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
							/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableCell, {
								className: "sticky left-0 bg-card z-10 max-w-[280px]",
								children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
									className: "text-xs text-muted-foreground",
									children: r.item_sr_no
								}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
									className: "truncate",
									children: r.item_name
								})]
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
								className: `text-xs rounded px-1.5 py-0.5 ${r.level === "AEN" ? "bg-primary/10 text-primary" : "bg-muted"}`,
								children: r.level
							}) }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								className: "text-sm",
								children: r.aen
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								className: "text-sm text-muted-foreground",
								children: r.sse ?? "—"
							}),
							EDITABLE.map((f) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								className: "text-right",
								children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditableNumber, {
									value: r[f],
									editable: isAdmin,
									onSave: (v) => saveEdit(r.id, f, r[f], v)
								})
							}, f)),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								className: "text-right text-xs text-muted-foreground",
								children: r.weightage ?? "—"
							})
						] }, r.id))
					] })] })
				})
			}) })
		]
	});
}
function EditableNumber({ value, editable, onSave }) {
	const [v, setV] = (0, import_react.useState)(String(value));
	const [editing, setEditing] = (0, import_react.useState)(false);
	if (!editable) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: value });
	return editing ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", {
		autoFocus: true,
		type: "number",
		value: v,
		onChange: (e) => setV(e.target.value),
		onBlur: () => {
			setEditing(false);
			const n = Number(v);
			if (!Number.isNaN(n)) onSave(n);
		},
		onKeyDown: (e) => {
			if (e.key === "Enter") e.target.blur();
			if (e.key === "Escape") {
				setV(String(value));
				setEditing(false);
			}
		},
		className: "w-20 text-right bg-background border rounded px-1 py-0.5 text-sm"
	}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
		className: "hover:bg-muted rounded px-1 -mx-1",
		onClick: () => {
			setV(String(value));
			setEditing(true);
		},
		children: value
	});
}
//#endregion
export { DataSheets as component };
