"use client"; import { useState } from "react"; import { PageLayout, LoadingState, PageHeader } from "@/components/layout"; import { AccountCard, AccountEditDialog, AccountBulkActions, } from "@/components/accounts"; import { useBankingData } from "@/lib/hooks"; import { updateAccount, deleteAccount } from "@/lib/store-db"; import { Card, CardContent } from "@/components/ui/card"; import { Building2, Folder } from "lucide-react"; import type { Account } from "@/lib/types"; import { cn } from "@/lib/utils"; import { getAccountBalance } from "@/lib/account-utils"; export default function AccountsPage() { const { data, isLoading, refresh } = useBankingData(); const [editingAccount, setEditingAccount] = useState(null); const [isDialogOpen, setIsDialogOpen] = useState(false); const [selectedAccounts, setSelectedAccounts] = useState>( new Set(), ); const [formData, setFormData] = useState({ name: "", type: "CHECKING" as Account["type"], folderId: "folder-root", externalUrl: "", initialBalance: 0, }); if (isLoading || !data) { return ; } const formatCurrency = (amount: number) => { return new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR", }).format(amount); }; const handleEdit = (account: Account) => { setEditingAccount(account); setFormData({ name: account.name, type: account.type, folderId: account.folderId || "folder-root", externalUrl: account.externalUrl || "", initialBalance: account.initialBalance || 0, }); setIsDialogOpen(true); }; const handleSave = async () => { if (!editingAccount) return; try { const updatedAccount = { ...editingAccount, name: formData.name, type: formData.type, folderId: formData.folderId, externalUrl: formData.externalUrl || null, initialBalance: formData.initialBalance, }; await updateAccount(updatedAccount); refresh(); setIsDialogOpen(false); setEditingAccount(null); } catch (error) { console.error("Error updating account:", error); alert("Erreur lors de la mise à jour du compte"); } }; const handleDelete = async (accountId: string) => { if (!confirm("Supprimer ce compte et toutes ses transactions ?")) return; try { await deleteAccount(accountId); refresh(); } catch (error) { console.error("Error deleting account:", error); alert("Erreur lors de la suppression du compte"); } }; const handleBulkDelete = async () => { const count = selectedAccounts.size; if ( !confirm( `Supprimer ${count} compte${count > 1 ? "s" : ""} et toutes leurs transactions ?`, ) ) return; try { const ids = Array.from(selectedAccounts); const response = await fetch( `/api/banking/accounts?ids=${ids.join(",")}`, { method: "DELETE", }, ); if (!response.ok) { throw new Error("Failed to delete accounts"); } setSelectedAccounts(new Set()); refresh(); } catch (error) { console.error("Error deleting accounts:", error); alert("Erreur lors de la suppression des comptes"); } }; const toggleSelectAccount = (accountId: string, selected: boolean) => { const newSelected = new Set(selectedAccounts); if (selected) { newSelected.add(accountId); } else { newSelected.delete(accountId); } setSelectedAccounts(newSelected); }; const getTransactionCount = (accountId: string) => { return data.transactions.filter((t) => t.accountId === accountId).length; }; const totalBalance = data.accounts.reduce( (sum, a) => sum + getAccountBalance(a), 0, ); // Grouper les comptes par folder const accountsByFolder = data.accounts.reduce( (acc, account) => { const folderId = account.folderId || "no-folder"; if (!acc[folderId]) { acc[folderId] = []; } acc[folderId].push(account); return acc; }, {} as Record, ); // Obtenir les folders racine (sans parent) et les trier par nom const rootFolders = data.folders .filter((f) => !f.parentId) .sort((a, b) => a.name.localeCompare(b.name)); return (

Solde total

= 0 ? "text-emerald-600" : "text-red-600" )} > {formatCurrency(totalBalance)}

} /> {data.accounts.length === 0 ? (

Aucun compte

Importez un fichier OFX depuis le tableau de bord pour ajouter votre premier compte.

) : ( <>
{/* Afficher d'abord les comptes sans dossier */} {accountsByFolder["no-folder"] && accountsByFolder["no-folder"].length > 0 && (

Sans dossier

({accountsByFolder["no-folder"].length}) sum + getAccountBalance(a), 0, ) >= 0 ? "text-emerald-600" : "text-red-600", )} > {formatCurrency( accountsByFolder["no-folder"].reduce( (sum, a) => sum + getAccountBalance(a), 0, ), )}
{accountsByFolder["no-folder"].map((account) => { const folder = data.folders.find( (f) => f.id === account.folderId, ); return ( ); })}
)} {/* Afficher les comptes groupés par folder */} {rootFolders.map((folder) => { const folderAccounts = accountsByFolder[folder.id] || []; if (folderAccounts.length === 0) return null; const folderBalance = folderAccounts.reduce( (sum, a) => sum + getAccountBalance(a), 0, ); return (

{folder.name}

({folderAccounts.length}) = 0 ? "text-emerald-600" : "text-red-600", )} > {formatCurrency(folderBalance)}
{folderAccounts.map((account) => { const accountFolder = data.folders.find( (f) => f.id === account.folderId, ); return ( ); })}
); })}
)}
); }