import { useEffect, useState } from 'react'; import { supabase } from '@/integrations/supabase/client'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { RichTextEditor } from '@/components/RichTextEditor'; import { toast } from '@/hooks/use-toast'; import { Mail, ChevronDown, ChevronUp, Webhook } from 'lucide-react'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; import { EmailTemplatePreview } from '@/components/admin/EmailTemplatePreview'; interface NotificationTemplate { id: string; key: string; name: string; is_active: boolean; email_subject: string; email_body_html: string; webhook_url: string; last_payload_example: Record | null; } const RELEVANT_SHORTCODES = { 'payment_success': ['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}', '{produk}', '{link_akses}', '{thank_you_page}'], 'access_granted': ['{nama}', '{email}', '{produk}', '{link_akses}', '{username_akses}', '{password_akses}', '{kadaluarsa_akses}'], 'order_created': ['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}', '{produk}', '{payment_link}', '{thank_you_page}'], 'payment_reminder': ['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}', '{batas_pembayaran}', '{jumlah_pembayaran}', '{bank_tujuan}', '{nomor_rekening}', '{payment_link}', '{thank_you_page}'], 'consulting_scheduled': ['{nama}', '{email}', '{tanggal_konsultasi}', '{jam_konsultasi}', '{durasi_konsultasi}', '{link_meet}', '{jenis_konsultasi}', '{topik_konsultasi}'], 'event_reminder': ['{nama}', '{email}', '{judul_event}', '{tanggal_event}', '{jam_event}', '{link_event}', '{lokasi_event}', '{kapasitas_event}'], 'bootcamp_progress': ['{nama}', '{email}', '{judul_bootcamp}', '{progres_bootcamp}', '{modul_selesai}', '{modul_selanjutnya}', '{link_progress}'], }; const DEFAULT_TEMPLATES: { key: string; name: string; defaultSubject: string; defaultBody: string }[] = [ { key: 'payment_success', name: 'Pembayaran Berhasil', defaultSubject: 'Pembayaran Berhasil - Order #{order_id}', defaultBody: `

Pembayaran Berhasil! 🎉

Halo {nama}, terima kasih atas pembayaran Anda. Kami senang menginformasikan bahwa pembayaran Anda telah berhasil dikonfirmasi.

Detail Pembayaran

Parameter Value
Order ID {order_id}
Tanggal Pesanan {tanggal_pesanan}
Total Pembayaran {total}
Metode Pembayaran {metode_pembayaran}

Produk yang Dibeli

{produk}

Lihat Detail Pesanan

Info: Anda akan menerima email terpisah untuk mengakses produk Anda.
` }, { key: 'access_granted', name: 'Akses Produk Diberikan', defaultSubject: 'Akses Anda Sudah Aktif - {produk}', defaultBody: `

Selamat! Akses Aktif 🚀

Halo {nama}, selamat! Akses Anda ke {produk} sudah aktif dan siap digunakan.

Anda sekarang dapat mengakses semua materi dan fitur yang tersedia dalam produk ini.

ACCESS GRANTED

Akses Sekarang

Penting:

` }, { key: 'order_created', name: 'Pesanan Dibuat', defaultSubject: 'Pesanan #{order_id} Sedang Diproses', defaultBody: `

Pesanan Diterima ✅

Halo {nama}, terima kasih telah melakukan pesanan. Kami telah menerima pesanan Anda dengan detail sebagai berikut:

Informasi Pesanan Detail
Nomor Pesanan {order_id}
Total Pembayaran {total}
Status Menunggu Pembayaran

Langkah Selanjutnya:

  1. Selesaikan pembayaran sebelum batas waktu
  2. Setelah pembayaran dikonfirmasi, Anda akan menerima email akses produk
  3. Simpan bukti pembayaran untuk arsip Anda
Penting: Segera lakukan pembayaran agar pesanan tidak kedaluwarsa.
` }, { key: 'payment_reminder', name: 'Pengingat Pembayaran', defaultSubject: 'Reminder: Segera Selesaikan Pembayaran #{order_id}', defaultBody: `

Reminder Pembayaran ⏰

Halo {nama}, ini adalah pengingat bahwa pesanan Anda masih menunggu pembayaran.

Detail Pesanan Informasi
Order ID {order_id}
Total Pembayaran {total}
Tanggal Pesanan {tanggal_pesanan}

Bayar Sekarang

Peringatan: Jika pembayaran tidak diselesaikan dalam batas waktu, pesanan akan otomatis dibatalkan.
` }, { key: 'consulting_scheduled', name: 'Konsultasi Terjadwal', defaultSubject: 'Konsultasi Terjadwal - {tanggal_konsultasi}', defaultBody: `

Sesi Konsultasi Dikonfirmasi 📅

Halo {nama}, sesi konsultasi Anda telah berhasil dijadwalkan. Berikut adalah detailnya:

Detail Sesi Informasi
Tanggal {tanggal_konsultasi}
Waktu {jam_konsultasi}
Link Meeting {link_meet}

Bergabung ke Meeting

Persiapan Sebelum Sesi:

Tip: Gunakan Google Chrome untuk pengalaman meeting terbaik.
` }, { key: 'event_reminder', name: 'Reminder Webinar/Bootcamp', defaultSubject: 'Reminder: {judul_event} - {tanggal_event}', defaultBody: `

Jangan Sampai Ketinggalan! 🔥

Halo {nama}, jangan lupa bahwa {judul_event} akan segera dimulai!

EVENT STARTING SOON!

{judul_event}
Event Detail Informasi
Judul Event {judul_event}
Tanggal {tanggal_event}
Waktu {jam_event}

Bergabung Sekarang

Persiapan Event:

` }, { key: 'bootcamp_progress', name: 'Progress Bootcamp', defaultSubject: 'Update Progress Bootcamp - {nama}', defaultBody: `

Progress Update 📈

Halo {nama}, ini adalah update terbaru tentang progress bootcamp Anda.

PROGRESS ANDA
75%
Completed Modules: 15/20

Module Selesai:

Module Berikutnya:

Lanjut Belajar

Motivasi: Anda sudah 75% selesai! Terus semangat, kesuksesan Anda sudah di depan mata!
` }, ]; export function NotifikasiTab() { const [templates, setTemplates] = useState([]); const [loading, setLoading] = useState(true); const [expandedTemplates, setExpandedTemplates] = useState>(new Set()); const [testingTemplate, setTestingTemplate] = useState(null); const [previewTemplate, setPreviewTemplate] = useState(null); const [isPreviewOpen, setIsPreviewOpen] = useState(false); useEffect(() => { fetchData(); }, []); const fetchData = async () => { try { console.log('Fetching templates...'); // Fetch templates const { data: templatesData, error: fetchError } = await supabase.from('notification_templates').select('*').order('key'); if (fetchError) { console.error('Error fetching templates:', fetchError); toast({ title: 'Error', description: 'Gagal mengambil template: ' + fetchError.message, variant: 'destructive' }); setLoading(false); return; } console.log('Templates data:', templatesData); console.log('Template count:', templatesData?.length); if (templatesData && templatesData.length > 0) { console.log('Setting templates from database:', templatesData.length); // Check if any templates have empty content const emptyTemplates = templatesData.filter(t => !t.email_subject || !t.email_body_html); if (emptyTemplates.length > 0) { console.log('Found templates with empty content:', emptyTemplates.map(t => ({ key: t.key, name: t.name }))); console.log('Reseeding templates with empty content...'); await forceSeedTemplates(); } else { setTemplates(templatesData); } } else { console.log('No templates found, seeding default templates...'); // Seed default templates if none exist await seedTemplates(); } } catch (error) { console.error('Unexpected error in fetchData:', error); toast({ title: 'Error', description: 'Terjadi kesalahan tak terduga saat mengambil data', variant: 'destructive' }); } finally { setLoading(false); } }; const forceSeedTemplates = async () => { try { console.log('Force reseed: Deleting existing templates...'); // Delete existing templates const { error: deleteError } = await supabase.from('notification_templates').delete().neq('id', ''); if (deleteError) { console.error('Error deleting templates:', deleteError); } console.log('Force reseed: Inserting default templates...'); await seedTemplates(); } catch (error) { console.error('Error in forceSeedTemplates:', error); } }; const seedTemplates = async () => { try { console.log('Seeding default templates...'); const toUpsert = DEFAULT_TEMPLATES.map(t => ({ key: t.key, name: t.name, is_active: false, email_subject: t.defaultSubject, email_body_html: t.defaultBody, webhook_url: '', })); console.log('Upserting templates:', toUpsert.length); const { data, error } = await supabase .from('notification_templates') .upsert(toUpsert, { onConflict: 'key', ignoreDuplicates: false }) .select(); if (error) { console.error('Error seeding templates:', error); toast({ title: 'Error', description: 'Gagal membuat template default: ' + error.message, variant: 'destructive' }); return; } console.log('Templates seeded/updated successfully:', data); if (data) { setTemplates(data); toast({ title: 'Berhasil', description: `Berhasil membuat ${data.length} template default` }); } } catch (error) { console.error('Unexpected error in seedTemplates:', error); toast({ title: 'Error', description: 'Terjadi kesalahan saat membuat template default', variant: 'destructive' }); } }; const updateTemplate = async (template: NotificationTemplate) => { const { id, key, name, ...updates } = template; const { error } = await supabase.from('notification_templates').update(updates).eq('id', id); if (error) toast({ title: 'Error', description: error.message, variant: 'destructive' }); else toast({ title: 'Berhasil', description: `Template "${name}" disimpan` }); }; const sendTestEmail = async (template: NotificationTemplate & { test_email?: string }) => { if (!template.test_email) { toast({ title: 'Error', description: 'Masukkan email tujuan', variant: 'destructive' }); return; } setTestingTemplate(template.id); try { // Fetch email settings from notification_settings const { data: emailData } = await supabase .from('notification_settings') .select('*') .single(); if (!emailData || !emailData.api_token || !emailData.from_email) { throw new Error('Konfigurasi email provider belum lengkap'); } // Import EmailTemplateRenderer and ShortcodeProcessor const { EmailTemplateRenderer, ShortcodeProcessor } = await import('@/lib/email-templates/master-template'); // Process shortcodes and render with master template const processedSubject = ShortcodeProcessor.process(template.email_subject || ''); const processedContent = ShortcodeProcessor.process(template.email_body_html || ''); const fullHtml = EmailTemplateRenderer.render({ subject: processedSubject, content: processedContent, brandName: 'ACCESS HUB' }); // Send test email using send-email-v2 const { data, error } = await supabase.functions.invoke('send-email-v2', { body: { recipient: template.test_email, api_token: emailData.api_token, from_name: emailData.from_name, from_email: emailData.from_email, subject: processedSubject, content: fullHtml, }, }); if (error) throw error; if (data?.success) { toast({ title: 'Berhasil', description: `Email test "${template.name}" dikirim ke ${template.test_email}` }); } else { throw new Error(data?.message || 'Failed to send test email'); } } catch (error: any) { console.error('Test template email error:', error); toast({ title: 'Error', description: error.message || 'Gagal mengirim email test template', variant: 'destructive' }); } finally { setTestingTemplate(null); } }; const toggleExpand = (id: string) => { setExpandedTemplates(prev => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; if (loading) return
; return (
{/* Notification Templates Info */} Konfigurasi Email Pengaturan provider email (Mailketing API) ada di tab Integrasi Konfigurasikan provider email di tab Integrasi → Provider Email untuk mengirim notifikasi. Gunakan Mailketing API untuk pengiriman email yang andal.
Gunakan jika template kosong atau bermasalah
{/* Notification Templates */} Template Notifikasi Atur template email untuk berbagai jenis notifikasi

Shortcode yang tersedia:

Setiap template memiliki shortcode yang relevan dengan jenis notifikasinya. Lihat detail template untuk shortcode yang tersedia.

Penting: Email dikirim melalui Mailketing API yang dikonfigurasi di tab Integrasi. Pastikan API token valid dan domain pengirim sudah terdaftar di Mailketing. Toggle "Aktifkan" hanya mengontrol pengiriman email. Jika webhook_url diisi, sistem tetap akan mengirim payload ke URL tersebut meskipun email dinonaktifkan.

{templates.map((template) => ( toggleExpand(template.id)} >
{ const updated = { ...template, is_active: checked }; setTemplates(templates.map(t => t.id === template.id ? updated : t)); updateTemplate(updated); }} onClick={(e) => e.stopPropagation()} />

{template.name}

{template.key}

{expandedTemplates.has(template.id) ? ( ) : ( )}
{ setTemplates(templates.map(t => t.id === template.id ? { ...t, email_subject: e.target.value } : t )); }} placeholder="Subjek email..." className="border-2" />
{ setTemplates(templates.map(t => t.id === template.id ? { ...t, email_body_html: html } : t )); }} placeholder="Tulis isi email..." />
{ setTemplates(templates.map(t => t.id === template.id ? { ...t, webhook_url: e.target.value } : t )); }} placeholder="https://n8n.example.com/webhook/..." className="border-2" />
{/* Relevant Shortcodes for this Template */}

Shortcodes untuk template ini:

{RELEVANT_SHORTCODES[template.key as keyof typeof RELEVANT_SHORTCODES]?.map(shortcode => ( {shortcode} )) || Tidak ada shortcode khusus untuk template ini}
{template.last_payload_example && (
                          {JSON.stringify(template.last_payload_example, null, 2)}
                        
)}
))}
{/* Modal Email Preview */} {previewTemplate && ( setIsPreviewOpen(false)} onTest={sendTestEmail} isTestSending={testingTemplate === previewTemplate.id} /> )}
); }