import React, { useEffect, useState } from 'react'; import { CondoService } from '../services/mockDb'; import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js"; import { Briefcase, Calendar, CheckCircle2, AlertCircle, Eye, Paperclip, X, FileText, Download, Users, Euro } from 'lucide-react'; import { ExtraordinaryExpense } from '../types'; export const ExtraordinaryUser: React.FC = () => { const [expenses, setExpenses] = useState([]); const [loading, setLoading] = useState(true); const [paypalClientId, setPaypalClientId] = useState(''); const [successMsg, setSuccessMsg] = useState(''); const [hasFamily, setHasFamily] = useState(true); const [userFamilyId, setUserFamilyId] = useState(null); // Details Modal State const [showDetails, setShowDetails] = useState(false); const [selectedExpense, setSelectedExpense] = useState(null); const [loadingDetails, setLoadingDetails] = useState(false); useEffect(() => { const load = async () => { try { const user = CondoService.getCurrentUser(); if (!user?.familyId) { setHasFamily(false); setLoading(false); return; } setUserFamilyId(user.familyId); const [myExp, condo] = await Promise.all([ CondoService.getMyExpenses(), CondoService.getActiveCondo() ]); setExpenses(myExp); if (condo?.paypalClientId) setPaypalClientId(condo.paypalClientId); // Update "Last Viewed" timestamp to clear notification localStorage.setItem('lastViewedExpensesTime', Date.now().toString()); // Trigger event to update Sidebar immediately window.dispatchEvent(new Event('expenses-viewed')); } catch(e) { console.error(e); } finally { setLoading(false); } }; load(); }, []); const handlePaymentSuccess = async (expenseId: string, amount: number) => { try { await CondoService.payExpense(expenseId, amount); setSuccessMsg('Pagamento registrato con successo!'); setTimeout(() => setSuccessMsg(''), 3000); // Refresh logic const updatedList = await CondoService.getMyExpenses(); setExpenses(updatedList); // Also update selected expense if modal is open if (selectedExpense) { const updatedDetails = await CondoService.getExpenseDetails(expenseId); setSelectedExpense(updatedDetails); } } catch(e) { alert("Errore registrazione pagamento"); } }; const handleCardClick = async (expenseId: string) => { setLoadingDetails(true); try { // Fetch full details including attachments const fullDetails = await CondoService.getExpenseDetails(expenseId); setSelectedExpense(fullDetails); setShowDetails(true); } catch (e) { console.error(e); alert("Impossibile caricare i dettagli."); } finally { setLoadingDetails(false); } }; const openAttachment = async (expenseId: string, attId: string) => { try { const file = await CondoService.getExpenseAttachment(expenseId, attId); const win = window.open(); if (win) { if (file.fileType.startsWith('image/') || file.fileType === 'application/pdf') { win.document.write(``); } else { win.document.write(`Download ${file.fileName}`); } } } catch(e) { alert("Errore apertura file"); } }; if (loading) return
Caricamento spese...
; if (!hasFamily) { return (

Nessuna Famiglia Associata

Il tuo utente (probabilmente Admin) non è collegato ad alcuna famiglia, quindi non ci sono spese personali da mostrare.

Vai in Impostazioni > Utenti e associa il tuo account a una famiglia per testare questa vista.

); } return (

Le Mie Spese Extra

Lavori straordinari e ripartizioni

{successMsg && (
{successMsg}
)} {expenses.length === 0 ? (

Nessuna spesa straordinaria attiva.

) : (
{expenses.map(exp => { const isPaid = exp.myShare.status === 'PAID'; return (
handleCardClick(exp.id)} className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden flex flex-col cursor-pointer hover:shadow-md transition-all group" >

{exp.title}

{new Date(exp.startDate).toLocaleDateString()}

{isPaid ? 'Saldato' : 'In Sospeso'}
Quota Totale (100%) € {exp.totalAmount.toLocaleString()}
La tua quota ({exp.myShare.percentage}%) € {exp.myShare.amountDue.toFixed(2)}
Versato: € {exp.myShare.amountPaid.toFixed(2)} Restante: € {(exp.myShare.amountDue - exp.myShare.amountPaid).toFixed(2)}
Clicca per dettagli e pagamenti
); })}
)} {/* DETAILS MODAL */} {showDetails && selectedExpense && (

{selectedExpense.title}

{selectedExpense.contractorName}

{/* Top Section: Info & Dates */}

Descrizione Lavori

{selectedExpense.description}

Inizio Lavori

{new Date(selectedExpense.startDate).toLocaleDateString()}

Costo Totale Progetto

€ {selectedExpense.totalAmount.toLocaleString()}

{/* Middle Section: Items and Distribution Grid */}
{/* Items List */}

Voci di Spesa (Totale)

{selectedExpense.items.map((item, i) => ( ))}
{item.description} € {item.amount.toLocaleString()}
Totale € {selectedExpense.totalAmount.toLocaleString()}
{/* Shares Table (Piano di Ripartizione) */}

Piano di Ripartizione

{selectedExpense.shares?.map((share, i) => { const isMe = share.familyId === userFamilyId; return ( ); })}
Condomino % Quota
{share.familyName} {isMe && TU} {share.percentage}% € {share.amountDue.toFixed(2)}
{/* Attachments */} {selectedExpense.attachments && selectedExpense.attachments.length > 0 && (

Documenti & Allegati

{selectedExpense.attachments.map(att => ( ))}
)}
{/* Payment Footer - Only visible here now */}
{(() => { const myShare = selectedExpense.shares?.find(s => s.familyId === userFamilyId); if (!myShare) return null; const remaining = Math.max(0, myShare.amountDue - myShare.amountPaid); if (remaining < 0.01) { return (
Quota Saldata
); } return (
Da Saldare: € {remaining.toFixed(2)}
{paypalClientId ? ( { return actions.order.create({ intent: "CAPTURE", purchase_units: [{ description: `Spesa Straordinaria: ${selectedExpense.title}`, amount: { currency_code: "EUR", value: remaining.toFixed(2) } }] }); }} onApprove={(data, actions) => { if(!actions.order) return Promise.resolve(); return actions.order.capture().then(() => { handlePaymentSuccess(selectedExpense.id, remaining); }); }} /> ) : (
Pagamenti online non configurati.
)}
); })()}
)}
); };