import React, { useState, useEffect } from 'react'; import { getNonce } from '../../Helpers'; import ArrowBackIcon from '@mui/icons-material/ArrowBack'; import BarChartIcon from '@mui/icons-material/BarChart'; import PersonIcon from '@mui/icons-material/Person'; import HowToVoteIcon from '@mui/icons-material/HowToVote'; import TrendingUpIcon from '@mui/icons-material/TrendingUp'; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line } from 'recharts'; // Declare wp global for WordPress declare const wp: any; interface PollResultsProps { pollId: number; pollName: string; onBack: () => void; } interface Answer { id: string; text: string; image_url?: string; votes: number; percentage: number; } interface Submission { id: number; poll_id: number; user_id: number; user_data: string; user_name?: string; user_email?: string; ip_address: string; selected_answers: string[]; selected_answers_text?: string[]; submitted_at: string; } const PollResults: React.FC = ({ pollId, pollName, onBack }) => { const [results, setResults] = useState<{ total_votes: number; answers: Answer[] }>({ total_votes: 0, answers: [] }); const [submissions, setSubmissions] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { loadResults(); }, [pollId]); const loadResults = () => { setLoading(true); (wp as any).ajax.send('simpleform_get_poll_results', { data: { nonce: getNonce(), poll_id: pollId, }, success(response: any) { if (response.results) { setResults(response.results); } if (response.submissions) { // Transform submissions to ensure proper data types const transformedSubmissions = response.submissions.map((sub: any) => ({ ...sub, id: Number(sub.id), poll_id: Number(sub.poll_id), user_id: Number(sub.user_id), selected_answers: Array.isArray(sub.selected_answers) ? sub.selected_answers : [], })); setSubmissions(transformedSubmissions); } setLoading(false); }, error(error: any) { console.error('Error loading results:', error); setLoading(false); }, }); }; const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }; const getAnswerText = (answerId: string) => { const answer = results.answers.find(a => a.id === answerId); return answer ? answer.text : answerId; }; // Calculate statistics const getStats = () => { const totalResponses = submissions.length; const totalVotes = results.total_votes; const averageSelectionsPerVoter = totalResponses > 0 ? (totalVotes / totalResponses).toFixed(1) : '0'; const mostPopularAnswer = results.answers.length > 0 ? results.answers.reduce((prev, current) => (prev.votes > current.votes) ? prev : current) : null; return { totalResponses, totalVotes, averageSelectionsPerVoter, mostPopularAnswer }; }; // Prepare data for pie chart const getPieChartData = () => { return results.answers.map(answer => ({ name: answer.text, value: answer.votes, percentage: answer.percentage })); }; // Prepare data for bar chart const getBarChartData = () => { return results.answers.map(answer => ({ answer: answer.text.length > 30 ? answer.text.substring(0, 30) + '...' : answer.text, votes: answer.votes, percentage: answer.percentage })); }; // Get voting timeline data const getTimelineData = () => { const timeline: { [key: string]: number } = {}; submissions.forEach(sub => { const date = new Date(sub.submitted_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); timeline[date] = (timeline[date] || 0) + 1; }); return Object.entries(timeline).map(([date, count]) => ({ date, votes: count })); }; const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#f97316']; const stats = getStats(); if (loading) { return (

Loading results...

); } return (

Poll Results: {pollName}

{results.total_votes}

Total Votes

{submissions.length}

Unique Voters

{stats.averageSelectionsPerVoter}

Avg Selections/Voter

{stats.mostPopularAnswer && (

{stats.mostPopularAnswer.text}

Most Popular ({stats.mostPopularAnswer.votes} votes)

)}
{results.answers.length === 0 ? (

No votes yet

Results will appear here once users vote

) : ( <>

Vote Distribution (Bar Chart)

Vote Distribution (Pie Chart)

`${name}: ${percentage.toFixed(1)}%`} outerRadius={80} fill="#8884d8" dataKey="value" > {getPieChartData().map((entry, index) => ( ))}
{submissions.length > 1 && (

Voting Timeline

)}

Detailed Results

{results.answers.map((answer, index) => (
{answer.text} {answer.votes} votes ({answer.percentage.toFixed(1)}%)
))}
)} {submissions.length > 0 && (

Recent Submissions

{submissions.map(submission => ( ))}
User Email Selected Answer(s) IP Address Submitted
{submission.user_name || 'Anonymous'} {submission.user_email || '-'} {submission.selected_answers_text ? submission.selected_answers_text.join(', ') : submission.selected_answers.map(answerId => getAnswerText(answerId) ).join(', ') } {submission.ip_address} {formatDate(submission.submitted_at)}
)}
); }; export default PollResults;