import { useState, useMemo } from "react"; import { useParams, Link } from "react-router-dom"; import { useQuery } from "@tanstack/react-query"; import type { ColumnDef } from "@tanstack/react-table"; import { ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, } from "recharts"; import { ArrowLeft, FileSpreadsheet, Printer, HelpCircle, AlertCircle, Lock, RotateCcw, Filter, } from "lucide-react"; import { REPORT_CATALOG, fetchReport, exportReport, type ReportKey, type ReportFilterParams, } from "@/api/reports"; import { departmentsApi, vendorsApi } from "@/api/masters"; import { ApiError } from "@/api/client"; import { useAuthStore } from "@/hooks/useAuth"; import { formatDateTime } from "@/lib/format"; import { DataTable } from "@/components/DataTable"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { cn } from "@/lib/utils"; import { toast } from "@/lib/toast"; function currentMonthStr(): string { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; } function humanizeSummaryKey(key: string): string { const SPECIAL: Record = { total_assets: "Total Assets", total_complaints: "Total Complaints", total_downtime_minutes: "Downtime (Mins)", downtime_formatted: "Total Downtime", downtime_days_count: "Distinct Downtime Days", total_scheduled_minutes: "Scheduled Mins", total_uptime_minutes: "Uptime (Mins)", uptime_formatted: "Total Uptime", downtime_pct: "Downtime %", downtime_vs_uptime_pct: "Downtime vs Uptime %", scheduled_hours_per_day: "Scheduled Hrs/Day", downtime_end_milestone: "Downtime Milestone", departments_count: "Departments", total_under_repair: "Under Repair", total_outstanding_complaints: "Outstanding Complaints", total_visits: "Total Visits", departments_visited: "Departments Visited", total_equipment_checked: "Equipment Checked", linked_complaints_count: "Linked Complaints", open_count: "Open", in_progress_count: "In Progress", closed_count: "Closed", critical_count: "Critical", avg_response_minutes: "Avg Response (Mins)", planned_count: "Planned", completed_count: "Completed", upcoming_count: "Upcoming", due_count: "Due", overdue_count: "Overdue", rescheduled_count: "Rescheduled", compliance_pct: "Compliance %", total_records: "Total Records", active_contracts: "Active Contracts", expiring_contracts: "Expiring Contracts", expired_contracts: "Expired Contracts", active_warranties: "Active Warranties", expiring_warranties: "Expiring Warranties", total_items: "Total Items", on_demo_count: "On Demo", returned_count: "Returned", }; return ( SPECIAL[key] ?? key .replace(/_/g, " ") .replace(/\b\w/g, (c) => c.toUpperCase()) ); } function computeUptimePct(record: Record): string { const upRaw = record.total_uptime_minutes ?? record.uptime_seconds; const downRaw = record.total_downtime_minutes ?? record.downtime_seconds; if (upRaw != null && downRaw != null) { const up = Number(upRaw); const down = Number(downRaw); const total = up + down; if (Number.isFinite(total) && total > 0) { return `${((up / total) * 100).toFixed(1)} %`; } } if (record.downtime_pct != null) { const dtPct = Number(record.downtime_pct); if (Number.isFinite(dtPct)) { return `${Math.max(0, 100 - dtPct).toFixed(1)} %`; } } return "—"; } export function ReportDetailPage() { const { reportKey } = useParams<{ reportKey: string }>(); const user = useAuthStore((s) => s.user); const role = user?.role; const isDeptUser = role === "department_user"; const meta = REPORT_CATALOG.find((r) => r.key === reportKey); const key = meta?.key as ReportKey | undefined; const isForbidden = Boolean(role && meta?.hiddenForRoles?.includes(role)); // Tailored filter state const [month, setMonth] = useState(currentMonthStr()); const [dateFrom, setDateFrom] = useState(""); const [dateTo, setDateTo] = useState(""); const [dueFrom, setDueFrom] = useState(""); const [dueTo, setDueTo] = useState(""); const [departmentId, setDepartmentId] = useState(""); const [priority, setPriority] = useState(""); const [callStatus, setCallStatus] = useState(""); const [serviceMode, setServiceMode] = useState(""); const [agencyId, setAgencyId] = useState(""); const [supplierId, setSupplierId] = useState(""); const [statusFilter, setStatusFilter] = useState(""); const [recordKind, setRecordKind] = useState("all"); const [contractType, setContractType] = useState(""); const [formulaOpen, setFormulaOpen] = useState(false); const [exporting, setExporting] = useState<"xlsx" | "csv" | null>(null); const filterParams: ReportFilterParams = useMemo(() => { if (!key) return {}; const p: ReportFilterParams = {}; if (!isDeptUser && departmentId) p.department_id = Number(departmentId); switch (key) { case "monthly-maintenance": case "monthly-department": if (month) p.month = month; break; case "daily-visit": if (dateFrom) p.date_from = dateFrom; if (dateTo) p.date_to = dateTo; break; case "breakdown-complaints": if (dateFrom) p.date_from = dateFrom; if (dateTo) p.date_to = dateTo; if (priority) p.priority = priority; if (callStatus) p.call_status = callStatus; break; case "pm-compliance": if (dateFrom || dateTo) { if (dateFrom) p.date_from = dateFrom; if (dateTo) p.date_to = dateTo; } else if (month) { p.month = month; } if (serviceMode) p.service_mode = serviceMode; break; case "calibration-due": if (dueFrom) p.due_from = dueFrom; if (dueTo) p.due_to = dueTo; if (agencyId) p.agency_id = Number(agencyId); if (statusFilter) p.status = statusFilter; break; case "contracts-warranty": if (recordKind) p.record_kind = recordKind; if (statusFilter) p.status = statusFilter; if (contractType) p.contract_type = contractType; break; case "demo-equipment": if (supplierId) p.supplier_id = Number(supplierId); if (statusFilter) p.status = statusFilter; if (dateFrom) p.date_from = dateFrom; if (dateTo) p.date_to = dateTo; break; } return p; }, [ key, isDeptUser, departmentId, month, dateFrom, dateTo, dueFrom, dueTo, priority, callStatus, serviceMode, agencyId, supplierId, statusFilter, recordKind, contractType, ]); const activeFiltersCount = useMemo(() => { let count = 0; if (departmentId) count++; if (month && month !== currentMonthStr()) count++; if (dateFrom || dateTo) count++; if (dueFrom || dueTo) count++; if (priority) count++; if (callStatus) count++; if (serviceMode) count++; if (agencyId) count++; if (supplierId) count++; if (statusFilter) count++; if (recordKind && recordKind !== "all") count++; if (contractType) count++; return count; }, [ departmentId, month, dateFrom, dateTo, dueFrom, dueTo, priority, callStatus, serviceMode, agencyId, supplierId, statusFilter, recordKind, contractType, ]); function handleResetFilters() { setMonth(currentMonthStr()); setDateFrom(""); setDateTo(""); setDueFrom(""); setDueTo(""); setDepartmentId(""); setPriority(""); setCallStatus(""); setServiceMode(""); setAgencyId(""); setSupplierId(""); setStatusFilter(""); setRecordKind("all"); setContractType(""); } const deptsQuery = useQuery({ queryKey: ["departments", "active-only"], queryFn: () => departmentsApi.list(false), enabled: Boolean(key) && !isDeptUser && !isForbidden, }); const vendorsQuery = useQuery({ queryKey: ["vendors", "active-only"], queryFn: () => vendorsApi.list(false), enabled: Boolean(key) && (key === "calibration-due" || key === "demo-equipment") && !isForbidden, }); const reportQuery = useQuery({ queryKey: ["report", key, filterParams], queryFn: () => fetchReport(key!, filterParams), enabled: Boolean(key) && !isForbidden, }); const report = reportQuery.data; const columns: ColumnDef, unknown>[] = useMemo(() => { if (!report) return []; const baseCols: ColumnDef, unknown>[] = report.columns.map( (col) => ({ id: col.key, accessorFn: (row) => row[col.key], header: col.label, cell: ({ getValue }) => { const val = getValue(); if (val === null || val === undefined || val === "") return "—"; if (typeof val === "boolean") return val ? "Yes" : "No"; return String(val); }, }) ); if ( key === "monthly-maintenance" && !report.columns.some((c) => c.key === "uptime_pct") ) { const uptimePctCol: ColumnDef, unknown> = { id: "uptime_pct", accessorFn: (row) => computeUptimePct(row), header: "Uptime %", cell: ({ getValue }) => ( {String(getValue() ?? "—")} ), }; const dtPctIdx = baseCols.findIndex((c) => c.id === "downtime_pct"); if (dtPctIdx >= 0) { baseCols.splice(dtPctIdx, 0, uptimePctCol); } else { baseCols.push(uptimePctCol); } } return baseCols; }, [report, key]); async function handleExport(format: "xlsx" | "csv") { if (!key) return; setExporting(format); try { await exportReport(key, format, filterParams); toast.success(`Exported ${key}.${format}`); } catch (err) { toast.error( err instanceof ApiError ? err.detail : `Failed to export ${format.toUpperCase()}` ); } finally { setExporting(null); } } if (!meta || !key) { return (

Report Not Found

Unknown report key: {reportKey}

); } if (isForbidden) { return (

Access Restricted

{meta.title} is available only to System Administrators, Biomedical Engineers, and Management.

); } const departments = deptsQuery.data?.items ?? []; const allVendors = vendorsQuery.data?.items ?? []; const agencies = allVendors.filter( (v) => v.vendor_type === "calibration_agency" || v.vendor_type === "service_provider" ); const suppliers = allVendors.filter((v) => v.vendor_type === "supplier"); const pieData = key === "monthly-maintenance" && report ? [ { name: "Uptime (hrs)", value: Math.round((Number(report.summary.total_uptime_minutes ?? 0) / 60) * 100) / 100, color: "#22c55e", }, { name: "Downtime (hrs)", value: Math.round((Number(report.summary.total_downtime_minutes ?? 0) / 60) * 100) / 100, color: "#ef4444", }, ] : []; return (
{/* Print-Only Official Hospital Letterhead & Scope */}
XYZ Hospital
XYZ HOSPITAL
NABH Accredited Tertiary Care Hospital • Department of Clinical Engineering
27, Sadashiv Peth, Pune, Maharashtra 411030 • Tel: +91 20 6609 6000
Audit & Operational Record
Ref: XYZ-BME-{key?.toUpperCase() ?? "REP"}
Date: {formatDateTime(new Date().toISOString())} IST
{user?.name && (
Generated by: {user.name} ({user.role?.replace(/_/g, " ").toUpperCase()})
)}
{/* Print Filter / Scope summary bar */}
Report:{" "} {report?.title ?? meta.title}
{month && (
Period: {month}
)} {dateFrom && (
From: {dateFrom}
)} {dateTo && (
To: {dateTo}
)}
Department:{" "} {departmentId ? departments.find((d) => String(d.id) === departmentId)?.name ?? departmentId : isDeptUser && user?.department_name ? user.department_name : "All Departments"}
{priority && (
Priority:{" "} {priority.toUpperCase()}
)} {callStatus && (
Status:{" "} {callStatus.toUpperCase()}
)}
Total Records: {report?.rows?.length ?? 0}
{/* Screen Header */}
All Reports • {meta.category}

{report?.title ?? meta.title}

{meta.description}

{key === "monthly-maintenance" && report?.formula_info && ( )}
{/* Formula Info Popover / Panel for Monthly Maintenance */} {key === "monthly-maintenance" && formulaOpen && report?.formula_info && (
Uptime & Downtime Calculation Methodology
Scheduled Hours / Day:{" "} {report.formula_info.scheduled_hours_per_day} hrs
Days in Month:{" "} {report.formula_info.days_in_month} days
Downtime End Milestone:{" "} {report.formula_info.downtime_end_milestone}
  • Uptime Formula: {report.formula_info.uptime_formula}
  • Downtime Formula: {report.formula_info.downtime_formula}
  • Month-Boundary Clipping: Each breakdown is clipped to the selected calendar month in IST ([month_start_IST, next_month_start_IST)), and distinct calendar downtime days count unique dates covered by those intervals.
)} {/* Tailored Filter Bar */}
Report Parameters & Scope {activeFiltersCount > 0 && ( {activeFiltersCount} active filter{activeFiltersCount > 1 ? "s" : ""} )}
{activeFiltersCount > 0 && ( )}
{(key === "monthly-maintenance" || key === "monthly-department" || key === "pm-compliance") && (
setMonth(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" />
)} {(key === "daily-visit" || key === "breakdown-complaints" || key === "pm-compliance" || key === "demo-equipment") && ( <>
setDateFrom(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" />
setDateTo(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" />
)} {key === "calibration-due" && ( <>
setDueFrom(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" />
setDueTo(e.target.value)} className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white" />
)} {!isDeptUser && (
)} {key === "breakdown-complaints" && ( <>
)} {key === "pm-compliance" && (
)} {key === "calibration-due" && ( <>
)} {key === "contracts-warranty" && ( <>
)} {key === "demo-equipment" && ( <>
)}
{/* Summary Strip */} {report && (
{key === "monthly-maintenance" && (
Uptime %
{computeUptimePct(report.summary)}
Hospital Availability
)} {Object.entries(report.summary).map(([sKey, sVal]) => { const isNegative = sKey.includes("downtime") || sKey.includes("overdue") || sKey.includes("under_repair"); const isPositive = sKey.includes("uptime") || sKey.includes("compliance") || sKey.includes("completed"); const borderTopColor = isNegative ? "border-t-rose-500" : isPositive ? "border-t-emerald-500" : "border-t-[#1e3a8a]"; return (
{humanizeSummaryKey(sKey)}
{String(sVal)}
); })}
)} {/* Monthly Maintenance Charts */} {key === "monthly-maintenance" && report?.chart_data && report.chart_data.length > 0 && (

Department Uptime vs Downtime (Hours)

Hospital Uptime Share

{pieData.map((entry, idx) => ( ))}
)} {/* Report DataTable */} {/* Hospital Tripartite Sign-off Block (Print / PDF Only) */}
Hospital Engineering Audit & Verification Sign-off (NABH Chapter FMS) XYZ Hospital
1. PREPARED BY
Name: {user?.name || "Biomedical Engineer"}
Role: {user?.role?.replace(/_/g, " ").toUpperCase() || "BIOMEDICAL"}
Date: {new Date().toLocaleDateString("en-IN")}
2. VERIFIED BY
Name: __________________________
Role: HOD / Biomedical In-Charge
Date: ____ / ____ / ________
3. APPROVED BY
Name: __________________________
Role: Medical Superintendent / Director
Date: ____ / ____ / ________
Official Hospital Record • XYZ Hospital • Confidential • Retain for 7 Years AMS Portal Generated • NABH Compliant
); }