'use client'; import React, { useState, useEffect, useRef } from 'react'; import { Button } from './ui/Button'; import { Input } from './ui/Input'; import { ErrorMessage } from './ui/ErrorMessage'; import { createBeneficiary } from '../lib/api'; interface AddBeneficiaryModalProps { isOpen: boolean; onClose: () => void; onSuccess: (beneficiary: { id: number; name: string }) => void; } export function AddBeneficiaryModal({ isOpen, onClose, onSuccess, }: AddBeneficiaryModalProps) { const [name, setName] = useState(''); const [address, setAddress] = useState(''); const [phone, setPhone] = useState(''); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const nameInputRef = useRef(null); useEffect(() => { if (isOpen) { setName(''); setAddress(''); setPhone(''); setError(null); setTimeout(() => { nameInputRef.current?.focus(); }, 100); } }, [isOpen]); useEffect(() => { const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape' && isOpen && !isLoading) { onClose(); } }; document.addEventListener('keydown', handleEscape); return () => document.removeEventListener('keydown', handleEscape); }, [isOpen, isLoading, onClose]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); const trimmedName = name.trim(); if (!trimmedName) { setError('Please enter a name for the beneficiary'); return; } setIsLoading(true); try { const result = await createBeneficiary({ name: trimmedName, address: address.trim() || undefined, phone: phone.trim() || undefined, }); onSuccess({ id: result.id, name: trimmedName }); onClose(); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to create beneficiary'); } finally { setIsLoading(false); } }; const handleBackdropClick = (e: React.MouseEvent) => { if (e.target === e.currentTarget && !isLoading) { onClose(); } }; if (!isOpen) return null; return (

Enter details for the person you want to care for

{error && ( setError(null)} /> )} { setName(e.target.value); setError(null); }} placeholder="e.g., Grandma Julia" disabled={isLoading} fullWidth autoComplete="off" /> setAddress(e.target.value)} placeholder="123 Main St, City, State" disabled={isLoading} fullWidth autoComplete="off" /> setPhone(e.target.value)} placeholder="+1 (555) 123-4567" disabled={isLoading} fullWidth autoComplete="off" />
); }