import { useState, useEffect } from "react"; import { useAuth } from "../../contexts/AuthContext"; import AddressForm from "../../components/AddressForm"; import UpgradeBanner from "../../components/UpgradeBanner"; import { getAddresses, createAddress, deleteAddress, updateAddress } from "../../api/addresses"; import "./Addresses.css"; export default function Addresses() { const { tierLimits, refreshAccount } = useAuth(); const [addresses, setAddresses] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [editingId, setEditingId] = useState(null); const [editLabel, setEditLabel] = useState(""); const maxAddresses = tierLimits.max_addresses; const isUnlimited = maxAddresses === -1; const atLimit = !isUnlimited && addresses.length >= maxAddresses; useEffect(() => { async function fetchAddresses() { try { setLoading(true); const data = await getAddresses(); setAddresses(data); } catch (err) { setError(err.message); console.error("Failed to fetch addresses:", err); } finally { setLoading(false); } } fetchAddresses(); }, []); async function handleAddressSubmit(data) { try { const newAddress = await createAddress(data); setAddresses((prev) => [...prev, newAddress]); setError(null); refreshAccount(); } catch (err) { setError(err.message); console.error("Failed to create address:", err); } } async function handleDelete(id, label) { const displayName = label || "this address"; if (!window.confirm(`Remove "${displayName}"? This will also delete all associated alert rules.`)) { return; } try { await deleteAddress(id); setAddresses((prev) => prev.filter((a) => a.id !== id)); setError(null); refreshAccount(); } catch (err) { setError(err.message); console.error("Failed to delete address:", err); } } function handleEditStart(addr) { setEditingId(addr.id); setEditLabel(addr.label ?? ""); } async function handleEditSave(id) { try { const updated = await updateAddress(id, { label: editLabel || null }); setAddresses((prev) => prev.map((a) => (a.id === id ? updated : a))); setEditingId(null); setEditLabel(""); setError(null); } catch (err) { setError(err.message); console.error("Failed to update address:", err); } } function handleEditCancel() { setEditingId(null); setEditLabel(""); } return (
Loading addresses...
} {error &&Error: {error}
} {!loading && !error && addresses.length === 0 && (No addresses tracked yet. Add one above to get started.
)} {addresses.length > 0 && (