"use client" import { useTransition, type ReactElement } from "react" import { useTranslations } from "next-intl" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import { z } from "zod" import { Loader2, Save } from "lucide-react" import { toast } from "sonner" import { Button } from "@/shared/components/ui/button" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card" import { Form } from "@/shared/components/ui/form" import { TextField } from "@/shared/components/form-fields/text-field" import { SelectField } from "@/shared/components/form-fields/select-field" import type { UserProfile } from "@/modules/users/data-access" import { useSettingsService } from "@/modules/settings/components/settings-service-context" const profileFormSchema = z.object({ name: z.string().min(2, "Name must be at least 2 characters."), email: z.string().email().optional(), role: z.string().optional(), phone: z.string().optional(), address: z.string().optional(), gender: z.string().optional(), age: z.string().optional(), }) type ProfileFormValues = z.infer const GENDER_OPTIONS = [ { value: "male", label: "Male" }, { value: "female", label: "Female" }, { value: "other", label: "Other" }, { value: "prefer_not_to_say", label: "Prefer not to say" }, ] export function ProfileSettingsForm({ user }: { user: UserProfile }): ReactElement { const t = useTranslations("settings.profile") const { profile } = useSettingsService() const [isPending, startTransition] = useTransition() const form = useForm({ resolver: zodResolver(profileFormSchema), defaultValues: { name: user.name ?? "", email: user.email ?? "", role: user.role ?? "", phone: user.phone ?? "", address: user.address ?? "", gender: user.gender ?? "", age: user.age !== undefined && user.age !== null ? String(user.age) : "", }, }) function onSubmit(data: ProfileFormValues): void { startTransition(async () => { try { const ageNum = data.age ? Number(data.age) : undefined const result = await profile.updateProfile({ name: data.name, phone: data.phone || undefined, address: data.address || undefined, gender: data.gender || undefined, age: ageNum !== undefined && !Number.isNaN(ageNum) ? ageNum : undefined, }) if (result.success) { toast.success(t("success")) } else { toast.error(result.message || t("failure")) } } catch { toast.error(t("failure")) } }) } return ( {t("title")} {t("description")}
) }