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 { webhookServiceClient } from "@/grpcweb"; import useCurrentUser from "@/hooks/useCurrentUser"; import useLoading from "@/hooks/useLoading"; import { useTranslate } from "@/utils/i18n"; interface CreateWebhookDialogProps { open: boolean; onOpenChange: (open: boolean) => void; webhookName?: string; onSuccess?: () => void; } interface State { displayName: string; url: string; } export function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: CreateWebhookDialogProps) { const t = useTranslate(); const currentUser = useCurrentUser(); const [state, setState] = useState({ displayName: "", url: "", }); const requestState = useLoading(false); const isCreating = webhookName === undefined; useEffect(() => { if (webhookName) { webhookServiceClient .getWebhook({ name: webhookName, }) .then((webhook) => { setState({ displayName: webhook.displayName, url: webhook.url, }); }); } }, [webhookName]); 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 webhookServiceClient.createWebhook({ parent: currentUser.name, webhook: { displayName: state.displayName, url: state.url, }, }); } else { await webhookServiceClient.updateWebhook({ 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;