"use client" import { Dispatch, SetStateAction, useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Checkbox } from "@/components/ui/checkbox"; import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { Spinner } from "@/components/ui/spinner"; import { useTranslations } from "next-intl"; import { useFieldArray, useForm, Controller, SubmitHandler } from "react-hook-form"; import { Plus, Trash2 } from "lucide-react"; import { updateClient } from "@/actions/clients"; import type { OAuthClient } from "@/types"; interface FormData { name: string; redirect_uris: { value: string }[]; scopes: string[]; } interface Props { client: OAuthClient | null; onClose: () => void; setClients: Dispatch>; } const SCOPES = ["profile:read", "profile:edit"] as const; export function UpdateClientDialog({ client, onClose, setClients }: Props) { const t = useTranslations("MePage.items.applications.dialog"); const [error, setError] = useState(null); const { register, handleSubmit, control, reset, formState: { errors, isSubmitting }} = useForm({ defaultValues: { name: "", redirect_uris: [{ value: "" }], scopes: [] }, }); const { fields, append, remove } = useFieldArray({ control, name: "redirect_uris", }); useEffect(() => { if (client) { reset({ name: client.name, redirect_uris: client.redirect_uris.map((value) => ({ value })), scopes: client.scopes, }); } }, [client, reset]); const onSubmit: SubmitHandler = async (data) => { if (!client) return; setError(null); const result = await updateClient(client.id, { name: data.name, redirect_uris: data.redirect_uris.map((r) => r.value).filter(Boolean), scopes: data.scopes, }); if (!result.success || !result.client) { setError(result.message ?? null); return; } setClients((prev) => prev ? prev.map((c) => (c.id === result.client!.id ? result.client! : c)) : prev ); onClose(); }; return ( !open && onClose()}> {t("editTitle")} {t("editSubtitle")}
{t("name.title")} {errors.name && {errors.name.message}} {t("redirectUris.title")}
{fields.map((field, index) => (
))} {errors.redirect_uris?.[0]?.value && ( {errors.redirect_uris[0]?.value?.message} )}
{t("scopes.title")} (
{SCOPES.map((scope) => ( ))}
)} /> {errors.scopes && {errors.scopes.message}}
{error && {error}}
); }