import React, { useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { userServiceClient } from "@/grpcweb"; import useCurrentUser from "@/hooks/useCurrentUser"; import useLoading from "@/hooks/useLoading"; import { useTranslate } from "@/utils/i18n"; interface Props { open: boolean; onOpenChange: (open: boolean) => void; webhookName?: string; onSuccess?: () => void; } interface State { displayName: string; url: string; } function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Props) { const t = useTranslate(); const currentUser = useCurrentUser(); const [state, setState] = useState({ displayName: "", url: "", }); const requestState = useLoading(false); const isCreating = webhookName === undefined; useEffect(() => { if (webhookName && currentUser) { // For editing, we need to get the webhook data // Since we're using user webhooks now, we need to list all webhooks and find the one we want userServiceClient .listUserWebhooks({ parent: currentUser.name, }) .then((response) => { const webhook = response.webhooks.find((w) => w.name === webhookName); if (webhook) { setState({ displayName: webhook.displayName, url: webhook.url, }); } }); } }, [webhookName, currentUser]); const setPartialState = (partialState: Partial) => { setState({ ...state, ...partialState, }); }; const handleTitleInputChange = (e: React.ChangeEvent) => { setPartialState({ displayName: e.target.value, }); }; const handleUrlInputChange = (e: React.ChangeEvent) => { setPartialState({ url: e.target.value, }); }; const handleSaveBtnClick = async () => { if (!state.displayName || !state.url) { toast.error(t("message.fill-all-required-fields")); return; } if (!currentUser) { toast.error("User not authenticated"); return; } try { requestState.setLoading(); if (isCreating) { await userServiceClient.createUserWebhook({ parent: currentUser.name, webhook: { displayName: state.displayName, url: state.url, }, }); } else { await userServiceClient.updateUserWebhook({ webhook: { name: webhookName, displayName: state.displayName, url: state.url, }, updateMask: ["display_name", "url"], }); } onSuccess?.(); onOpenChange(false); requestState.setFinish(); } catch (error: any) { console.error(error); toast.error(error.details); requestState.setError(); } }; return ( {isCreating ? t("setting.webhook-section.create-dialog.create-webhook") : t("setting.webhook-section.create-dialog.edit-webhook")}
); } export default CreateWebhookDialog;