'use client' import { AsyncButton } from '@/components/async-button' import { SubmitButton } from '@/components/submit-button' import { Button } from '@/components/ui/button' import { Card, CardContent, CardFooter, CardHeader, CardTitle, } from '@/components/ui/card' import { Checkbox } from '@/components/ui/checkbox' import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form' import { Input } from '@/components/ui/input' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { getExpense, getGroup } from '@/lib/api' import { ExpenseFormValues, expenseFormSchema } from '@/lib/schemas' import { zodResolver } from '@hookform/resolvers/zod' import { useSearchParams } from 'next/navigation' import { useForm } from 'react-hook-form' export type Props = { group: NonNullable>> expense?: NonNullable>> onSubmit: (values: ExpenseFormValues) => Promise onDelete?: () => Promise } export function ExpenseForm({ group, expense, onSubmit, onDelete }: Props) { const isCreate = expense === undefined const searchParams = useSearchParams() const form = useForm({ resolver: zodResolver(expenseFormSchema), defaultValues: expense ? { title: expense.title, amount: String(expense.amount / 100) as unknown as number, // hack paidBy: expense.paidById, paidFor: expense.paidFor.map(({ participantId }) => participantId), isReimbursement: expense.isReimbursement, } : searchParams.get('reimbursement') ? { title: 'Reimbursement', amount: String( (Number(searchParams.get('amount')) || 0) / 100, ) as unknown as number, // hack paidBy: searchParams.get('from') ?? undefined, paidFor: [searchParams.get('to') ?? undefined], isReimbursement: true, } : { title: '', amount: 0, paidFor: [], isReimbursement: false }, }) return (
onSubmit(values))}> {isCreate ? <>Create expense : <>Edit expense} ( Expense title Enter a description for the expense. )} /> ( Paid by Select the participant who paid the expense. )} /> ( Amount
{group.currency}
(
This is a reimbursement
)} />
)} /> (
Paid for Select who the expense was paid for.
{group.participants.map(({ id, name }) => ( { return ( { return checked ? field.onChange([...field.value, id]) : field.onChange( field.value?.filter( (value) => value !== id, ), ) }} /> {name} ) }} /> ))}
)} />
Creating… : <>Saving…} > {isCreate ? <>Create : <>Save} {!isCreate && onDelete && ( Delete )}
) }