import { useCallback, useEffect, useMemo, useState } from 'react' import { __ } from '@wordpress/i18n' import { useDispatch } from '@wordpress/data' import { store_name } from '../../../store/backend' import { Toggle } from '../Toggle/Toggle' import type { SetupChecklistEmailTemplate } from './types' import './EmailNotificationsStepContent.scss' interface EmailNotificationsStepContentProps { templates: SetupChecklistEmailTemplate[] actionUrl: string guideUrl: string } export const EmailNotificationsStepContent = ({ templates, actionUrl, guideUrl, }: EmailNotificationsStepContentProps) => { const { saveSetupChecklistEmailNotifications } = useDispatch(store_name) as { saveSetupChecklistEmailNotifications: ( templates: { id: number; enabled: boolean }[] ) => Promise<{ status?: string }> } const [enabledById, setEnabledById] = useState>({}) const [isSaving, setIsSaving] = useState(false) useEffect(() => { const initialState: Record = {} templates.forEach((template) => { initialState[template.id] = template.enabled }) setEnabledById(initialState) }, [templates]) const hasChanges = useMemo(() => { return templates.some( (template) => enabledById[template.id] !== template.enabled ) }, [enabledById, templates]) const handleToggle = useCallback((templateId: number, enabled: boolean) => { setEnabledById((current) => ({ ...current, [templateId]: enabled, })) }, []) const handleConfirm = useCallback(async () => { setIsSaving(true) try { const payload = templates.map((template) => ({ id: template.id, enabled: enabledById[template.id] ?? false, })) await saveSetupChecklistEmailNotifications(payload) } finally { setIsSaving(false) } }, [enabledById, saveSetupChecklistEmailNotifications, templates]) const getRecipientBadgeClass = (recipient: string) => { if (recipient === 'customer') { return 'wbk_emailNotificationsStep__badge--customer' } if (recipient === 'admin') { return 'wbk_emailNotificationsStep__badge--admin' } return 'wbk_emailNotificationsStep__badge--default' } if (!templates.length) { return (

{__( 'No email templates found. Create templates on the Email Notifications page.', 'webba-booking-lite' )}

{__('Go to Email Notifications', 'webba-booking-lite')} {guideUrl && ( {__('View Guide', 'webba-booking-lite')} )}
) } return (
    {templates.map((template) => (
  • {template.name} {template.type_label} {template.recipients.length > 0 && (
    {template.recipients.map((recipient, index) => ( {template.recipient_labels[index] || recipient} ))}
    )}
    handleToggle(template.id, enabled) } />
  • ))}
{__('Manage templates', 'webba-booking-lite')} {guideUrl && ( {__('View Guide', 'webba-booking-lite')} )}
{hasChanges && (

{__( 'Click Confirm to save your choices and complete this step.', 'webba-booking-lite' )}

)}
) }