import React, { useState, useEffect } from 'react'; import { Link, useSearchParams } from 'react-router-dom'; import { billingService } from '../../services/billingService'; import { patientService } from '../../services/patientService'; import Loading from '../../components/Loading'; import ErrorAlert from '../../components/ErrorAlert'; import SuccessAlert from '../../components/SuccessAlert'; function BillingList() { const [billings, setBillings] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [searchParams] = useSearchParams(); const patientId = searchParams.get('patientId'); const user = JSON.parse(localStorage.getItem('user') || '{}'); // Filters const [statusFilter, setStatusFilter] = useState(''); const [patientFilter, setPatientFilter] = useState(''); const [patients, setPatients] = useState([]); const [pageSize] = useState(50); // Limit to 50 records per page useEffect(() => { const fetchBillings = async () => { try { setLoading(true); let response; if (patientId) { response = await billingService.getBillingHistoryForPatient(patientId); } else if (user.role === 'PATIENT') { response = await billingService.getBillingHistoryForPatient(user.patientId); } else { response = await billingService.getAllBillings(); } setBillings(response.data || []); } catch (err) { setError('Failed to fetch billing records'); console.error(err); } finally { setLoading(false); } }; fetchBillings(); }, [patientId, user.role, user.patientId]); // Load patients for filter dropdown (for billing admin) useEffect(() => { if (user.role === 'BILLING_ADMIN') { const loadPatients = async () => { try { const response = await patientService.getAllPatients(); setPatients(response.data || []); } catch (err) { console.error('Failed to load patients:', err); } }; loadPatients(); } }, [user.role]); // Filter billings based on selected filters const filteredBillings = billings.filter(billing => { if (statusFilter && billing.paymentStatus !== statusFilter) { return false; } if (patientFilter && billing.patientName !== patientFilter) { return false; } return true; }).slice(0, pageSize); // Limit to first 50 records for performance const pendingBillings = billings.filter(b => b.paymentStatus === 'PENDING'); const handleUpdateStatus = async (billId, newStatus) => { try { const updateData = { paymentStatus: newStatus }; if (newStatus === 'PAID') { updateData.paymentDate = new Date().toISOString().split('T')[0]; } console.log('Updating billing status:', { billId, updateData }); await billingService.updatePaymentStatus(billId, updateData); setSuccess(`Billing status updated to ${newStatus}`); // Refresh the list const response = user.role === 'BILLING_ADMIN' ? await billingService.getAllBillings() : await billingService.getBillingHistoryForPatient(patientId || user.patientId); setBillings(response.data || []); } catch (err) { setError(`Failed to update billing status: ${err.response?.data?.error || err.message}`); console.error('Update status error:', err); } }; // Prevent unauthorized access to billing if (user.role === 'DOCTOR' || user.role === 'LAB_TECHNICIAN') { return (

Access Denied

You do not have permission to access billing records.

); } if (loading) return ; return (

{patientId ? 'Patient Billing History' : 'Billing Records'}

{error && setError(null)} />} {success && setSuccess(null)} />} {/* Filters for Billing Admin */} {user.role === 'BILLING_ADMIN' && (

Filters

)} {/* Pending Billing Records Section (for Billing Admin) */} {user.role === 'BILLING_ADMIN' && pendingBillings.length > 0 && (

Pending Billing Records ({pendingBillings.length})

{pendingBillings.map(billing => (

{billing.patientName}

${billing.totalCost}

))}
)}
{filteredBillings.map(billing => ( ))}
Patient Total Cost Payment Status Payment Date Actions
{billing.patientName} ${billing.totalCost} {billing.paymentStatus} {billing.paymentDate || 'Not paid'} e.currentTarget.style.textDecoration = 'underline'} onMouseLeave={(e) => e.currentTarget.style.textDecoration = 'none'}> View
{filteredBillings.length === 0 && (
{billings.length === 0 ? 'No billing records found' : 'No records match the selected filters'}
)}
); } export default BillingList;