import { useEffect, useState } from 'react'; import { getWhatsappConfig, saveWhatsappConfig, } from '../services/whatsappConfigService'; const fieldStyle = { width: '100%', border: '1px solid var(--color-border)', borderRadius: 12, padding: '0.7rem 0.85rem', background: '#fff', color: 'var(--color-text)', fontWeight: 600, fontSize: '0.92rem', boxSizing: 'border-box', }; const labelStyle = { display: 'block', fontSize: '0.8rem', fontWeight: 800, color: 'var(--color-text-soft)', marginBottom: '0.35rem', letterSpacing: '0.03em', textTransform: 'uppercase', }; export function WhatsappConfigModal({ onClose }) { const [loading, setLoading] = useState(true); const [currentConfig, setCurrentConfig] = useState(null); const [saving, setSaving] = useState(false); const [validating, setValidating] = useState(false); const [validation, setValidation] = useState(null); const [saveSuccess, setSaveSuccess] = useState(false); const [error, setError] = useState(''); const [form, setForm] = useState({ access_token: '', phone_number_id: '', api_version: 'v25.0', webhook_token: '', waba_id: '', }); useEffect(() => { getWhatsappConfig() .then((data) => { setCurrentConfig(data); setForm((f) => ({ ...f, phone_number_id: data.phone_number_id || '', api_version: data.api_version || 'v25.0', webhook_token: data.webhook_token || '', waba_id: data.waba_id || '', })); }) .catch(() => setError('Não foi possível carregar a configuração atual.')) .finally(() => setLoading(false)); }, []); function handleChange(field, value) { setValidation(null); setSaveSuccess(false); setError(''); setForm((f) => ({ ...f, [field]: value })); } async function handleValidate() { if (!form.access_token || !form.phone_number_id) return; setValidating(true); setValidation(null); const apiVersion = form.api_version || 'v25.0'; const url = `https://graph.facebook.com/${apiVersion}/${form.phone_number_id}` + `?access_token=${encodeURIComponent(form.access_token)}&fields=display_phone_number,verified_name,quality_rating`; try { const response = await fetch(url); const data = await response.json(); if (!response.ok) { setValidation({ valid: false, error: data?.error?.message || 'Credenciais inválidas', code: data?.error?.code, }); } else { setValidation({ valid: true, phone_number: data.display_phone_number, verified_name: data.verified_name, quality_rating: data.quality_rating, }); } } catch { setValidation({ valid: false, error: 'Sem acesso à internet para validar' }); } finally { setValidating(false); } } async function handleSave() { setSaving(true); setSaveSuccess(false); setError(''); try { await saveWhatsappConfig(form); setSaveSuccess(true); setTimeout(onClose, 1200); } catch (err) { const msg = err?.message || ''; setError(`Erro ao salvar${msg ? `: ${msg}` : '. Verifique se a migration 025 foi executada no banco.'}`); } finally { setSaving(false); } } const canValidate = !!(form.access_token && form.phone_number_id); const canSave = !!(form.access_token || form.phone_number_id) && !saving; return (
e.stopPropagation()} style={{ width: 'min(540px, 100%)', borderRadius: 22, border: '1px solid var(--color-border)', background: '#fff', padding: '1.4rem', display: 'grid', gap: '1rem', boxShadow: 'var(--shadow-lg)', maxHeight: '90vh', overflowY: 'auto', }} > {/* Header */}
Configurar WhatsApp Meta Cloud API
{/* Status atual */} {!loading && currentConfig && (
{currentConfig.is_configured ? '✅' : '⚠️'}
{currentConfig.is_configured ? 'Integração configurada' : 'Configuração incompleta'} {currentConfig.is_configured && ( Token via {currentConfig.token_source === 'database' ? 'banco de dados' : 'variável de ambiente'} {currentConfig.phone_number_id ? ` · ID: ${currentConfig.phone_number_id}` : ''} )} {!currentConfig.is_configured && ( Preencha o Token e o Phone Number ID abaixo )}
)} {loading && (

Carregando configuração atual…

)} {/* Formulário */}
handleChange('access_token', e.target.value)} style={fieldStyle} />
handleChange('phone_number_id', e.target.value)} style={fieldStyle} />
handleChange('waba_id', e.target.value)} style={fieldStyle} />

Necessário para criar e sincronizar templates HSM.

handleChange('api_version', e.target.value)} style={fieldStyle} />
handleChange('webhook_token', e.target.value)} style={fieldStyle} />
{/* Resultado da validação */} {validation && (
{validation.valid ? ( <> ✅ Credenciais válidas {validation.verified_name && `Conta: ${validation.verified_name}`} {validation.phone_number && ` · ${validation.phone_number}`} {validation.quality_rating && ` · Qualidade: ${validation.quality_rating}`} ) : ( <> ❌ Credenciais inválidas {validation.error || 'Verifique o Token e o Phone Number ID'} {validation.code ? ` (código ${validation.code})` : ''} )}
)} {/* Feedback de erro geral */} {error && (

{error}

)} {/* Feedback de sucesso */} {saveSuccess && (

✅ Configuração salva com sucesso!

)} {/* Ações */}
); }