
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<PollResultsProps> = ({ pollId, pollName, onBack }) => {
    const [results, setResults] = useState<{ total_votes: number; answers: Answer[] }>({ total_votes: 0, answers: [] });
    const [submissions, setSubmissions] = useState<Submission[]>([]);
    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 (
            <div className="poll-results-loading">
                <div className="spinner"></div>
                <p>Loading results...</p>
            </div>
        );
    }

    return (
        <div className="poll-results-container">
            <div className="poll-results-header">
                <button className="back-btn" onClick={onBack}>
                    <ArrowBackIcon />
                    Back to Polls
                </button>
                <div className="header-content">
                    <h1>
                        <BarChartIcon />
                        Poll Results: {pollName}
                    </h1>
                </div>
            </div>

            <div className="poll-stats-cards">
                <div className="stat-card">
                    <div className="stat-icon">
                        <HowToVoteIcon />
                    </div>
                    <div className="stat-content">
                        <h3>{results.total_votes}</h3>
                        <p>Total Votes</p>
                    </div>
                </div>
                <div className="stat-card">
                    <div className="stat-icon">
                        <PersonIcon />
                    </div>
                    <div className="stat-content">
                        <h3>{submissions.length}</h3>
                        <p>Unique Voters</p>
                    </div>
                </div>
                <div className="stat-card">
                    <div className="stat-icon">
                        <BarChartIcon />
                    </div>
                    <div className="stat-content">
                        <h3>{stats.averageSelectionsPerVoter}</h3>
                        <p>Avg Selections/Voter</p>
                    </div>
                </div>
                {stats.mostPopularAnswer && (
                    <div className="stat-card highlight">
                        <div className="stat-icon">
                            <TrendingUpIcon />
                        </div>
                        <div className="stat-content">
                            <h3>{stats.mostPopularAnswer.text}</h3>
                            <p>Most Popular ({stats.mostPopularAnswer.votes} votes)</p>
                        </div>
                    </div>
                )}
            </div>

            {results.answers.length === 0 ? (
                <div className="no-results">
                    <BarChartIcon className="no-results-icon" />
                    <h3>No votes yet</h3>
                    <p>Results will appear here once users vote</p>
                </div>
            ) : (
                <>
                    <div className="poll-charts">
                        <div className="chart-container">
                            <h3>Vote Distribution (Bar Chart)</h3>
                            <ResponsiveContainer width="100%" height={300}>
                                <BarChart data={getBarChartData()}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="answer" angle={-45} textAnchor="end" height={100} />
                                    <YAxis />
                                    <Tooltip />
                                    <Legend />
                                    <Bar dataKey="votes" fill="#3b82f6" name="Number of Votes" />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>

                        <div className="chart-container">
                            <h3>Vote Distribution (Pie Chart)</h3>
                            <ResponsiveContainer width="100%" height={300}>
                                <PieChart>
                                    <Pie
                                        data={getPieChartData()}
                                        cx="50%"
                                        cy="50%"
                                        labelLine={false}
                                        label={({ name, percentage }) => `${name}: ${percentage.toFixed(1)}%`}
                                        outerRadius={80}
                                        fill="#8884d8"
                                        dataKey="value"
                                    >
                                        {getPieChartData().map((entry, index) => (
                                            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                                        ))}
                                    </Pie>
                                    <Tooltip />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>

                        {submissions.length > 1 && (
                            <div className="chart-container full-width">
                                <h3>Voting Timeline</h3>
                                <ResponsiveContainer width="100%" height={300}>
                                    <LineChart data={getTimelineData()}>
                                        <CartesianGrid strokeDasharray="3 3" />
                                        <XAxis dataKey="date" />
                                        <YAxis />
                                        <Tooltip />
                                        <Legend />
                                        <Line type="monotone" dataKey="votes" stroke="#3b82f6" strokeWidth={2} name="Votes per Day" />
                                    </LineChart>
                                </ResponsiveContainer>
                            </div>
                        )}
                    </div>

                    <div className="poll-results-chart">
                        <h2>Detailed Results</h2>
                        <div className="results-bars">
                            {results.answers.map((answer, index) => (
                                <div key={answer.id} className="result-bar-item">
                                    <div className="result-label">
                                        <span className="answer-text">{answer.text}</span>
                                        <span className="answer-stats">
                                            {answer.votes} votes ({answer.percentage.toFixed(1)}%)
                                        </span>
                                    </div>
                                    <div className="result-bar-container">
                                        <div
                                            className="result-bar-fill"
                                            style={{
                                                width: `${answer.percentage}%`,
                                                backgroundColor: COLORS[index % COLORS.length]
                                            }}
                                        ></div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </>
            )}

            {submissions.length > 0 && (
                <div className="submissions-table">
                    <h2>Recent Submissions</h2>
                    <table>
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Email</th>
                                <th>Selected Answer(s)</th>
                                <th>IP Address</th>
                                <th>Submitted</th>
                            </tr>
                        </thead>
                        <tbody>
                            {submissions.map(submission => (
                                <tr key={submission.id}>
                                    <td>{submission.user_name || 'Anonymous'}</td>
                                    <td>{submission.user_email || '-'}</td>
                                    <td>
                                        {submission.selected_answers_text 
                                            ? submission.selected_answers_text.join(', ')
                                            : submission.selected_answers.map(answerId =>
                                                getAnswerText(answerId)
                                            ).join(', ')
                                        }
                                    </td>
                                    <td>{submission.ip_address}</td>
                                    <td>{formatDate(submission.submitted_at)}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
};

export default PollResults;