import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { ACCOUNT_TYPES, CURRENCY_OPTIONS, formatAccountType, type AccountType, type Bank, type CurrencyCode, } from '@/types/account'; import { __ } from '@/utils/i18n'; import { useCallback, useEffect, useState } from 'react'; import { BankCombobox } from './bank-combobox'; import { CustomBankData, CustomBankForm } from './custom-bank-form'; export interface AccountFormData { displayName: string; bankId: number | null; type: AccountType | null; currencyCode: CurrencyCode | null; customBank: CustomBankData | null; } interface AccountFormProps { initialValues?: { displayName: string; bank: Bank; type: AccountType; currencyCode: CurrencyCode; }; forceAccountType?: AccountType; onChange: (data: AccountFormData) => void; } const initialCustomBankData: CustomBankData = { name: '', logo: null, logoPreview: null, }; export function AccountForm({ initialValues, forceAccountType, onChange, }: AccountFormProps) { const [displayName, setDisplayName] = useState( initialValues?.displayName ?? '', ); const [selectedBankId, setSelectedBankId] = useState( initialValues?.bank.id ?? null, ); const [selectedType, setSelectedType] = useState( initialValues?.type ?? forceAccountType ?? null, ); const [selectedCurrency, setSelectedCurrency] = useState(initialValues?.currencyCode ?? null); const [isCreatingCustomBank, setIsCreatingCustomBank] = useState(false); const [customBankData, setCustomBankData] = useState( initialCustomBankData, ); useEffect(() => { onChange({ displayName, bankId: isCreatingCustomBank ? null : selectedBankId, type: selectedType, currencyCode: selectedCurrency, customBank: isCreatingCustomBank ? customBankData : null, }); }, [ displayName, selectedBankId, selectedType, selectedCurrency, isCreatingCustomBank, customBankData, onChange, ]); useEffect(() => { if (initialValues) { setDisplayName(initialValues.displayName); setSelectedBankId(initialValues.bank.id); setSelectedType(initialValues.type); setSelectedCurrency(initialValues.currencyCode); setIsCreatingCustomBank(false); setCustomBankData(initialCustomBankData); } }, [initialValues]); const handleCreateCustomBank = useCallback((searchQuery: string) => { setIsCreatingCustomBank(true); setCustomBankData({ name: searchQuery, logo: null, logoPreview: null, }); setSelectedBankId(null); }, []); const handleCancelCustomBank = useCallback(() => { setIsCreatingCustomBank(false); setCustomBankData(initialCustomBankData); }, []); return ( <>
setDisplayName(e.target.value)} placeholder={__('Account name')} required />
{isCreatingCustomBank ? ( ) : ( <> )}
{(selectedType === 'investment' || selectedType === 'retirement') && (

{__( "This account type is for balance tracking only and\n doesn't support transactions.", )}

)}
); }