'use client'; import { FC, useState } from "react"; import { BillingLocation, YearMonth } from "../../../../../lib/db-types"; import { formatYearMonth } from "../../../../../lib/format"; import { useTranslations } from "next-intl"; import { useRouter } from "next/navigation"; import { updateMonth } from "../../../../../lib/actions/monthActions"; import { toast, ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { BillToggleBadge } from "./BillToggleBadge"; export interface MultiBillEditProps { locations: BillingLocation[]; year: number; month: number; } interface BillState { locationId: string; billId: string; paid: boolean; } export const MultiBillEdit: FC = ({ locations, year, month }) => { const t = useTranslations("multi-bill-edit"); const router = useRouter(); // Initialize bill states from locations const initialBillStates: BillState[] = locations.flatMap(location => location.bills.map(bill => ({ locationId: location._id, billId: bill._id, paid: bill.paid, })) ); const [billStates, setBillStates] = useState(initialBillStates); const [isSaving, setIsSaving] = useState(false); const [allPaidMode, setAllPaidMode] = useState(false); // Toggle individual bill paid status const handleBillToggle = (locationId: string, billId: string) => { setBillStates(prevStates => prevStates.map(state => state.locationId === locationId && state.billId === billId ? { ...state, paid: !state.paid } : state ) ); }; // Toggle all bills paid status const handleSetAllAsPayed = () => { const newPaidState = !allPaidMode; setAllPaidMode(newPaidState); setBillStates(prevStates => prevStates.map(state => ({ ...state, paid: newPaidState })) ); }; // Save changes to database const handleSave = async () => { setIsSaving(true); try { const updates = billStates.map(state => ({ locationId: state.locationId, billId: state.billId, paid: state.paid, })); await updateMonth({ year, month }, updates); } catch (error) { console.error('Error saving bill updates:', error); toast.error(t("save-error-message"), { theme: "dark" }); setIsSaving(false); } }; // Cancel and return to home page const handleCancel = () => { router.push(`/home?year=${year}`); }; // Get bill state for a specific bill const getBillState = (locationId: string, billId: string): boolean => { const state = billStates.find( s => s.locationId === locationId && s.billId === billId ); return state?.paid ?? false; }; const yearMonth: YearMonth = { year, month }; return (

{formatYearMonth(yearMonth)}

{locations.map(location => (

{formatYearMonth(yearMonth)} {location.name}

{location.bills.length > 0 ? (
{location.bills.map(bill => { const isPaid = getBillState(location._id, bill._id); return ( handleBillToggle(location._id, bill._id)} /> ); })}
) : (

{t("no-bills-message")}

)}
))} {/* Action buttons */}
); };