'use client' import { SubmitButton } from '@/components/submit-button' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from '@/components/ui/card' import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form' import { HoverCard, HoverCardContent, HoverCardTrigger, } from '@/components/ui/hover-card' import { Input } from '@/components/ui/input' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select' import { getGroup } from '@/lib/api' import { GroupFormValues, groupFormSchema } from '@/lib/schemas' import { zodResolver } from '@hookform/resolvers/zod' import { Save, Trash2 } from 'lucide-react' import Link from 'next/link' import { useEffect, useState } from 'react' import { useFieldArray, useForm } from 'react-hook-form' export type Props = { group?: NonNullable>> onSubmit: ( groupFormValues: GroupFormValues, participantId?: string, ) => Promise protectedParticipantIds?: string[] } export function GroupForm({ group, onSubmit, protectedParticipantIds = [], }: Props) { const form = useForm({ resolver: zodResolver(groupFormSchema), defaultValues: group ? { name: group.name, currency: group.currency, participants: group.participants, } : { name: '', currency: '', participants: [{ name: 'John' }, { name: 'Jane' }, { name: 'Jack' }], }, }) const { fields, append, remove } = useFieldArray({ control: form.control, name: 'participants', keyName: 'key', }) const [activeUser, setActiveUser] = useState(null) useEffect(() => { if (activeUser === null) { const currentActiveUser = fields.find( (f) => f.id === localStorage.getItem(`${group?.id}-activeUser`), )?.name || 'None' setActiveUser(currentActiveUser) } }, [activeUser, fields, group?.id]) const updateActiveUser = () => { if (!activeUser) return if (group?.id) { const participant = group.participants.find((p) => p.name === activeUser) if (participant?.id) { localStorage.setItem(`${group.id}-activeUser`, participant.id) } else { localStorage.setItem(`${group.id}-activeUser`, activeUser) } } else { localStorage.setItem('newGroup-activeUser', activeUser) } } return (
{ await onSubmit( values, group?.participants.find((p) => p.name === activeUser)?.id ?? undefined, ) })} > Group information ( Group name Enter a name for your group. )} /> ( Currency symbol We’ll use it to display amounts. )} /> Participants Enter the name for each participant
    {fields.map((item, index) => (
  • ( Participant #{index + 1}
    {item.id && protectedParticipantIds.includes(item.id) ? ( This participant is part of expenses, and can not be removed. ) : ( )}
    )} />
  • ))}
Local settings These settings are set per-device, and are used to customize your experience.
{activeUser !== null && ( Active user User used as default for paying expenses. )}
{group ? <>Save : <> Create} {!group && ( )}
) }