import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import { Button } from "../../../components/ui/button"; import { Input } from "../../../components/ui/input"; import { AmountInput } from "../../../components/ui/AmountInput"; import { Select } from "../../../components/ui/select"; import { Label } from "../../../components/ui/label"; import { cn } from "../../../lib/utils"; import type { Wallet } from "../../../types"; import { useEffect } from "react"; export const transactionSchema = z.object({ type: z.enum(['expense', 'income', 'transfer']), amount: z.coerce.number().positive("Amount must be positive"), currency: z.string().min(1, "Currency is required"), wallet_id: z.coerce.number().min(1, "Wallet is required"), to_wallet_id: z.coerce.number().optional().nullable(), category: z.string().optional(), note: z.string().optional() }).refine(data => { if (data.type === 'transfer' && !data.to_wallet_id) return false; return true; }, { message: "Destination wallet is required", path: ["to_wallet_id"] }).refine(data => { if (data.type === 'transfer' && data.wallet_id === data.to_wallet_id) return false; return true; }, { message: "Cannot transfer to same wallet", path: ["to_wallet_id"] }); export type TransactionFormValues = z.infer; const CATEGORIES = ['Food', 'Transport', 'Utilities', 'Shopping', 'Entertainment', 'Health', 'Salary', 'Investment', 'Other']; export function TransactionForm({ wallets, onSubmit, isSubmitting, submitError }: { wallets: Wallet[], onSubmit: (values: TransactionFormValues) => void, isSubmitting: boolean, submitError: string }) { const form = useForm({ resolver: zodResolver(transactionSchema), defaultValues: { type: 'expense', amount: '' as any, currency: wallets[0]?.currency || 'USD', wallet_id: wallets[0]?.id || 0, category: 'Other', note: '' } }); const type = form.watch('type'); const walletId = form.watch('wallet_id'); useEffect(() => { const w = wallets.find(w => w.id === Number(walletId)); if (w) { form.setValue('currency', w.currency); } }, [walletId, wallets, form]); return (
{['expense', 'income', 'transfer'].map(t => ( ))}
{form.formState.errors.amount &&

{form.formState.errors.amount.message}

}
{type === 'transfer' && (
{form.formState.errors.to_wallet_id &&

{form.formState.errors.to_wallet_id.message}

}
)} {type !== 'transfer' && (
)}
{submitError && (
{submitError}
)}
); }