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 { Textarea } from '@/components/ui/textarea'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { RichTextEditor } from '@/components/RichTextEditor'; import { toast } from '@/hooks/use-toast'; import { Mail, AlertTriangle, Send, ChevronDown, ChevronUp, Webhook } from 'lucide-react'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; interface SmtpSettings { id?: string; smtp_host: string; smtp_port: number; smtp_username: string; smtp_password: string; smtp_from_name: string; smtp_from_email: string; smtp_use_tls: boolean; } 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 SHORTCODES_HELP = { common: ['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}'], access: ['{produk}', '{link_akses}'], consulting: ['{tanggal_konsultasi}', '{jam_konsultasi}', '{link_meet}'], event: ['{judul_event}', '{tanggal_event}', '{jam_event}', '{link_event}'], }; const DEFAULT_TEMPLATES = [ { key: 'payment_success', name: 'Pembayaran Berhasil' }, { key: 'access_granted', name: 'Akses Produk Diberikan' }, { key: 'order_created', name: 'Pesanan Dibuat' }, { key: 'payment_reminder', name: 'Pengingat Pembayaran' }, { key: 'consulting_scheduled', name: 'Konsultasi Terjadwal' }, { key: 'event_reminder', name: 'Reminder Webinar/Bootcamp' }, { key: 'bootcamp_progress', name: 'Progress Bootcamp' }, ]; const emptySmtp: SmtpSettings = { smtp_host: '', smtp_port: 587, smtp_username: '', smtp_password: '', smtp_from_name: '', smtp_from_email: '', smtp_use_tls: true, }; export function NotifikasiTab() { const [smtp, setSmtp] = useState(emptySmtp); const [templates, setTemplates] = useState([]); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [testEmail, setTestEmail] = useState(''); const [expandedTemplates, setExpandedTemplates] = useState>(new Set()); useEffect(() => { fetchData(); }, []); const fetchData = async () => { // Fetch SMTP settings const { data: smtpData } = await supabase.from('notification_settings').select('*').single(); if (smtpData) setSmtp(smtpData); // Fetch templates const { data: templatesData } = await supabase.from('notification_templates').select('*').order('key'); if (templatesData && templatesData.length > 0) { setTemplates(templatesData); } else { // Seed default templates if none exist await seedTemplates(); } setLoading(false); }; const seedTemplates = async () => { const toInsert = DEFAULT_TEMPLATES.map(t => ({ key: t.key, name: t.name, is_active: false, email_subject: '', email_body_html: '', webhook_url: '', })); const { data, error } = await supabase.from('notification_templates').insert(toInsert).select(); if (!error && data) setTemplates(data); }; const saveSmtp = async () => { setSaving(true); const payload = { ...smtp }; delete payload.id; if (smtp.id) { const { error } = await supabase.from('notification_settings').update(payload).eq('id', smtp.id); if (error) toast({ title: 'Error', description: error.message, variant: 'destructive' }); else toast({ title: 'Berhasil', description: 'Pengaturan SMTP disimpan' }); } else { const { data, error } = await supabase.from('notification_settings').insert(payload).select().single(); if (error) toast({ title: 'Error', description: error.message, variant: 'destructive' }); else { setSmtp(data); toast({ title: 'Berhasil', description: 'Pengaturan SMTP disimpan' }); } } setSaving(false); }; const sendTestEmail = async () => { if (!testEmail) return toast({ title: 'Error', description: 'Masukkan email tujuan', variant: 'destructive' }); console.log('Test email would be sent to:', testEmail, 'with SMTP config:', smtp); toast({ title: 'Info', description: `Email uji coba akan dikirim ke ${testEmail} (fitur sedang dikembangkan)` }); }; 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 toggleExpand = (id: string) => { setExpandedTemplates(prev => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; const isSmtpConfigured = smtp.smtp_host && smtp.smtp_username && smtp.smtp_password; if (loading) return
; return (
{/* SMTP Settings */} Pengaturan SMTP Konfigurasi server email untuk pengiriman notifikasi {!isSmtpConfigured && ( Konfigurasi SMTP belum lengkap. Email tidak akan terkirim. )}
setSmtp({ ...smtp, smtp_host: e.target.value })} placeholder="smtp.example.com" className="border-2" />
setSmtp({ ...smtp, smtp_port: parseInt(e.target.value) || 587 })} className="border-2" />
setSmtp({ ...smtp, smtp_username: e.target.value })} className="border-2" />
setSmtp({ ...smtp, smtp_password: e.target.value })} className="border-2" />
setSmtp({ ...smtp, smtp_from_name: e.target.value })} placeholder="Nama Bisnis" className="border-2" />
setSmtp({ ...smtp, smtp_from_email: e.target.value })} placeholder="noreply@example.com" className="border-2" />
setSmtp({ ...smtp, smtp_use_tls: checked })} />
setTestEmail(e.target.value)} placeholder="Email uji coba" className="border-2 max-w-xs" />
{/* Notification Templates */} Template Notifikasi Atur template email untuk berbagai jenis notifikasi

Shortcode yang tersedia:

Umum: {SHORTCODES_HELP.common.join(', ')}
Akses: {SHORTCODES_HELP.access.join(', ')}
Konsultasi: {SHORTCODES_HELP.consulting.join(', ')}
Event: {SHORTCODES_HELP.event.join(', ')}
{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" />
{template.last_payload_example && (
                          {JSON.stringify(template.last_payload_example, null, 2)}
                        
)}
))}
); }