import { __ } from '@wordpress/i18n'; import React, { useState, useEffect } from 'react'; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Toaster } from "@/components/ui/toaster" import { useToast } from "@/components/hooks/use-toast" import { Settings, MessageSquare, Wand2, Share2, MoreHorizontal, HelpCircle, ExternalLink, CheckCircle2, XCircle, RefreshCw } from 'lucide-react'; import ChatWidgetSettings from './ChatWidgetSettings'; import AiConfigSettings from './AiConfigSettings'; import IntegrationsSettings from './IntegrationsSettings'; import MiscSettings from './MiscSettings'; import {buttonVariants} from "../../../components/ui/button"; const AISK_API = (window.AiskSettings?.apiUrl || '/wp-json/aisk/v1').replace(/\/+$/, ''); const SettingsApp = () => { const { toast } = useToast() const [settings, setSettings] = useState({ general: { openai_key: '', chat_model: '', }, chatwidget: { chat_icon: '', widget_logo: '', widget_text: '', widget_color: '#1976d2', suggested_questions: [], widget_position: 'bottom-right', widget_greeting: '', widget_placeholder: '', widget_title: '', widget_subtitle: '', show_orders_tab: true, }, ai_config: { woocommerce_enabled: false, included_post_types: ['post', 'page'], excluded_posts: [], excluded_pages: [], excluded_products: [], exclude_categories: [], contact_info: '', custom_content: '', batch_size: 10, max_context_length: 2000, }, integrations: { whatsapp: { enabled: false, account_sid: '', auth_token: '', phone_number: '', welcome_message: '', enable_template_messages: false, }, telegram: { enabled: false, bot_token: '', bot_username: '', welcome_message: '', }, contact_form: { enabled: false, shortcode: '', }, }, misc: { show_credit: false, custom_css: '', }, }); const [isSaving, setIsSaving] = useState(false); const [saveMessage, setSaveMessage] = useState(''); const [activeTab, setActiveTab] = useState("general"); const [activeIntegrationTab, setActiveIntegrationTab] = useState("whatsapp"); const { nonce, apiUrl } = settings; const [models, setModels] = useState({ models: [], default: '', source: '' }); const [isLoadingModels, setIsLoadingModels] = useState(false); useEffect(() => { // Load settings from WordPress on mount loadSettings(); loadModels(); }, []); const loadModels = async (refresh = false) => { setIsLoadingModels(true); try { const response = await fetch(`${AISK_API}/models${refresh ? '?refresh=1' : ''}`, { headers: { 'X-WP-Nonce': AiskSettings.nonce } }); const data = await response.json(); if (Array.isArray(data?.models)) { setModels(data); } } catch (error) { console.error('Error loading models:', error); } finally { setIsLoadingModels(false); } }; const selectedModel = settings.general.chat_model || models.default; const loadSettings = async () => { try { const response = await fetch(`${AISK_API}/settings`, { headers: { 'X-WP-Nonce': AiskSettings.nonce } }); const data = await response.json(); if (data) { setSettings(prevSettings => ({ ...prevSettings, ...data })); } } catch (error) { console.error('Error loading settings:', error); } }; // Validate inputs before saving const validateBeforeSave = () => { const phone = settings?.integrations?.whatsapp?.phone_number || ''; if (phone && !/^whatsapp:\+\d{10,15}$/.test(phone)) { // Focus the Integrations → WhatsApp tab and show an error toast setActiveTab('integrations'); setActiveIntegrationTab('whatsapp'); toast({ title: (
{__('Invalid WhatsApp number', 'aisk-ai-chat')}
), description: __('Use format "whatsapp:+1234567890" including country code.', 'aisk-ai-chat'), className: "bg-red-50 border-red-200" }); return false; } return true; }; const saveSettings = async () => { if (!validateBeforeSave()) return; setIsSaving(true); try { const response = await fetch(`${AISK_API}/settings`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': AiskSettings.nonce }, body: JSON.stringify(settings) }); if (response.ok) { toast({ title: (
{__('Settings saved successfully!', 'aisk-ai-chat')}
), description: __('Your changes have been applied.', 'aisk-ai-chat'), className: "bg-green-50 border-green-200" }); } else { throw new Error('Failed to save settings'); } } catch (error) { toast({ title: (
{__('Failed to save settings', 'aisk-ai-chat')}
), description: __('Please try again or contact support if the problem persists.', 'aisk-ai-chat'), className: "bg-red-50 border-red-200" }); } finally { setIsSaving(false); } }; const updateSettings = (section, key, value) => { setSettings(prev => ({ ...prev, [section]: { ...prev[section], [key]: value } })); }; return ( <>
{__('Aisk Settings', 'aisk-ai-chat')} {__('Configure your chatbot and integration settings', 'aisk-ai-chat')}
{__('Need Help?', 'aisk-ai-chat')} {__('Documentation', 'aisk-ai-chat')}
{saveMessage && ( {saveMessage} )} {__('General', 'aisk-ai-chat')} {__('Chat Widget', 'aisk-ai-chat')} {__('AI Config', 'aisk-ai-chat')} {__('Integrations', 'aisk-ai-chat')} {__('Misc', 'aisk-ai-chat')} {__('General Settings', 'aisk-ai-chat')} {__('Configure your API keys and general settings', 'aisk-ai-chat')}
updateSettings('general', 'openai_key', e.target.value)} type="password" className="max-w-xl" />

{__('Generate your API key at', 'aisk-ai-chat')}{" "} platform.openai.com/api-keys

{models.source === 'openai' ? __('Models available to your OpenAI account. Used for chat replies and intent detection.', 'aisk-ai-chat') : __('Showing default models. Save a valid API key, then refresh to load models from your OpenAI account.', 'aisk-ai-chat')}

); }; export default SettingsApp;