feat(report-page) base setup overall

This commit is contained in:
2025-10-16 03:38:54 +05:30
parent ab23473f40
commit ebf152495e
8 changed files with 1061 additions and 610 deletions

View File

@@ -1,339 +0,0 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/use-auth";
import { Plus, ClipboardCheck, Clock, CheckCircle, AlertCircle } from "lucide-react";
import { format } from "date-fns";
import { Appointment, Patient } from "@repo/db/types";
export default function PreAuthorizationsPage() {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [isPreAuthFormOpen, setIsPreAuthFormOpen] = useState(false);
const [selectedPatient, setSelectedPatient] = useState<number | null>(null);
const [selectedProcedure, setSelectedProcedure] = useState<string | null>(null);
const { toast } = useToast();
const { user } = useAuth();
// Fetch patients
const { data: patients = [], isLoading: isLoadingPatients } = useQuery<Patient[]>({
queryKey: ["/api/patients"],
enabled: !!user,
});
// Fetch appointments
const {
data: appointments = [] as Appointment[],
isLoading: isLoadingAppointments
} = useQuery<Appointment[]>({
queryKey: ["/api/appointments"],
enabled: !!user,
});
const toggleMobileMenu = () => {
setIsMobileMenuOpen(!isMobileMenuOpen);
};
const handleNewPreAuth = (patientId: number, procedure: string) => {
setSelectedPatient(patientId);
setSelectedProcedure(procedure);
setIsPreAuthFormOpen(true);
// Show a toast notification of success
const patient = patients.find(p => p.id === patientId);
toast({
title: "Pre-authorization Request Started",
description: `Started pre-auth for ${patient?.firstName} ${patient?.lastName} - ${procedure}`,
});
};
// Common dental procedures requiring pre-authorization
const dentalProcedures = [
{ code: "D2740", name: "Crown - porcelain/ceramic" },
{ code: "D2950", name: "Core buildup, including any pins" },
{ code: "D3330", name: "Root Canal - molar" },
{ code: "D4341", name: "Periodontal scaling & root planing" },
{ code: "D4910", name: "Periodontal maintenance" },
{ code: "D5110", name: "Complete denture - maxillary" },
{ code: "D6010", name: "Surgical placement of implant body" },
{ code: "D7240", name: "Removal of impacted tooth" },
];
// Get patients with active insurance
const patientsWithInsurance = patients.filter(patient =>
patient.insuranceProvider && patient.insuranceId
);
// Sample pre-authorization data
const samplePreAuths = [
{
id: "PA2023-001",
patientId: patientsWithInsurance[0]?.id || 1,
procedureCode: "D2740",
procedureName: "Crown - porcelain/ceramic",
requestDate: new Date(new Date().setDate(new Date().getDate() - 14)),
status: "approved",
approvalDate: new Date(new Date().setDate(new Date().getDate() - 7)),
expirationDate: new Date(new Date().setMonth(new Date().getMonth() + 6)),
},
{
id: "PA2023-002",
patientId: patientsWithInsurance[0]?.id || 1,
procedureCode: "D3330",
procedureName: "Root Canal - molar",
requestDate: new Date(new Date().setDate(new Date().getDate() - 5)),
status: "pending",
approvalDate: null,
expirationDate: null,
},
{
id: "PA2023-003",
patientId: patientsWithInsurance[0]?.id || 1,
procedureCode: "D7240",
procedureName: "Removal of impacted tooth",
requestDate: new Date(new Date().setDate(new Date().getDate() - 30)),
status: "denied",
approvalDate: null,
expirationDate: null,
denialReason: "Not medically necessary based on submitted documentation",
}
];
return (
<div>
{/* Header */}
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-800">Pre-authorizations</h1>
<p className="text-gray-600">Manage insurance pre-authorizations for dental procedures</p>
</div>
{/* New Pre-Authorization Request Section */}
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-medium text-gray-800">New Pre-Authorization Request</h2>
</div>
<Card>
<CardHeader className="pb-2">
<CardTitle>Recent Patients for Pre-Authorization</CardTitle>
</CardHeader>
<CardContent>
{isLoadingPatients ? (
<div className="text-center py-4">Loading patients data...</div>
) : patientsWithInsurance.length > 0 ? (
<div className="divide-y">
{patientsWithInsurance.map((patient) => (
<div
key={patient.id}
className="py-4 flex items-center justify-between cursor-pointer hover:bg-gray-50"
onClick={() => {
setSelectedPatient(Number(patient.id));
handleNewPreAuth(
patient.id,
dentalProcedures[Math.floor(Math.random() * 3)].name
);
}}
>
<div>
<h3 className="font-medium">{patient.firstName} {patient.lastName}</h3>
<div className="text-sm text-gray-500">
<span>Insurance: {patient.insuranceProvider === 'delta'
? 'Delta Dental'
: patient.insuranceProvider === 'metlife'
? 'MetLife'
: patient.insuranceProvider === 'cigna'
? 'Cigna'
: patient.insuranceProvider === 'aetna'
? 'Aetna'
: patient.insuranceProvider}</span>
<span className="mx-2"></span>
<span>ID: {patient.insuranceId}</span>
<span className="mx-2"></span>
<span>Procedure needed: {dentalProcedures[0].name}</span>
</div>
</div>
<div className="text-primary">
<ClipboardCheck className="h-5 w-5" />
</div>
</div>
))}
</div>
) : (
<div className="text-center py-8">
<ClipboardCheck className="h-12 w-12 mx-auto text-gray-400 mb-3" />
<h3 className="text-lg font-medium">No patients with insurance</h3>
<p className="text-gray-500 mt-1">
Add insurance information to patients to request pre-authorizations
</p>
</div>
)}
</CardContent>
</Card>
</div>
{/* Pre-Authorization Submitted Section */}
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-medium text-gray-800">Pre-Authorization Submitted</h2>
</div>
<Card>
<CardHeader className="pb-2">
<CardTitle>Pending Pre-Authorization Requests</CardTitle>
</CardHeader>
<CardContent>
{patientsWithInsurance.length > 0 ? (
<div className="divide-y">
{samplePreAuths.filter(auth => auth.status === 'pending').map((preAuth) => {
const patient = patients.find(p => p.id === preAuth.patientId) ||
{ firstName: "Unknown", lastName: "Patient" };
return (
<div
key={preAuth.id}
className="py-4 flex items-center justify-between cursor-pointer hover:bg-gray-50"
onClick={() => toast({
title: "Pre-Authorization Details",
description: `Viewing details for ${preAuth.id}`
})}
>
<div>
<h3 className="font-medium">{patient.firstName} {patient.lastName} - {preAuth.procedureName}</h3>
<div className="text-sm text-gray-500">
<span>ID: {preAuth.id}</span>
<span className="mx-2"></span>
<span>Submitted: {format(preAuth.requestDate, 'MMM dd, yyyy')}</span>
<span className="mx-2"></span>
<span>Expected Response: {format(new Date(preAuth.requestDate.getTime() + 7 * 24 * 60 * 60 * 1000), 'MMM dd, yyyy')}</span>
</div>
</div>
<div className="flex items-center gap-2">
<span className="px-2 py-1 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800">
<span className="flex items-center">
<Clock className="h-3 w-3 mr-1" />
Pending
</span>
</span>
</div>
</div>
);
})}
{samplePreAuths.filter(auth => auth.status === 'pending').length === 0 && (
<div className="text-center py-8">
<Clock className="h-12 w-12 mx-auto text-gray-400 mb-3" />
<h3 className="text-lg font-medium">No pending requests</h3>
<p className="text-gray-500 mt-1">
Submitted pre-authorization requests will appear here
</p>
</div>
)}
</div>
) : (
<div className="text-center py-8">
<Clock className="h-12 w-12 mx-auto text-gray-400 mb-3" />
<h3 className="text-lg font-medium">No pre-authorization history</h3>
<p className="text-gray-500 mt-1">
Submitted pre-authorization requests will appear here
</p>
</div>
)}
</CardContent>
</Card>
</div>
{/* Pre-Authorization Results Section */}
<div>
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-medium text-gray-800">Pre-Authorization Results</h2>
</div>
<Card>
<CardHeader className="pb-2">
<CardTitle>Completed Pre-Authorization Requests</CardTitle>
</CardHeader>
<CardContent>
{patientsWithInsurance.length > 0 ? (
<div className="divide-y">
{samplePreAuths.filter(auth => auth.status !== 'pending').map((preAuth) => {
const patient = patients.find(p => p.id === preAuth.patientId) ||
{ firstName: "Unknown", lastName: "Patient" };
return (
<div
key={preAuth.id}
className="py-4 flex items-center justify-between cursor-pointer hover:bg-gray-50"
onClick={() => toast({
title: "Pre-Authorization Details",
description: `Viewing details for ${preAuth.id}`
})}
>
<div>
<h3 className="font-medium">{patient.firstName} {patient.lastName} - {preAuth.procedureName}</h3>
<div className="text-sm text-gray-500">
<span>ID: {preAuth.id}</span>
<span className="mx-2"></span>
<span>Requested: {format(preAuth.requestDate, 'MMM dd, yyyy')}</span>
{preAuth.status === 'approved' && (
<>
<span className="mx-2"></span>
<span>Expires: {format(preAuth.expirationDate as Date, 'MMM dd, yyyy')}</span>
</>
)}
{preAuth.status === 'denied' && preAuth.denialReason && (
<>
<span className="mx-2"></span>
<span className="text-red-600">Reason: {preAuth.denialReason}</span>
</>
)}
</div>
</div>
<div className="flex items-center gap-2">
<span className={`px-2 py-1 text-xs font-medium rounded-full ${
preAuth.status === 'approved' ? 'bg-green-100 text-green-800' :
'bg-red-100 text-red-800'
}`}>
{preAuth.status === 'approved' ? (
<span className="flex items-center">
<CheckCircle className="h-3 w-3 mr-1" />
Approved
</span>
) : (
<span className="flex items-center">
<AlertCircle className="h-3 w-3 mr-1" />
Denied
</span>
)}
</span>
</div>
</div>
);
})}
{samplePreAuths.filter(auth => auth.status !== 'pending').length === 0 && (
<div className="text-center py-8">
<CheckCircle className="h-12 w-12 mx-auto text-gray-400 mb-3" />
<h3 className="text-lg font-medium">No completed requests</h3>
<p className="text-gray-500 mt-1">
Processed pre-authorization results will appear here
</p>
</div>
)}
</div>
) : (
<div className="text-center py-8">
<CheckCircle className="h-12 w-12 mx-auto text-gray-400 mb-3" />
<h3 className="text-lg font-medium">No pre-authorization results</h3>
<p className="text-gray-500 mt-1">
Completed pre-authorization requests will appear here
</p>
</div>
)}
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -1,18 +1,10 @@
// apps/Frontend/src/pages/reports-page.tsx
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Search,
Edit,
Eye,
ChevronLeft,
ChevronRight,
Settings,
} from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
@@ -20,285 +12,465 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Patient } from "@repo/db/types";
import { formatDateToHumanReadable } from "@/utils/dateUtils";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import {
DollarSign,
FileText,
Download,
AlertCircle,
Calendar,
Users,
TrendingUp,
} from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { apiRequest } from "@/lib/queryClient"; // <<-- your helper
import type { PatientBalanceRow } from "@repo/db/types";
type ReportType =
| "patients_with_balance"
| "patients_no_balance"
| "monthly_collections"
| "collections_by_doctor"
| "procedure_codes_by_doctor"
| "payment_methods"
| "insurance_vs_patient_payments"
| "aging_report";
interface PatientBalancesResponse {
balances: PatientBalanceRow[];
totalCount: number;
}
export default function ReportsPage() {
const { user } = useAuth();
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [searchField, setSearchField] = useState("all");
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;
// Fetch patients
const { data: patients = [], isLoading: isLoadingPatients } = useQuery<
Patient[]
>({
queryKey: ["/api/patients"],
// pagination state for patient balances
const [balancesPage, setBalancesPage] = useState<number>(1);
const balancesPerPage = 10;
// date range state (for dashboard summary)
const [startDate, setStartDate] = useState(() => {
const d = new Date();
d.setMonth(d.getMonth() - 1);
return d.toISOString().split("T")[0];
});
const [endDate, setEndDate] = useState(
() => new Date().toISOString().split("T")[0]
);
const [selectedReportType, setSelectedReportType] = useState<ReportType>(
"patients_with_balance"
);
const [isGenerating, setIsGenerating] = useState(false);
// --- 1) patient balances (paginated) using apiRequest ---
const {
data: patientBalancesResponse,
isLoading: isLoadingBalances,
isError: isErrorBalances,
} = useQuery<PatientBalancesResponse>({
queryKey: [
"/api/payments-reports/patient-balances",
balancesPage,
balancesPerPage,
startDate,
endDate,
selectedReportType,
],
queryFn: async () => {
const offset = (balancesPage - 1) * balancesPerPage;
const minBalanceFlag = selectedReportType === "patients_with_balance";
const endpoint = `/api/payments-reports/patient-balances?limit=${balancesPerPage}&offset=${offset}&minBalance=${minBalanceFlag}&from=${encodeURIComponent(
String(startDate)
)}&to=${encodeURIComponent(String(endDate))}`;
const res = await apiRequest("GET", endpoint);
if (!res.ok) {
const body = await res
.json()
.catch(() => ({ message: "Failed to load patient balances" }));
throw new Error(body.message || "Failed to load patient balances");
}
return res.json();
},
enabled: !!user,
});
// Filter patients based on search
const filteredPatients = patients.filter((patient) => {
if (!searchTerm) return true;
const patientBalances: PatientBalanceRow[] =
patientBalancesResponse?.balances ?? [];
const patientBalancesTotal = patientBalancesResponse?.totalCount ?? 0;
const searchLower = searchTerm.toLowerCase();
const fullName = `${patient.firstName} ${patient.lastName}`.toLowerCase();
const patientId = `PID-${patient?.id?.toString().padStart(4, "0")}`;
switch (searchField) {
case "name":
return fullName.includes(searchLower);
case "id":
return patientId.toLowerCase().includes(searchLower);
case "phone":
return patient.phone?.toLowerCase().includes(searchLower) || false;
case "all":
default:
return (
fullName.includes(searchLower) ||
patientId.toLowerCase().includes(searchLower) ||
patient.phone?.toLowerCase().includes(searchLower) ||
patient.email?.toLowerCase().includes(searchLower) ||
false
);
}
// --- 2) dashboard summary (separate route/storage) using apiRequest ---
const { data: dashboardSummary, isLoading: isLoadingSummary } = useQuery({
queryKey: [
"/api/payments-reports/summary",
String(startDate),
String(endDate),
],
queryFn: async () => {
const endpoint = `/api/payments-reports/summary?from=${encodeURIComponent(
String(startDate)
)}&to=${encodeURIComponent(String(endDate))}`;
const res = await apiRequest("GET", endpoint);
if (!res.ok) {
const body = await res
.json()
.catch(() => ({ message: "Failed to load dashboard summary" }));
throw new Error(body.message || "Failed to load dashboard summary");
}
return res.json();
},
enabled: !!user,
});
// Pagination
const totalPages = Math.ceil(filteredPatients.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const currentPatients = filteredPatients.slice(startIndex, endIndex);
const toggleMobileMenu = () => {
setIsMobileMenuOpen(!isMobileMenuOpen);
// format currency for numbers in dollars (storage returns decimal numbers like 123.45)
const formatCurrency = (amountDollars: number | undefined | null) => {
const value = Number(amountDollars ?? 0);
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(value);
};
const getPatientInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
// summary stats: use dashboardSummary for totals (server-driven) and derive other counts from paginated balances
const summaryStats = {
totalPatients: dashboardSummary?.totalPatients ?? 0,
// use the server-provided count of patients with balance inside range
patientsWithBalance: dashboardSummary?.patientsWithBalance ?? 0,
// patientsNoBalance: based on totalCount - patientsWithBalance (note: totalCount is number of patients with payments in range)
patientsNoBalance: Math.max(
0,
(dashboardSummary?.totalPatients ?? 0) -
(dashboardSummary?.patientsWithBalance ?? 0)
),
totalOutstanding:
dashboardSummary?.totalOutstanding ??
patientBalances.reduce((s, b) => s + (b.currentBalance ?? 0), 0),
totalCollected: dashboardSummary?.totalCollected ?? 0,
};
const generateReport = async () => {
setIsGenerating(true);
await new Promise((r) => setTimeout(r, 900));
setIsGenerating(false);
};
// -------------------- report rendering (only patients_with_balance wired) --------------------
// -------------------- report rendering (only patients_with_balance wired) --------------------
const renderPatientsWithBalance = () => {
// Use patientBalances for the current page list (already minBalance filtered if selectedReportType === 'patients_with_balance')
const patientsWithBalance = patientBalances
.filter((b) => (b.currentBalance ?? 0) > 0)
.map((b) => ({
patientId: b.patientId,
patientName: `${b.firstName ?? "Unknown"} ${b.lastName ?? ""}`.trim(),
currentBalance: b.currentBalance ?? 0,
totalCharges: b.totalCharges ?? 0,
totalPayments: b.totalPayments ?? 0,
}));
const totalOutstanding = patientsWithBalance.reduce(
(s, p) => s + p.currentBalance,
0
);
const avgBalance = patientsWithBalance.length
? totalOutstanding / patientsWithBalance.length
: 0;
return (
<div className="space-y-4">
<div className="grid grid-cols-3 gap-4 mb-6">
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-red-600">
{summaryStats.patientsWithBalance}
</div>
<p className="text-sm text-gray-600">Patients with Balance</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-red-600">
{formatCurrency(summaryStats.totalOutstanding)}
</div>
<p className="text-sm text-gray-600">Total Outstanding</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="text-2xl font-bold text-blue-600">
{formatCurrency(avgBalance)}
</div>
<p className="text-sm text-gray-600">
Average Balance (visible page)
</p>
</CardContent>
</Card>
</div>
<div className="bg-white rounded-lg border">
<div className="px-4 py-3 border-b bg-gray-50">
<h3 className="font-medium text-gray-900">
Patients with Outstanding Balances
</h3>
</div>
<div className="divide-y">
{patientsWithBalance.length === 0 ? (
<div className="p-8 text-center text-gray-500">
<DollarSign className="h-12 w-12 mx-auto mb-3 text-gray-300" />
<p>No patients have outstanding balances on this page</p>
</div>
) : (
patientsWithBalance.map((p) => (
<div key={p.patientId} className="p-4 hover:bg-gray-50">
<div className="flex justify-between items-center">
<div>
<h4 className="font-medium text-gray-900">
{p.patientName}
</h4>
<p className="text-sm text-gray-500">
Patient ID: {p.patientId}
</p>
</div>
<div className="text-right">
<div className="text-lg font-semibold text-red-600">
{formatCurrency(p.currentBalance)}
</div>
<div className="text-sm text-gray-500">
Charges: {formatCurrency(p.totalCharges)}
</div>
</div>
</div>
</div>
))
)}
</div>
</div>
{/* pagination controls for balances */}
<div className="flex items-center justify-between mt-4">
<div className="text-sm text-gray-600">
Showing {(balancesPage - 1) * balancesPerPage + 1} -{" "}
{Math.min(balancesPage * balancesPerPage, patientBalancesTotal)} of{" "}
{patientBalancesTotal}
</div>
<div className="space-x-2">
<Button
disabled={balancesPage <= 1}
onClick={() => setBalancesPage((p) => Math.max(1, p - 1))}
>
Previous
</Button>
<Button
disabled={balancesPage * balancesPerPage >= patientBalancesTotal}
onClick={() => setBalancesPage((p) => p + 1)}
>
Next
</Button>
</div>
</div>
</div>
);
};
const renderReportContent = () => {
if (isLoadingBalances || isLoadingSummary) {
return (
<div className="text-center py-12">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
<p className="text-gray-600">Loading report data...</p>
</div>
);
}
if ((patientBalances?.length ?? 0) === 0) {
return (
<div className="text-center py-12">
<AlertCircle className="h-12 w-12 text-amber-500 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-gray-900 mb-2">
Financial Data Not Available
</h3>
<p className="text-gray-600 mb-4">
No patient balance data yet. Add payments/service lines to populate
reports.
</p>
<div className="text-sm text-gray-500">
<p>
Date range: {startDate} to {endDate}
</p>
</div>
</div>
);
}
switch (selectedReportType) {
case "patients_with_balance":
return renderPatientsWithBalance();
default:
return (
<div className="text-center py-12">
<FileText className="h-12 w-12 text-gray-300 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-gray-900 mb-2">
Report Type Not Implemented
</h3>
<p className="text-gray-600">
The "{selectedReportType}" report is being developed. For now use
"Patients with Outstanding Balance".
</p>
</div>
);
}
};
return (
<div>
<div className="max-w-7xl mx-auto">
{/* Header */}
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-900 mb-2">Reports</h1>
<div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
<div>
<h1 className="text-2xl font-semibold text-gray-900">
Financial Reports
</h1>
<p className="text-gray-600">
View and manage all patient information
Generate comprehensive financial reports for your practice
</p>
</div>
{/* Search and Filters */}
<Card className="mb-6">
<CardContent className="p-4">
<div className="flex flex-col md:flex-row gap-4">
<div className="flex-1 relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
<Input
placeholder="Search patients..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
<div className="flex gap-2">
<Select value={searchField} onValueChange={setSearchField}>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Fields</SelectItem>
<SelectItem value="name">Name</SelectItem>
<SelectItem value="id">Patient ID</SelectItem>
<SelectItem value="phone">Phone</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm">
<Settings className="h-4 w-4 mr-2" />
Advanced
</Button>
</div>
</div>
</CardContent>
</Card>
{/* Patient List */}
<Card>
<CardContent className="p-0">
{isLoadingPatients ? (
<div className="text-center py-8">Loading patients...</div>
) : (
<>
{/* Table Header */}
<div className="grid grid-cols-12 gap-4 p-4 bg-gray-50 border-b text-sm font-medium text-gray-600">
<div className="col-span-3">Patient</div>
<div className="col-span-2">DOB / Gender</div>
<div className="col-span-2">Contact</div>
<div className="col-span-2">Insurance</div>
<div className="col-span-2">Status</div>
<div className="col-span-1">Actions</div>
</div>
{/* Table Rows */}
{currentPatients.length === 0 ? (
<div className="text-center py-8 text-gray-500">
{searchTerm
? "No patients found matching your search."
: "No patients available."}
</div>
) : (
currentPatients.map((patient) => (
<div
key={patient.id}
className="grid grid-cols-12 gap-4 p-4 border-b hover:bg-gray-50 transition-colors"
>
{/* Patient Info */}
<div className="col-span-3 flex items-center space-x-3">
<div className="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center text-sm font-medium text-gray-600">
{getPatientInitials(
patient.firstName,
patient.lastName
)}
</div>
<div>
<div className="font-medium text-gray-900">
{patient.firstName} {patient.lastName}
</div>
<div className="text-sm text-gray-500">
PID-{patient.id?.toString().padStart(4, "0")}
</div>
</div>
</div>
{/* DOB / Gender */}
<div className="col-span-2">
<div className="text-sm text-gray-900">
{formatDateToHumanReadable(patient.dateOfBirth)}
</div>
<div className="text-sm text-gray-500 capitalize">
{patient.gender}
</div>
</div>
{/* Contact */}
<div className="col-span-2">
<div className="text-sm text-gray-900">
{patient.phone || "Not provided"}
</div>
<div className="text-sm text-gray-500">
{patient.email || "No email"}
</div>
</div>
{/* Insurance */}
<div className="col-span-2">
<div className="text-sm text-gray-900">
{patient.insuranceProvider
? `${patient.insuranceProvider.charAt(0).toUpperCase()}${patient.insuranceProvider.slice(1)}`
: "Not specified"}
</div>
<div className="text-sm text-gray-500">
ID: {patient.insuranceId || "N/A"}
</div>
</div>
{/* Status */}
<div className="col-span-2">
<span
className={cn(
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",
patient.status === "active"
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
)}
>
{patient.status === "active" ? "Active" : "Inactive"}
</span>
</div>
{/* Actions */}
<div className="col-span-1">
<div className="flex space-x-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<Edit className="h-4 w-4 text-blue-600" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
>
<Eye className="h-4 w-4 text-gray-600" />
</Button>
</div>
</div>
</div>
))
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between p-4 border-t bg-gray-50">
<div className="text-sm text-gray-700">
Showing {startIndex + 1} to{" "}
{Math.min(endIndex, filteredPatients.length)} of{" "}
{filteredPatients.length} results
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="sm"
onClick={() =>
setCurrentPage(Math.max(1, currentPage - 1))
}
disabled={currentPage === 1}
>
<ChevronLeft className="h-4 w-4 mr-1" />
Previous
</Button>
{/* Page Numbers */}
{Array.from({ length: totalPages }, (_, i) => i + 1).map(
(page) => (
<Button
key={page}
variant={
currentPage === page ? "default" : "outline"
}
size="sm"
onClick={() => setCurrentPage(page)}
className="w-8 h-8 p-0"
>
{page}
</Button>
)
)}
<Button
variant="outline"
size="sm"
onClick={() =>
setCurrentPage(Math.min(totalPages, currentPage + 1))
}
disabled={currentPage === totalPages}
>
Next
<ChevronRight className="h-4 w-4 ml-1" />
</Button>
</div>
</div>
)}
</>
)}
</CardContent>
</Card>
<Button
onClick={generateReport}
disabled={isGenerating}
className="mt-4 md:mt-0"
>
<Download className="h-4 w-4 mr-2" />{" "}
{isGenerating ? "Generating..." : "Export Report"}
</Button>
</div>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Calendar className="h-5 w-5" />
Report Configuration
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="start-date">Start Date</Label>
<Input
id="start-date"
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="end-date">End Date</Label>
<Input
id="end-date"
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="report-type">Report Type</Label>
<Select
value={selectedReportType}
onValueChange={(v) => setSelectedReportType(v as ReportType)}
>
<SelectTrigger>
<SelectValue placeholder="Select report type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="patients_with_balance">
Patients with Outstanding Balance
</SelectItem>
<SelectItem value="patients_no_balance">
Patients with Zero Balance
</SelectItem>
<SelectItem value="monthly_collections">
Monthly Collections Summary
</SelectItem>
<SelectItem value="collections_by_doctor">
Collections by Each Doctor
</SelectItem>
<SelectItem value="procedure_codes_by_doctor">
Procedure Codes Analysis by Doctors
</SelectItem>
<SelectItem value="payment_methods">
Payment Methods Breakdown
</SelectItem>
<SelectItem value="insurance_vs_patient_payments">
Insurance vs Patient Payments
</SelectItem>
<SelectItem value="aging_report">
Accounts Receivable Aging
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<Separator />
<div className="grid grid-cols-2 md:grid-cols-5 gap-4">
<div className="text-center">
<div className="text-lg font-semibold text-blue-600">
{summaryStats.totalPatients}
</div>
<p className="text-sm text-gray-600">Total Patients</p>
</div>
<div className="text-center">
<div className="text-lg font-semibold text-red-600">
{summaryStats.patientsWithBalance}
</div>
<p className="text-sm text-gray-600">With Balance</p>
</div>
<div className="text-center">
<div className="text-lg font-semibold text-green-600">
{summaryStats.patientsNoBalance}
</div>
<p className="text-sm text-gray-600">Zero Balance</p>
</div>
<div className="text-center">
<div className="text-lg font-semibold text-orange-600">
{formatCurrency(summaryStats.totalOutstanding)}
</div>
<p className="text-sm text-gray-600">Outstanding</p>
</div>
<div className="text-center">
<div className="text-lg font-semibold text-purple-600">
{formatCurrency(summaryStats.totalCollected)}
</div>
<p className="text-sm text-gray-600">Collected</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>
{selectedReportType === "patients_with_balance"
? "Patients with Outstanding Balance"
: selectedReportType}
</CardTitle>
</CardHeader>
<CardContent>{renderReportContent()}</CardContent>
</Card>
</div>
);
}