Files
Medasset_ai/frontend/src/pages/AIReportPage.tsx
T

1651 lines
69 KiB
TypeScript

import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
AlertTriangle,
ChevronDown,
ChevronRight,
Cpu,
Download,
FileSpreadsheet,
HelpCircle,
Info,
Printer,
RefreshCw,
Sparkles,
X,
} from "lucide-react";
import {
Bar,
BarChart,
CartesianGrid,
Legend,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import {
aiApi,
type AIFilterParams,
type AIHowCalculated,
type AIMetric,
type AINarrative,
type AIPeriod,
type AISectionKey,
type AISuggestion,
} from "@/api/ai";
import { categoriesApi, departmentsApi } from "@/api/masters";
import { useAuthStore } from "@/hooks/useAuth";
import { formatDateTime, formatINR } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
function SectionSkeleton() {
return (
<div className="bg-white border border-gray-200 rounded-xl p-5 space-y-4 animate-pulse">
<div className="h-5 w-64 bg-gray-200 rounded" />
<div className="h-20 bg-gray-100 rounded-lg" />
<div className="h-44 bg-gray-100 rounded-lg" />
</div>
);
}
function NarrativeCard({
narrative,
section,
isAdmin,
regenerating,
onRegenerate,
}: {
narrative?: AINarrative | null;
section: AISectionKey;
isAdmin: boolean;
regenerating: boolean;
onRegenerate: (section: AISectionKey) => void;
}) {
if (!narrative) return null;
const isAI = narrative.source === "ai";
return (
<div className="rounded-lg border border-blue-100 bg-blue-50/40 p-4 space-y-2.5">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2 flex-wrap">
<span
className={
isAI
? "inline-flex items-center gap-1 rounded-full bg-[#1e3a8a] text-white text-xs font-medium px-2.5 py-0.5"
: "inline-flex items-center gap-1 rounded-full bg-slate-700 text-white text-xs font-medium px-2.5 py-0.5"
}
>
{isAI ? <Sparkles className="h-3 w-3" /> : <Cpu className="h-3 w-3" />}
{isAI ? "AI summary" : "Rule-based summary"}
</span>
{narrative.failure_reason && (
<span
className="inline-flex items-center gap-1 text-xs text-amber-800 bg-amber-50 border border-amber-200 rounded px-2 py-0.5"
title={narrative.failure_reason}
>
<AlertTriangle className="h-3.5 w-3.5 shrink-0 text-amber-600" />
<span>
{narrative.failure_reason.includes("timed out")
? "AI response pending (showing deterministic summary)"
: "Deterministic summary (AI validation fallback)"}
</span>
</span>
)}
</div>
{isAdmin && (
<Button
type="button"
variant="outline"
size="sm"
loading={regenerating}
onClick={() => onRegenerate(section)}
className="no-print text-xs h-7"
>
<RefreshCw className="h-3.5 w-3.5 mr-1" />
Regenerate summary
</Button>
)}
</div>
<p className="text-sm font-semibold text-gray-900">{narrative.headline}</p>
{narrative.bullets.length > 0 && (
<ul className="space-y-1.5 text-sm text-gray-700 list-disc pl-5">
{narrative.bullets.map((b, i) => (
<li key={i} className="leading-relaxed">
<span>{b.text}</span>
{b.metric_ids.length > 0 && (
<span className="ml-1.5 text-[11px] font-mono text-gray-400">
[{b.metric_ids.join(", ")}]
</span>
)}
</li>
))}
</ul>
)}
</div>
);
}
function SectionToolbarAndDrawers({
section,
metrics,
howCalculated,
filters,
exportingKey,
onExport,
}: {
section: AISectionKey;
metrics: AIMetric[];
howCalculated?: AIHowCalculated | null;
filters: AIFilterParams;
exportingKey: string | null;
onExport: (section: AISectionKey, format: "xlsx" | "csv", filters: AIFilterParams) => void;
}) {
const [evidenceOpen, setEvidenceOpen] = useState(false);
const [howOpen, setHowOpen] = useState(false);
return (
<div className="space-y-2.5 pt-2 border-t border-gray-100">
<div className="flex flex-wrap items-center justify-between gap-2 no-print">
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => setEvidenceOpen((v) => !v)}
className="inline-flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-[#1e3a8a] bg-gray-50 hover:bg-blue-50 border border-gray-200 rounded-md px-2.5 py-1.5 transition-colors"
>
{evidenceOpen ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
Evidence ({metrics.length})
</button>
<div className="relative">
<button
type="button"
onClick={() => setHowOpen((v) => !v)}
className="inline-flex items-center gap-1 text-xs font-medium text-gray-700 hover:text-[#1e3a8a] bg-gray-50 hover:bg-blue-50 border border-gray-200 rounded-md px-2.5 py-1.5 transition-colors"
>
<HelpCircle className="h-3.5 w-3.5" />
How this is calculated
</button>
{howOpen && howCalculated && (
<div className="absolute left-0 z-30 mt-2 w-80 sm:w-[440px] rounded-xl bg-white border border-gray-200 shadow-lg p-4 space-y-3 text-xs text-gray-700">
<div className="flex items-center justify-between">
<span className="font-semibold text-gray-900">
Calculation Formulas &amp; Inputs
</span>
<button
type="button"
onClick={() => setHowOpen(false)}
className="p-0.5 text-gray-400 hover:text-gray-700"
aria-label="Close methodology popover"
>
<X className="h-4 w-4" />
</button>
</div>
{howCalculated.formulas?.length > 0 && (
<ul className="space-y-1.5 list-disc pl-4">
{howCalculated.formulas.map((f, idx) => (
<li key={idx} className="leading-relaxed">
{f}
</li>
))}
</ul>
)}
{howCalculated.latest_equipment_rule && (
<p className="text-gray-600">{howCalculated.latest_equipment_rule}</p>
)}
{howCalculated.missing_data_rule && (
<p className="text-gray-600">{howCalculated.missing_data_rule}</p>
)}
{howCalculated.settings_used &&
Object.keys(howCalculated.settings_used).length > 0 && (
<div className="pt-2 border-t border-gray-100">
<p className="font-semibold text-gray-800 mb-1">Active Settings</p>
<div className="grid grid-cols-2 gap-1.5">
{Object.entries(howCalculated.settings_used).map(([k, v]) => (
<div
key={k}
className="bg-gray-50 rounded px-2 py-1 flex items-center justify-between gap-2"
>
<span className="text-gray-500 truncate">{k.replace(/_/g, " ")}</span>
<span className="font-mono font-medium text-gray-900">
{String(v ?? "—")}
</span>
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
</div>
<div className="flex flex-wrap items-center gap-1.5">
<Button
type="button"
variant="outline"
size="sm"
loading={exportingKey === `${section}:xlsx`}
onClick={() => onExport(section, "xlsx", filters)}
className="text-xs h-7"
>
<FileSpreadsheet className="h-3.5 w-3.5 mr-1 text-emerald-700" />
Export Excel
</Button>
<Button
type="button"
variant="outline"
size="sm"
loading={exportingKey === `${section}:csv`}
onClick={() => onExport(section, "csv", filters)}
className="text-xs h-7"
>
<Download className="h-3.5 w-3.5 mr-1 text-blue-700" />
CSV
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.print()}
className="text-xs h-7"
>
<Printer className="h-3.5 w-3.5 mr-1 text-gray-600" />
Print
</Button>
</div>
</div>
{evidenceOpen && (
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3 overflow-x-auto">
<table className="w-full text-xs">
<thead>
<tr className="text-left text-gray-500 border-b border-gray-200">
<th className="py-1.5 pr-3 font-medium">Metric ID</th>
<th className="py-1.5 pr-3 font-medium">Label</th>
<th className="py-1.5 text-right font-medium">Value</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{metrics.map((m) => (
<tr key={m.id}>
<td className="py-1.5 pr-3 font-mono text-[11px] text-gray-600">{m.id}</td>
<td className="py-1.5 pr-3 text-gray-800">{m.label}</td>
<td className="py-1.5 text-right font-semibold text-gray-900">{m.formatted}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
function SuggestionCard({
suggestion,
evidenceMap,
assetIdByCode,
}: {
suggestion: AISuggestion;
evidenceMap: Map<string, AIMetric>;
assetIdByCode: Map<string, number>;
}) {
const [open, setOpen] = useState(false);
const palette =
suggestion.severity === "red"
? {
card: "border-red-200 bg-red-50/60",
badge: "bg-red-100 text-red-800 border-red-200",
label: "High Priority",
}
: suggestion.severity === "yellow"
? {
card: "border-amber-200 bg-amber-50/60",
badge: "bg-amber-100 text-amber-900 border-amber-200",
label: "Attention",
}
: {
card: "border-blue-200 bg-blue-50/50",
badge: "bg-blue-100 text-blue-800 border-blue-200",
label: "Optimization",
};
return (
<div className={`rounded-xl border p-4 space-y-2 ${palette.card}`}>
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="flex items-center gap-2 flex-wrap">
<span
className={`inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-semibold border ${palette.badge}`}
>
{suggestion.rule} • {palette.label}
</span>
<h3 className="text-sm font-semibold text-gray-900">{suggestion.title}</h3>
</div>
<div className="flex items-center gap-1.5 flex-wrap">
{suggestion.asset_codes.map((code) => {
const aid = assetIdByCode.get(code);
return (
<Link
key={code}
to={aid ? `/assets/${aid}` : `/assets?search=${encodeURIComponent(code)}`}
className="text-xs font-mono font-medium text-[#1e3a8a] bg-white hover:bg-blue-50 border border-blue-200 rounded px-2 py-0.5"
>
{code}
</Link>
);
})}
</div>
</div>
<p className="text-xs text-gray-700 leading-relaxed">{suggestion.detail}</p>
<p className="text-xs font-medium text-gray-900">{suggestion.action_for_human}</p>
{suggestion.evidence_metric_ids.length > 0 && (
<div>
<button
type="button"
onClick={() => setOpen((v) => !v)}
className="inline-flex items-center gap-1 text-[11px] font-medium text-gray-600 hover:text-gray-900 no-print"
>
{open ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
Supporting evidence ({suggestion.evidence_metric_ids.length})
</button>
{open && (
<div className="mt-1.5 rounded-md bg-white/90 border border-gray-200 p-2 space-y-1 text-xs">
{suggestion.evidence_metric_ids.map((eid) => {
const m = evidenceMap.get(eid);
return (
<div key={eid} className="flex items-center justify-between gap-2">
<span className="text-gray-600">
<code className="text-[11px] text-gray-500 mr-1.5">{eid}</code>
{m?.label ?? ""}
</span>
<span className="font-semibold text-gray-900">{m?.formatted ?? "—"}</span>
</div>
);
})}
</div>
)}
</div>
)}
</div>
);
}
export function AIReportPage() {
const user = useAuthStore((s) => s.user);
const isAdmin = user?.role === "system_admin";
const qc = useQueryClient();
const [period, setPeriod] = useState<AIPeriod>("12m");
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [departmentId, setDepartmentId] = useState<string>("");
const [categoryId, setCategoryId] = useState<string>("");
const [selectedDepAsset, setSelectedDepAsset] = useState<string>("");
const [bfGroupMode, setBfGroupMode] = useState<"department" | "category">("department");
const [exportingKey, setExportingKey] = useState<string | null>(null);
const [regeneratingSection, setRegeneratingSection] = useState<AISectionKey | null>(null);
const filters: AIFilterParams = useMemo(
() => ({
period,
date_from: period === "custom" && dateFrom ? dateFrom : undefined,
date_to: period === "custom" && dateTo ? dateTo : undefined,
department_id: departmentId ? Number(departmentId) : undefined,
category_id: categoryId ? Number(categoryId) : undefined,
}),
[period, dateFrom, dateTo, departmentId, categoryId]
);
const { data: deptsData } = useQuery({
queryKey: ["departments-all"],
queryFn: () => departmentsApi.list(),
});
const { data: catsData } = useQuery({
queryKey: ["categories-all"],
queryFn: () => categoriesApi.list(),
});
const statusQuery = useQuery({
queryKey: ["ai-status"],
queryFn: aiApi.getStatus,
staleTime: 60_000,
});
const summaryQuery = useQuery({
queryKey: ["ai-summary", filters],
queryFn: () => aiApi.getSummary(filters),
});
const comparisonQuery = useQuery({
queryKey: ["ai-comparison", filters],
queryFn: () => aiApi.getComparison(filters),
});
const depreciationQuery = useQuery({
queryKey: ["ai-depreciation", filters],
queryFn: () => aiApi.getDepreciation(filters),
});
const efficiencyQuery = useQuery({
queryKey: ["ai-efficiency", filters],
queryFn: () => aiApi.getEfficiency(filters),
});
const breakdownQuery = useQuery({
queryKey: ["ai-breakdown-frequency", filters],
queryFn: () => aiApi.getBreakdownFrequency(filters),
});
const regenerateMutation = useMutation({
mutationFn: (section: AISectionKey) => aiApi.regenerateNarrative(section, filters),
onMutate: (section) => setRegeneratingSection(section),
onSettled: () => setRegeneratingSection(null),
onSuccess: async (_res, section) => {
const keyMap: Record<AISectionKey, string> = {
summary: "ai-summary",
comparison: "ai-comparison",
depreciation: "ai-depreciation",
efficiency: "ai-efficiency",
"breakdown-frequency": "ai-breakdown-frequency",
};
await qc.invalidateQueries({ queryKey: [keyMap[section], filters] });
},
});
async function handleExport(
section: AISectionKey,
format: "xlsx" | "csv",
activeFilters: AIFilterParams
) {
const key = `${section}:${format}`;
setExportingKey(key);
try {
await aiApi.exportSection(section, format, activeFilters);
} finally {
setExportingKey(null);
}
}
// Build assetCode -> assetId lookup from loaded rows so suggestion chips link directly to /assets/:id
const assetIdByCode = useMemo(() => {
const map = new Map<string, number>();
for (const r of depreciationQuery.data?.rows ?? []) map.set(r.asset_code, r.asset_id);
for (const r of comparisonQuery.data?.rows ?? []) map.set(r.asset_code, r.asset_id);
for (const r of breakdownQuery.data?.rows ?? []) map.set(r.asset_code, r.asset_id);
return map;
}, [depreciationQuery.data, comparisonQuery.data, breakdownQuery.data]);
const suggestionEvidenceMap = useMemo(() => {
const map = new Map<string, AIMetric>();
for (const m of summaryQuery.data?.suggestions_evidence ?? []) map.set(m.id, m);
for (const m of summaryQuery.data?.metrics ?? []) map.set(m.id, m);
return map;
}, [summaryQuery.data]);
const depCurveRows = useMemo(
() => (depreciationQuery.data?.rows ?? []).filter((r) => r.curve && r.curve.length > 0),
[depreciationQuery.data]
);
const activeDepRow = useMemo(() => {
if (!depCurveRows.length) return null;
if (selectedDepAsset) {
const match = depCurveRows.find((r) => r.asset_code === selectedDepAsset);
if (match) return match;
}
return depCurveRows[0];
}, [depCurveRows, selectedDepAsset]);
const statusChipLabel =
statusQuery.data?.enabled && statusQuery.data?.reachable
? "AI summary active"
: "Rule-based summary";
const statusChipActive = Boolean(statusQuery.data?.enabled && statusQuery.data?.reachable);
const bfGroupChartData =
bfGroupMode === "department"
? breakdownQuery.data?.by_department ?? []
: breakdownQuery.data?.by_category ?? [];
return (
<div className="space-y-6">
{/* Print-Only Official Hospital Letterhead & Scope */}
<div className="print-only mb-4 border-b-2 border-[#102C52] pb-3">
<div className="flex items-start justify-between">
<div className="flex items-center gap-3.5">
<img
src="/logo.jpg"
alt="XYZ Hospital"
className="h-14 w-14 object-contain"
/>
<div>
<div className="text-base font-extrabold text-[#102C52] tracking-tight">
XYZ HOSPITAL
</div>
<div className="text-[11px] font-semibold text-gray-800">
NABH Accredited Tertiary Care Hospital &bull; Department of Clinical Engineering
</div>
<div className="text-[10px] text-gray-500">
27, Sadashiv Peth, Pune, Maharashtra 411030 &bull; Tel: +91 20 6609 6000
</div>
</div>
</div>
<div className="text-right text-[10px] text-gray-600 space-y-0.5 border-l border-gray-200 pl-3">
<div className="font-bold text-[#102C52] uppercase tracking-wider">
Executive AI &amp; Cost Analysis
</div>
<div>
<strong>Ref:</strong> XYZ-BME-AI-REP
</div>
<div>
<strong>Date:</strong> {formatDateTime(new Date().toISOString())} IST
</div>
{user?.name && (
<div>
<strong>Generated by:</strong> {user.name} ({user.role?.replace(/_/g, " ").toUpperCase()})
</div>
)}
</div>
</div>
{/* Print Filter / Scope summary bar */}
<div className="mt-2.5 pt-2 border-t border-gray-200 flex flex-wrap items-center justify-between text-[10px] text-gray-700 bg-gray-50 px-3 py-1.5 rounded">
<div className="flex items-center gap-4 flex-wrap">
<div>
<span className="text-gray-500">Analysis:</span>{" "}
<strong>AI Report &amp; Cost Analysis</strong>
</div>
<div>
<span className="text-gray-500">Period:</span>{" "}
<strong>{period.toUpperCase()}</strong>
</div>
<div>
<span className="text-gray-500">Summary Mode:</span>{" "}
<strong>{statusChipLabel}</strong>
</div>
</div>
</div>
</div>
{/* Header + Mode Segmented Toggle + Status Chip */}
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="flex flex-wrap items-center gap-2.5">
<h1 className="text-2xl font-bold text-gray-900">AI Report &amp; Cost Analysis</h1>
<span
data-testid="ai-status-chip"
className={
statusChipActive
? "inline-flex items-center gap-1.5 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-800 text-xs font-medium px-2.5 py-0.5"
: "inline-flex items-center gap-1.5 rounded-full bg-slate-100 border border-slate-200 text-slate-700 text-xs font-medium px-2.5 py-0.5"
}
>
{statusChipActive ? (
<Sparkles className="h-3.5 w-3.5 text-emerald-600" />
) : (
<Cpu className="h-3.5 w-3.5 text-slate-500" />
)}
{statusChipLabel}
</span>
</div>
<p className="text-sm text-gray-500 mt-0.5">
Deterministic cost, depreciation, efficiency, and breakdown analysis with evidence-grounded summaries.
</p>
</div>
<div className="flex flex-wrap items-center gap-2 no-print">
{/* Segmented Toggle: Simple reports | AI report */}
<div
role="tablist"
aria-label="Report mode"
className="inline-flex rounded-lg border border-gray-200 bg-gray-100 p-0.5"
>
<Link
to="/reports"
role="tab"
aria-selected={false}
className="px-3 py-1.5 text-xs font-medium rounded-md text-gray-600 hover:text-gray-900 transition-colors"
>
Simple reports
</Link>
<span
role="tab"
aria-selected={true}
className="px-3 py-1.5 text-xs font-semibold rounded-md bg-white text-[#1e3a8a] shadow-sm"
>
AI report
</span>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => window.print()}
className="text-xs"
>
<Printer className="h-4 w-4 mr-1.5" />
Print Report
</Button>
</div>
</div>
{/* Filter Bar */}
<div className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm no-print">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 items-end">
<div>
<label
htmlFor="ai-period"
className="block text-xs font-medium text-gray-600 mb-1"
>
Period
</label>
<select
id="ai-period"
value={period}
onChange={(e) => setPeriod(e.target.value as AIPeriod)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="3m">Last 3 Months</option>
<option value="6m">Last 6 Months</option>
<option value="12m">Last 12 Months</option>
<option value="custom">Custom Range</option>
</select>
</div>
<div>
<label
htmlFor="ai-department"
className="block text-xs font-medium text-gray-600 mb-1"
>
Department
</label>
<select
id="ai-department"
value={departmentId}
onChange={(e) => setDepartmentId(e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Departments</option>
{(deptsData?.items ?? []).map((d) => (
<option key={d.id} value={d.id}>
{d.name} ({d.code})
</option>
))}
</select>
</div>
<div>
<label
htmlFor="ai-category"
className="block text-xs font-medium text-gray-600 mb-1"
>
Category
</label>
<select
id="ai-category"
value={categoryId}
onChange={(e) => setCategoryId(e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Categories</option>
{(catsData?.items ?? []).map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
<div className="text-xs text-gray-500 flex items-center justify-between lg:justify-end gap-2 py-1.5">
{summaryQuery.data && (
<span>
Window:{" "}
<strong className="text-gray-800">
{summaryQuery.data.period_start} to {summaryQuery.data.period_end}
</strong>
</span>
)}
</div>
</div>
{period === "custom" && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-3 pt-3 border-t border-gray-100">
<div>
<label
htmlFor="ai-date-from"
className="block text-xs font-medium text-gray-600 mb-1"
>
From Date
</label>
<input
id="ai-date-from"
type="date"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label
htmlFor="ai-date-to"
className="block text-xs font-medium text-gray-600 mb-1"
>
To Date
</label>
<input
id="ai-date-to"
type="date"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
</div>
)}
</div>
{/* Executive Summary & Top Suggestions Panel */}
{summaryQuery.isLoading ? (
<SectionSkeleton />
) : summaryQuery.data ? (
<section className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h2 className="text-lg font-bold text-gray-900">AI Executive Summary &amp; Suggestions</h2>
<p className="text-xs text-gray-500">
Advisory items generated strictly from deterministic biomedical rules. Every decision remains with hospital staff.
</p>
</div>
<Badge variant="outline" className="text-xs">
{summaryQuery.data.suggestions.length} Suggestion(s)
</Badge>
</div>
<NarrativeCard
narrative={summaryQuery.data.narrative}
section="summary"
isAdmin={isAdmin}
regenerating={regeneratingSection === "summary"}
onRegenerate={(sec) => regenerateMutation.mutate(sec)}
/>
<div className="space-y-3">
<h3 className="text-sm font-semibold text-gray-800">Suggestions</h3>
{summaryQuery.data.suggestions.length === 0 ? (
<div className="rounded-lg border border-dashed border-gray-300 p-5 text-center text-sm text-gray-500">
No advisory suggestions triggered for the selected filters.
</div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{summaryQuery.data.suggestions.map((sug) => (
<SuggestionCard
key={sug.id}
suggestion={sug}
evidenceMap={suggestionEvidenceMap}
assetIdByCode={assetIdByCode}
/>
))}
</div>
)}
</div>
<SectionToolbarAndDrawers
section="summary"
metrics={summaryQuery.data.metrics}
howCalculated={summaryQuery.data.how_calculated}
filters={filters}
exportingKey={exportingKey}
onExport={handleExport}
/>
</section>
) : null}
{/* SECTION 1: Comparison: in-house vs outsourced vs rent */}
{comparisonQuery.isLoading ? (
<SectionSkeleton />
) : comparisonQuery.data ? (
<section className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h2 className="text-lg font-bold text-gray-900">
1. Comparison: in-house vs outsourced vs rent
</h2>
<p className="text-xs text-gray-500">
Latest {comparisonQuery.data.summary.latest_count} equipment evaluated over a{" "}
{comparisonQuery.data.horizon_years}-year horizon
</p>
</div>
<div className="flex flex-wrap gap-2 text-xs">
<Badge variant="info">
In-house lowest: {comparisonQuery.data.summary.in_house_lowest_count}
</Badge>
<Badge variant="outline">
Outsourced lowest: {comparisonQuery.data.summary.outsourced_lowest_count}
</Badge>
<Badge variant="outline">
Rent lowest: {comparisonQuery.data.summary.rent_lowest_count}
</Badge>
</div>
</div>
<NarrativeCard
narrative={comparisonQuery.data.narrative}
section="comparison"
isAdmin={isAdmin}
regenerating={regeneratingSection === "comparison"}
onRegenerate={(sec) => regenerateMutation.mutate(sec)}
/>
{comparisonQuery.data.rows.length === 0 ? (
<div className="rounded-lg border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500">
Add cost details on the asset page to see this.
</div>
) : (
<>
<div className="overflow-x-auto border border-gray-200 rounded-lg">
<table className="w-full text-xs sm:text-sm">
<thead className="bg-[#1e3a8a] text-white">
<tr>
<th className="text-left px-3 py-2.5 font-semibold">Asset</th>
<th className="text-right px-3 py-2.5 font-semibold">Purchase Price</th>
<th className="text-right px-3 py-2.5 font-semibold">In-House Cost</th>
<th className="text-right px-3 py-2.5 font-semibold">Outsourced Cost</th>
<th className="text-right px-3 py-2.5 font-semibold">Rent Cost</th>
<th className="text-center px-3 py-2.5 font-semibold">Lowest Option</th>
<th className="text-right px-3 py-2.5 font-semibold">Difference</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{comparisonQuery.data.rows.map((r) => (
<tr key={r.asset_id} className="hover:bg-gray-50">
<td className="px-3 py-2">
<Link
to={`/assets/${r.asset_id}`}
className="font-mono text-xs font-semibold text-[#1e3a8a] hover:underline"
>
{r.asset_code}
</Link>
<div className="text-xs text-gray-600 truncate max-w-[200px]">
{r.asset_name}
</div>
</td>
<td className="px-3 py-2 text-right font-medium text-gray-800">
{r.purchase_value != null ? (
formatINR(r.purchase_value)
) : (
<span className="text-gray-400 italic text-xs">
Insufficient data: purchase_value
</span>
)}
</td>
<td
className={`px-3 py-2 text-right ${
r.lowest_scenario === "in_house"
? "bg-emerald-50 font-semibold text-emerald-800"
: ""
}`}
>
{r.in_house_cost != null ? (
formatINR(r.in_house_cost)
) : (
<span className="text-gray-400 italic text-xs">
{r.in_house_reason || "Insufficient data"}
</span>
)}
</td>
<td
className={`px-3 py-2 text-right ${
r.lowest_scenario === "outsourced"
? "bg-emerald-50 font-semibold text-emerald-800"
: ""
}`}
>
{r.outsourced_cost != null ? (
formatINR(r.outsourced_cost)
) : (
<span className="text-gray-400 italic text-xs">
{r.outsourced_reason || "Insufficient data"}
</span>
)}
</td>
<td
className={`px-3 py-2 text-right ${
r.lowest_scenario === "rent"
? "bg-emerald-50 font-semibold text-emerald-800"
: ""
}`}
>
{r.rent_cost != null ? (
formatINR(r.rent_cost)
) : (
<span className="text-gray-400 italic text-xs">
{r.rent_reason || "Insufficient data"}
</span>
)}
</td>
<td className="px-3 py-2 text-center">
{r.lowest_scenario_label ? (
<span className="inline-flex items-center rounded-full bg-emerald-100 text-emerald-800 text-xs font-semibold px-2.5 py-0.5">
{r.lowest_scenario_label}
</span>
) : (
<span className="text-gray-400 italic text-xs">Insufficient data</span>
)}
</td>
<td className="px-3 py-2 text-right font-medium text-gray-800">
{r.savings_vs_next != null ? formatINR(r.savings_vs_next) : "—"}
</td>
</tr>
))}
</tbody>
</table>
</div>
{comparisonQuery.data.chart_data.length > 0 && (
<div className="pt-2">
<h3 className="text-xs font-semibold text-gray-600 uppercase tracking-wide mb-2">
{comparisonQuery.data.horizon_years}-Year Scenario Cost Comparison (INR)
</h3>
<div className="h-72 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={comparisonQuery.data.chart_data}
margin={{ top: 10, right: 16, left: 16, bottom: 24 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="asset_code"
tick={{ fontSize: 11 }}
angle={-20}
textAnchor="end"
height={50}
/>
<YAxis
tick={{ fontSize: 11 }}
tickFormatter={(v: number) => `₹${Math.round(v / 1000)}k`}
/>
<Tooltip
formatter={(value) =>
typeof value === "number" ? formatINR(value) : "Insufficient data"
}
/>
<Legend />
<Bar dataKey="in_house" name="In-House" fill="#1e3a8a" radius={[3, 3, 0, 0]} />
<Bar
dataKey="outsourced"
name="Outsourced (AMC/CMC)"
fill="#0ea5e9"
radius={[3, 3, 0, 0]}
/>
<Bar dataKey="rent" name="Rent" fill="#f59e0b" radius={[3, 3, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</div>
)}
</>
)}
<SectionToolbarAndDrawers
section="comparison"
metrics={comparisonQuery.data.metrics}
howCalculated={comparisonQuery.data.how_calculated}
filters={filters}
exportingKey={exportingKey}
onExport={handleExport}
/>
</section>
) : null}
{/* SECTION 2: Depreciated price and cost analysis */}
{depreciationQuery.isLoading ? (
<SectionSkeleton />
) : depreciationQuery.data ? (
<section className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h2 className="text-lg font-bold text-gray-900">
2. Depreciated price and cost analysis
</h2>
<p className="text-xs text-gray-500">
Current book value, accumulated depreciation, cumulative maintenance cost, and replacement review flags (≥{" "}
{Math.round(depreciationQuery.data.summary.replacement_review_ratio * 100)}%)
</p>
</div>
<div className="flex flex-wrap gap-2 text-xs">
<Badge variant="outline">
Book Value: {formatINR(depreciationQuery.data.summary.total_book_value)}
</Badge>
<Badge variant="outline">
Maintenance: {formatINR(depreciationQuery.data.summary.total_maintenance_cost)}
</Badge>
<Badge variant="warning">
Review Flagged: {depreciationQuery.data.summary.review_flag_count}
</Badge>
</div>
</div>
<NarrativeCard
narrative={depreciationQuery.data.narrative}
section="depreciation"
isAdmin={isAdmin}
regenerating={regeneratingSection === "depreciation"}
onRegenerate={(sec) => regenerateMutation.mutate(sec)}
/>
{depreciationQuery.data.rows.length === 0 ? (
<div className="rounded-lg border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500">
Add cost details on the asset page to see this.
</div>
) : (
<>
<div className="overflow-x-auto border border-gray-200 rounded-lg max-h-[420px]">
<table className="w-full text-xs sm:text-sm">
<thead className="bg-[#1e3a8a] text-white sticky top-0 z-10">
<tr>
<th className="text-left px-3 py-2.5 font-semibold">Asset</th>
<th className="text-right px-3 py-2.5 font-semibold">Purchase Value</th>
<th className="text-center px-3 py-2.5 font-semibold">Method</th>
<th className="text-right px-3 py-2.5 font-semibold">Book Value</th>
<th className="text-right px-3 py-2.5 font-semibold">Accum. Dep.</th>
<th className="text-right px-3 py-2.5 font-semibold">Maintenance Cost</th>
<th className="text-right px-3 py-2.5 font-semibold">Maint. Ratio</th>
<th className="text-right px-3 py-2.5 font-semibold">Lifetime Cost</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{depreciationQuery.data.rows.map((r) => {
const isSelected = activeDepRow?.asset_code === r.asset_code;
return (
<tr
key={r.asset_id}
onClick={() => r.curve.length > 0 && setSelectedDepAsset(r.asset_code)}
className={`cursor-pointer transition-colors ${
isSelected ? "bg-blue-50/70" : "hover:bg-gray-50"
}`}
>
<td className="px-3 py-2">
<Link
to={`/assets/${r.asset_id}`}
onClick={(e) => e.stopPropagation()}
className="font-mono text-xs font-semibold text-[#1e3a8a] hover:underline"
>
{r.asset_code}
</Link>
<div className="text-xs text-gray-600 truncate max-w-[180px]">
{r.asset_name}
</div>
</td>
<td className="px-3 py-2 text-right">
{r.purchase_value != null ? (
formatINR(r.purchase_value)
) : (
<span className="text-gray-400 italic text-xs">
{r.depreciation_reason === "rented"
? "Rented"
: "Insufficient data: purchase_value"}
</span>
)}
</td>
<td className="px-3 py-2 text-center text-xs text-gray-600">
{r.method ? (
r.method === "straight_line" ? "Straight Line" : "Written Down"
) : (
<span className="text-gray-400 italic">
{r.depreciation_reason || "N/A"}
</span>
)}
</td>
<td className="px-3 py-2 text-right font-medium">
{r.book_value != null ? (
formatINR(r.book_value)
) : (
<span className="text-gray-400 italic text-xs">
{r.depreciation_reason || "N/A"}
</span>
)}
</td>
<td className="px-3 py-2 text-right text-gray-700">
{r.accumulated_depreciation != null
? formatINR(r.accumulated_depreciation)
: "—"}
</td>
<td className="px-3 py-2 text-right text-gray-800">
{formatINR(r.maintenance_cost)}
</td>
<td className="px-3 py-2 text-right">
{r.maintenance_ratio != null ? (
<span
className={
r.review_flag
? "inline-flex items-center rounded px-2 py-0.5 bg-red-100 text-red-800 font-semibold text-xs"
: "text-gray-700"
}
>
{(r.maintenance_ratio * 100).toFixed(1)}%
</span>
) : (
"—"
)}
</td>
<td className="px-3 py-2 text-right font-semibold text-gray-900">
{r.lifetime_cost != null ? formatINR(r.lifetime_cost) : "—"}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{activeDepRow && (
<div className="pt-2 space-y-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-xs font-semibold text-gray-600 uppercase tracking-wide">
Book Value Over Useful Life — {activeDepRow.asset_code} ({activeDepRow.asset_name})
</h3>
<select
aria-label="Select asset for depreciation curve"
value={activeDepRow.asset_code}
onChange={(e) => setSelectedDepAsset(e.target.value)}
className="px-2.5 py-1 text-xs border border-gray-300 rounded-md bg-white no-print"
>
{depCurveRows.map((r) => (
<option key={r.asset_code} value={r.asset_code}>
{r.asset_code} — {r.asset_name}
</option>
))}
</select>
</div>
<div className="h-64 w-full">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={activeDepRow.curve}
margin={{ top: 10, right: 20, left: 16, bottom: 8 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="year"
tick={{ fontSize: 11 }}
tickFormatter={(v: number) => `Yr ${v}`}
/>
<YAxis
tick={{ fontSize: 11 }}
tickFormatter={(v: number) => `₹${Math.round(v / 1000)}k`}
/>
<Tooltip
formatter={(value) =>
typeof value === "number" ? formatINR(value) : "—"
}
labelFormatter={(label) => `Year ${label}`}
/>
<Line
type="monotone"
dataKey="book_value"
name="Book Value"
stroke="#1e3a8a"
strokeWidth={2.5}
dot={{ r: 3 }}
/>
</LineChart>
</ResponsiveContainer>
</div>
</div>
)}
</>
)}
<SectionToolbarAndDrawers
section="depreciation"
metrics={depreciationQuery.data.metrics}
howCalculated={depreciationQuery.data.how_calculated}
filters={filters}
exportingKey={exportingKey}
onExport={handleExport}
/>
</section>
) : null}
{/* SECTION 3: Efficiency */}
{efficiencyQuery.isLoading ? (
<SectionSkeleton />
) : efficiencyQuery.data ? (
<section className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm space-y-4">
<div>
<h2 className="text-lg font-bold text-gray-900">3. Efficiency</h2>
<p className="text-xs text-gray-500">
Weighted composite of uptime (50%), PM compliance (20%), SLA response (15%), and repeat-free reliability (15%)
</p>
</div>
<NarrativeCard
narrative={efficiencyQuery.data.narrative}
section="efficiency"
isAdmin={isAdmin}
regenerating={regeneratingSection === "efficiency"}
onRegenerate={(sec) => regenerateMutation.mutate(sec)}
/>
{/* KPI Strip */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3">
<div className="text-xs text-gray-500">Average Uptime</div>
<div className="text-xl font-bold text-gray-900 mt-0.5">
{efficiencyQuery.data.summary.avg_uptime_pct.toFixed(1)}%
</div>
</div>
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3">
<div className="text-xs text-gray-500">MTTR</div>
<div className="text-xl font-bold text-gray-900 mt-0.5">
{efficiencyQuery.data.summary.mttr_hours != null
? `${efficiencyQuery.data.summary.mttr_hours.toFixed(1)} hrs`
: "—"}
</div>
</div>
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3">
<div className="text-xs text-gray-500">MTBF</div>
<div className="text-xl font-bold text-gray-900 mt-0.5">
{efficiencyQuery.data.summary.mtbf_hours != null
? `${efficiencyQuery.data.summary.mtbf_hours.toFixed(1)} hrs`
: "No failures"}
</div>
</div>
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3">
<div className="text-xs text-gray-500">PM Compliance</div>
<div className="text-xl font-bold text-gray-900 mt-0.5">
{efficiencyQuery.data.summary.pm_compliance_pct.toFixed(1)}%
</div>
</div>
<div className="rounded-lg border border-blue-200 bg-blue-50/70 p-3">
<div className="text-xs text-blue-700 font-medium">Average Score</div>
<div className="text-xl font-bold text-[#1e3a8a] mt-0.5">
{efficiencyQuery.data.summary.avg_efficiency_score.toFixed(1)} / 100
</div>
</div>
</div>
{efficiencyQuery.data.rows.length === 0 ? (
<div className="rounded-lg border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500">
No operational equipment found for the selected filters.
</div>
) : (
<>
<div className="overflow-x-auto border border-gray-200 rounded-lg max-h-[380px]">
<table className="w-full text-xs sm:text-sm">
<thead className="bg-[#1e3a8a] text-white sticky top-0 z-10">
<tr>
<th className="text-left px-3 py-2.5 font-semibold">Group</th>
<th className="text-center px-3 py-2.5 font-semibold">Type</th>
<th className="text-right px-3 py-2.5 font-semibold">Assets</th>
<th className="text-right px-3 py-2.5 font-semibold">Uptime %</th>
<th className="text-right px-3 py-2.5 font-semibold">PM %</th>
<th className="text-right px-3 py-2.5 font-semibold">Response</th>
<th className="text-right px-3 py-2.5 font-semibold">Repeat-Free</th>
<th className="text-right px-3 py-2.5 font-semibold">Score</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{efficiencyQuery.data.rows.map((r) => (
<tr key={`${r.group_type}-${r.group}`} className="hover:bg-gray-50">
<td className="px-3 py-2 font-medium text-gray-900">{r.group}</td>
<td className="px-3 py-2 text-center">
<Badge variant="outline" className="text-[10px] capitalize">
{r.group_type}
</Badge>
</td>
<td className="px-3 py-2 text-right text-gray-700">{r.assets_in_scope}</td>
<td className="px-3 py-2 text-right">{r.uptime_pct.toFixed(1)}%</td>
<td className="px-3 py-2 text-right">{r.pm_compliance_pct.toFixed(1)}%</td>
<td className="px-3 py-2 text-right">{r.response_score.toFixed(1)}</td>
<td className="px-3 py-2 text-right">{r.repeat_free_score.toFixed(1)}</td>
<td className="px-3 py-2 text-right font-bold text-[#1e3a8a]">
{r.efficiency_score.toFixed(1)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{efficiencyQuery.data.chart_data.length > 0 && (
<div className="pt-2">
<h3 className="text-xs font-semibold text-gray-600 uppercase tracking-wide mb-2">
Score Composition by Department (Weighted Points out of 100)
</h3>
<div className="h-72 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={efficiencyQuery.data.chart_data}
margin={{ top: 10, right: 16, left: 8, bottom: 24 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="group"
tick={{ fontSize: 11 }}
angle={-15}
textAnchor="end"
height={50}
/>
<YAxis domain={[0, 100]} tick={{ fontSize: 11 }} />
<Tooltip />
<Legend />
<Bar dataKey="uptime" stackId="a" name="Uptime (50%)" fill="#1e3a8a" />
<Bar
dataKey="pm_compliance"
stackId="a"
name="PM Compliance (20%)"
fill="#0ea5e9"
/>
<Bar
dataKey="response"
stackId="a"
name="Response SLA (15%)"
fill="#10b981"
/>
<Bar
dataKey="repeat_free"
stackId="a"
name="Repeat-Free (15%)"
fill="#f59e0b"
/>
</BarChart>
</ResponsiveContainer>
</div>
</div>
)}
</>
)}
<SectionToolbarAndDrawers
section="efficiency"
metrics={efficiencyQuery.data.metrics}
howCalculated={efficiencyQuery.data.how_calculated}
filters={filters}
exportingKey={exportingKey}
onExport={handleExport}
/>
</section>
) : null}
{/* SECTION 4: Breakdown frequency and average breakdowns */}
{breakdownQuery.isLoading ? (
<SectionSkeleton />
) : breakdownQuery.data ? (
<section className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm space-y-4">
<div>
<h2 className="text-lg font-bold text-gray-900">
4. Breakdown frequency and average breakdowns
</h2>
<p className="text-xs text-gray-500">
Total breakdowns, average per equipment (including zero-breakdown assets), top-10 equipment, and monthly trend
</p>
</div>
<NarrativeCard
narrative={breakdownQuery.data.narrative}
section="breakdown-frequency"
isAdmin={isAdmin}
regenerating={regeneratingSection === "breakdown-frequency"}
onRegenerate={(sec) => regenerateMutation.mutate(sec)}
/>
{/* KPI Strip */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3">
<div className="text-xs text-gray-500">Total Breakdowns</div>
<div className="text-xl font-bold text-gray-900 mt-0.5">
{breakdownQuery.data.summary.total_breakdowns}
</div>
</div>
<div className="rounded-lg border border-gray-200 bg-gray-50/70 p-3">
<div className="text-xs text-gray-500">Average per Equipment</div>
<div className="text-xl font-bold text-gray-900 mt-0.5">
{breakdownQuery.data.summary.avg_breakdowns_per_equipment.toFixed(2)}
</div>
<div className="text-[11px] text-gray-400">
across {breakdownQuery.data.summary.assets_in_scope} assets in scope
</div>
</div>
<div className="rounded-lg border border-amber-200 bg-amber-50/70 p-3">
<div className="text-xs text-amber-800 font-medium">Repeat-Failure Assets</div>
<div className="text-xl font-bold text-amber-900 mt-0.5">
{breakdownQuery.data.summary.repeat_failure_count}
</div>
<div className="text-[11px] text-amber-700">
≥ {breakdownQuery.data.summary.repeat_threshold} in{" "}
{breakdownQuery.data.summary.repeat_window_days} days
</div>
</div>
</div>
{/* Top 10 Table */}
{breakdownQuery.data.rows.length > 0 ? (
<div className="overflow-x-auto border border-gray-200 rounded-lg">
<table className="w-full text-xs sm:text-sm">
<thead className="bg-[#1e3a8a] text-white">
<tr>
<th className="text-left px-3 py-2.5 font-semibold">Top-10 Equipment</th>
<th className="text-left px-3 py-2.5 font-semibold">Department</th>
<th className="text-left px-3 py-2.5 font-semibold">Category</th>
<th className="text-right px-3 py-2.5 font-semibold">Breakdowns</th>
<th className="text-right px-3 py-2.5 font-semibold">Avg Downtime (hrs)</th>
<th className="text-right px-3 py-2.5 font-semibold">Repeat Window</th>
<th className="text-center px-3 py-2.5 font-semibold">Repeat Flag</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{breakdownQuery.data.rows.map((r) => (
<tr key={r.asset_id} className="hover:bg-gray-50">
<td className="px-3 py-2">
<Link
to={`/assets/${r.asset_id}`}
className="font-mono text-xs font-semibold text-[#1e3a8a] hover:underline"
>
{r.asset_code}
</Link>
<div className="text-xs text-gray-600 truncate max-w-[180px]">
{r.asset_name}
</div>
</td>
<td className="px-3 py-2 text-gray-700">{r.department_name}</td>
<td className="px-3 py-2 text-gray-700">{r.category_name}</td>
<td className="px-3 py-2 text-right font-semibold text-gray-900">
{r.breakdown_count}
</td>
<td className="px-3 py-2 text-right text-gray-700">
{r.avg_downtime_hours.toFixed(1)}
</td>
<td className="px-3 py-2 text-right text-gray-700">
{r.repeat_window_count}
</td>
<td className="px-3 py-2 text-center">
{r.repeat_failure ? (
<span className="inline-flex items-center rounded-full bg-red-100 text-red-800 text-xs font-semibold px-2 py-0.5">
Repeat Failure
</span>
) : (
<span className="text-xs text-gray-400">Normal</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="rounded-lg border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500">
No breakdown data for the selected filters.
</div>
)}
{/* Charts: Monthly LineChart + Department/Category BarChart */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-5 pt-2">
<div>
<h3 className="text-xs font-semibold text-gray-600 uppercase tracking-wide mb-2">
Monthly Breakdown Trend
</h3>
<div className="h-64 w-full">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={breakdownQuery.data.chart_data.monthly_trend}
margin={{ top: 10, right: 16, left: 0, bottom: 16 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis dataKey="label" tick={{ fontSize: 11 }} />
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
<Tooltip />
<Line
type="monotone"
dataKey="breakdowns"
name="Breakdowns"
stroke="#dc2626"
strokeWidth={2.5}
dot={{ r: 3 }}
/>
</LineChart>
</ResponsiveContainer>
</div>
</div>
<div>
<div className="flex items-center justify-between mb-2">
<h3 className="text-xs font-semibold text-gray-600 uppercase tracking-wide">
Breakdowns &amp; Average per Equipment
</h3>
<div className="inline-flex rounded border border-gray-200 bg-gray-100 p-0.5 text-[11px] no-print">
<button
type="button"
onClick={() => setBfGroupMode("department")}
className={`px-2 py-0.5 rounded ${
bfGroupMode === "department"
? "bg-white text-[#1e3a8a] font-semibold shadow-sm"
: "text-gray-600"
}`}
>
Department
</button>
<button
type="button"
onClick={() => setBfGroupMode("category")}
className={`px-2 py-0.5 rounded ${
bfGroupMode === "category"
? "bg-white text-[#1e3a8a] font-semibold shadow-sm"
: "text-gray-600"
}`}
>
Category
</button>
</div>
</div>
<div className="h-64 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={bfGroupChartData}
margin={{ top: 10, right: 16, left: 0, bottom: 24 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="group"
tick={{ fontSize: 11 }}
angle={-15}
textAnchor="end"
height={50}
/>
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
<Tooltip />
<Legend />
<Bar dataKey="breakdowns" name="Total Breakdowns" fill="#1e3a8a" radius={[3, 3, 0, 0]} />
<Bar
dataKey="avg_breakdowns_per_equipment"
name="Avg / Equipment"
fill="#f59e0b"
radius={[3, 3, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</div>
</div>
</div>
<SectionToolbarAndDrawers
section="breakdown-frequency"
metrics={breakdownQuery.data.metrics}
howCalculated={breakdownQuery.data.how_calculated}
filters={filters}
exportingKey={exportingKey}
onExport={handleExport}
/>
</section>
) : null}
<div className="flex items-center gap-2 text-xs text-gray-500 pt-1">
<Info className="h-4 w-4 shrink-0 text-gray-400" />
<span>
All figures are calculated deterministically from hospital records. Summaries are advisory only and never replace clinical or administrative sign-off.
</span>
</div>
{/* Hospital Tripartite Sign-off Block (Print / PDF Only) */}
<div className="print-only mt-8 pt-4 border-t-2 border-gray-300 print-break-inside-avoid">
<div className="flex items-center justify-between text-[10px] font-bold uppercase tracking-wider text-gray-700 mb-4">
<span>Hospital Engineering Audit &amp; Verification Sign-off (NABH Chapter FMS)</span>
<span>XYZ Hospital</span>
</div>
<div className="grid grid-cols-3 gap-5 text-[10px]">
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
<div className="font-bold text-gray-800">1. PREPARED BY</div>
<div className="h-9 border-b border-dashed border-gray-400"></div>
<div className="space-y-0.5 text-gray-600">
<div>Name: {user?.name || "Biomedical Engineer"}</div>
<div>Role: {user?.role?.replace(/_/g, " ").toUpperCase() || "BIOMEDICAL"}</div>
<div>Date: {new Date().toLocaleDateString("en-IN")}</div>
</div>
</div>
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
<div className="font-bold text-gray-800">2. VERIFIED BY</div>
<div className="h-9 border-b border-dashed border-gray-400"></div>
<div className="space-y-0.5 text-gray-600">
<div>Name: __________________________</div>
<div>Role: HOD / Biomedical In-Charge</div>
<div>Date: ____ / ____ / ________</div>
</div>
</div>
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
<div className="font-bold text-gray-800">3. APPROVED BY</div>
<div className="h-9 border-b border-dashed border-gray-400"></div>
<div className="space-y-0.5 text-gray-600">
<div>Name: __________________________</div>
<div>Role: Medical Superintendent / Director</div>
<div>Date: ____ / ____ / ________</div>
</div>
</div>
</div>
<div className="mt-4 pt-2 border-t border-gray-200 text-[9px] text-gray-500 flex items-center justify-between">
<span>Official Hospital Record &bull; XYZ Hospital &bull; Confidential &bull; Retain for 7 Years</span>
<span>AMS Portal Generated &bull; NABH Compliant</span>
</div>
</div>
</div>
);
}