import { useEffect, useState } from 'react'; import type { ReactElement } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { Loader2, Send } from 'lucide-react'; import { Modal, SecondaryButton, PrimaryButton, FormField } from '@/components/shared'; import { moduleService } from '@/services/module-service'; import type { Module } from '@/types/module'; const webhookSyncSchema = z.object({ sync_webhook_url: z.string().min(1, 'Webhook URL is required').url('Please enter a valid URL'), }); type WebhookSyncFormData = z.infer; interface WebhookSyncModalProps { isOpen: boolean; onClose: () => void; moduleId: string | null; onLoadModule: (id: string) => Promise; } export const WebhookSyncModal = ({ isOpen, onClose, moduleId, onLoadModule, }: WebhookSyncModalProps): ReactElement | null => { const [module, setModule] = useState(null); const [isLoading, setIsLoading] = useState(false); const [isSyncing, setIsSyncing] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const { register, handleSubmit, setValue, reset, formState: { errors, isValid }, } = useForm({ resolver: zodResolver(webhookSyncSchema), mode: 'onChange', }); // Load module data when modal opens useEffect(() => { if (isOpen && moduleId) { const loadModule = async (): Promise => { try { setIsLoading(true); setError(null); setSuccess(null); const data = await onLoadModule(moduleId); setModule(data); setValue('sync_webhook_url', data.sync_webhook_url || data.webhookurl || '', { shouldValidate: true }); } catch (err: any) { setError(err?.response?.data?.error?.message || 'Failed to load module details'); } finally { setIsLoading(false); } }; loadModule(); } else { setModule(null); reset({ sync_webhook_url: '' }); setError(null); setSuccess(null); } }, [isOpen, moduleId, onLoadModule, setValue, reset]); const handleSync = async (data: WebhookSyncFormData): Promise => { if (!moduleId) return; try { setIsSyncing(true); setError(null); setSuccess(null); const response = await moduleService.syncWebhookData(moduleId, data.sync_webhook_url); if (response.success) { setSuccess('Identity data sync triggered successfully. The module application will receive the data shortly.'); } else { setError('Failed to trigger sync'); } } catch (err: any) { setError(err?.response?.data?.error?.message || 'Failed to trigger identity sync'); } finally { setIsSyncing(false); } }; return ( Close {isSyncing ? : } Sync Data } >
{isLoading && (
)} {error && (

{error}

)} {success && (

{success}

)} {!isLoading && module && (

{module.name}

{module.module_id}

Data Synchronized:

  • Tenants
  • Roles
  • Departments
  • Designations
  • Suppliers
  • Users
)}
); };