import { __ } from '@wordpress/i18n'; import React, { useState, useEffect, useRef } from 'react'; import { ThemeProvider, createTheme } from '@mui/material/styles'; import { DataGrid, gridPageCountSelector, gridPageSelector, useGridApiContext, useGridSelector } from '@mui/x-data-grid'; import { Box, Button, Pagination, Stack, Typography, Chip, Tooltip, Select, MenuItem, FormControl, InputLabel } from '@mui/material'; import { Monitor, Smartphone, Tablet, MapPin } from 'lucide-react'; import ChatWidget from '../../../components/ChatWidget'; // Create theme that matches WordPress admin const theme = createTheme({ palette: { primary: { main: '#2271b1', dark: '#135e96' }, secondary: { main: '#72777c' }, background: { default: '#f0f0f1' } }, components: { MuiDataGrid: { styleOverrides: { root: { backgroundColor: '#fff', border: '1px solid #c3c4c7', '& .MuiDataGrid-columnHeaders': { backgroundColor: '#f0f0f1', borderBottom: '1px solid #c3c4c7' } } } }, MuiChip: { styleOverrides: { root: { borderRadius: '16px', margin: '2px' } } } } }); function CustomPagination() { const apiRef = useGridApiContext(); const page = useGridSelector(apiRef, gridPageSelector); const pageCount = useGridSelector(apiRef, gridPageCountSelector); return ( apiRef.current.setPage(value - 1)} /> ); } // Device detection helper const getDeviceIcon = (platform) => { if (!platform) { return ; } const ua = String(platform).toLowerCase(); // Check for specific platforms first if (ua.includes('whatsapp')) { return ; } if (ua.includes('telegram')) { return ; } // Check for different mobile/desktop platforms if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone') || ua.includes('ipad') || ua.includes('windows phone')) { return ; } if (ua.includes('tablet') || ua.includes('ipad') || ua.includes('android') && !ua.includes('mobile')) { return ; } return ; }; // Intent chips with different colors const IntentChip = ({ intent }) => { const getColor = (intent) => { const colors = { 'pre-sales': 'rgb(176, 230, 255)', 'after-sales': 'rgb(171, 255, 208)', 'payment': 'rgb(255, 223, 171)', 'order': 'rgb(255, 171, 194)', 'product': 'rgb(190, 171, 255)', 'delivery': 'rgb(171, 255, 245)', 'discounts': 'rgb(255, 171, 237)', 'promotions': 'rgb(215, 255, 171)' }; return colors[intent.toLowerCase()] || 'rgb(200, 200, 200)'; }; return ( ); }; const ChatAdminDashboard = () => { const [conversations, setConversations] = useState([]); const [selectedChat, setSelectedChat] = useState(null); const [loading, setLoading] = useState(true); const [page, setPage] = useState(0); const [pageSize, setPageSize] = useState(3); const [totalRows, setTotalRows] = useState(0); const [timeFilter, setTimeFilter] = useState('7days'); const [locationFilter, setLocationFilter] = useState('all'); const [availableLocations, setAvailableLocations] = useState([]); const [error, setError] = useState(null); const chatWidgetRef = useRef(null); const handleViewChat = (chat) => { // Clear localStorage when opening a new chat localStorage.removeItem('wooai_conversation_id'); if (selectedChat?.conversation_id !== chat.conversation_id) { setSelectedChat(null); setTimeout(() => { // Set the new conversation ID in localStorage localStorage.setItem('wooai_conversation_id', chat.conversation_id); setSelectedChat(chat); if (chatWidgetRef.current) { chatWidgetRef.current.open(); } }, 0); } else { if (chatWidgetRef.current) { chatWidgetRef.current.open(); } } }; const columns = [ { field: 'id', headerName: __('ID', 'aisk-ai-chat'), width: 100, renderCell: (params) => ( {getDeviceIcon(params.row.platform)} #{params.row.conversation_id} ) }, { field: 'location', headerName: __('Location', 'aisk-ai-chat'), width: 200, renderCell: (params) => ( {params.row.city || __('Unknown City', 'aisk-ai-chat')} {params.row.country && `, ${params.row.country}`} {params.row.ip_address && ( {params.row.ip_address} )} ), sortable: true }, { field: 'intents', headerName: __('Intents', 'aisk-ai-chat'), width: 200, renderCell: (params) => { let intents = []; try { // Try to parse if it's a JSON string intents = params.row.intents ? JSON.parse(params.row.intents) : []; } catch (e) { // If it's a comma-separated string, split it intents = params.row.intents ? params.row.intents.split(',') : []; } return ( {intents.map((intent, index) => ( ))} ); } }, { field: 'user_info', headerName: __('User Info', 'aisk-ai-chat'), width: 250, renderCell: (params) => ( {params.row.user_name || __('Anonymous', 'aisk-ai-chat')} {params.row.user_email && ( {params.row.user_email} )} {params.row.user_phone && ( {params.row.user_phone} )} ) }, { field: 'page_url', headerName: __('Source Page', 'aisk-ai-chat'), width: 200, renderCell: (params) => ( {params.row.page_url ? new URL(params.row.page_url).pathname : __('N/A', 'aisk-ai-chat')} ) }, { field: 'created_at', headerName: __('Date & Time', 'aisk-ai-chat'), width: 200, valueFormatter: (params) => { // Parse the UTC timestamp from the database (stored in UTC) const utcDate = new Date(params.value); // Check if the date is valid if (isNaN(utcDate)) { return __('Invalid Date', 'aisk-ai-chat'); // Fallback message if the date is invalid } // Get the visitor's local time zone offset in minutes (in UTC) const localOffset = new Date().getTimezoneOffset(); // This returns the offset in minutes // Adjust the UTC date by the visitor's local time zone offset utcDate.setMinutes(utcDate.getMinutes() - localOffset); // Get today's date and yesterday's date for comparison const today = new Date(); const yesterday = new Date(today); yesterday.setDate(yesterday.getDate() - 1); // Format time with user's locale settings const time = utcDate.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', }); // If date is today if (utcDate.toDateString() === today.toDateString()) { return __('Today', 'aisk-ai-chat') + `, ${time}`; } // If date is yesterday if (utcDate.toDateString() === yesterday.toDateString()) { return __('Yesterday', 'aisk-ai-chat') + `, ${time}`; } // For other dates return utcDate.toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric', }) + `, ${time}`; } }, { field: 'actions', headerName: __('Actions', 'aisk-ai-chat'), width: 120, sortable: false, renderCell: (params) => ( ) } ]; useEffect(() => { loadConversations(); }, [page, pageSize, timeFilter, locationFilter]); const loadConversations = async () => { setLoading(true); // Set loading immediately let apiUrl = `${AiskSettings.apiUrl}/conversations`; apiUrl += `?page=${page + 1}&per_page=${pageSize}&time_filter=${timeFilter}&location_filter=${locationFilter}`; try { const response = await fetch(apiUrl, { headers: { 'X-WP-Nonce': AiskSettings.nonce } }); if (!response.ok) { throw new Error(`API error: ${response.status}`); } const data = await response.json(); if (!data || !data.conversations || !Array.isArray(data.conversations)) { console.error("Invalid API response:", data); setError(__('Failed to load conversations.', 'aisk-ai-chat')); return; } const conversationsWithIds = data.conversations.map(conv => ({ ...conv, id: conv.conversation_id })); setConversations(conversationsWithIds); setTotalRows(data.total || 0); if (data.locations && Array.isArray(data.locations)) { setAvailableLocations(data.locations); } } catch (error) { console.error('Error loading conversations:', error); setError( __('Failed to load conversations: %s', 'aisk-ai-chat').replace('%s', error.message) ); } finally { setLoading(false); } }; return ( {__('Chats', 'aisk-ai-chat')} {/* Filters */} {__('Time Period', 'aisk-ai-chat')} {__('Location', 'aisk-ai-chat')} { setPage(newPage); }} onPageSizeChange={(newPageSize) => { setPageSize(newPageSize); setPage(0); // Reset to first page when changing page size }} loading={loading} getRowId={(row) => row.conversation_id || row.id} components={{ Pagination: CustomPagination, }} disableSelectionOnClick disableColumnMenu sx={{ '& .MuiDataGrid-cell': { borderBottom: 1, borderColor: 'divider', }, '& .MuiDataGrid-row:hover': { backgroundColor: 'action.hover', } }} /> {selectedChat && ( { if (e.target === e.currentTarget) { setSelectedChat(null); } }} > e.stopPropagation()}> )} {error && ( {error} )} ); }; export default ChatAdminDashboard;