"use client"; import { useState } from "react"; import { format } from "date-fns"; import { ptBR } from "date-fns/locale"; import Label from "@/app/(protected)/components/shared/Label"; import { getPaymentsByObligationAction } from "@/app/lib/payments/actions"; export default function ObligationDetails({ obligations }) { const [expandedObligation, setExpandedObligation] = useState(null); const [obligationPayments, setObligationPayments] = useState({}); const [loading, setLoading] = useState(false); // Group obligations by their reference (description + dueDate) const groupedObligations = obligations.reduce((acc, obligation) => { const key = `${obligation.description || "Pagamento"}_${obligation.dueDate || obligation.createdAt}`; if (!acc[key]) { acc[key] = { ...obligation, users: [], }; } acc[key].users.push(obligation); return acc; }, {}); const groupedList = Object.values(groupedObligations); const fetchPaymentsForObligation = async (obligation) => { setLoading(true); try { const result = await getPaymentsByObligationAction(obligation._id); if (result.success) { setObligationPayments(prev => ({ ...prev, [obligation._id]: result.data || [], })); } } catch (error) { console.error("Error fetching payments:", error); } finally { setLoading(false); } }; const handleToggleExpand = (obligation) => { if (expandedObligation === obligation._id) { setExpandedObligation(null); } else { setExpandedObligation(obligation._id); if (!obligationPayments[obligation._id]) { fetchPaymentsForObligation(obligation); } } }; const getStatusBadge = (userObligation) => { const payments = obligationPayments[userObligation._id] || []; const hasVerified = payments.some(p => p.status === "verified"); const hasPending = payments.some(p => p.status === "pending_verification"); if (hasVerified) { return ; } if (hasPending) { return ; } return ; }; if (obligations.length === 0) { return (
Vencimento: {format(new Date(group.dueDate || group.createdAt), "dd/MM/yyyy", { locale: ptBR })}
{group.users.length} {group.users.length === 1 ? "aluno" : "alunos"}
R$ {group.amount?.toFixed(2)}
| Aluno | Valor | Status | |
|---|---|---|---|
| {userObligation.userId?.fullName || "N/A"} | {userObligation.userId?.email || "N/A"} | R$ {userObligation.amount?.toFixed(2) || "0.00"} | {getStatusBadge(userObligation)} |