import React, { useState, useEffect } from 'react';
import { getNonce } from '../../Helpers';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import AssessmentIcon from '@mui/icons-material/Assessment';
import PersonIcon from '@mui/icons-material/Person';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import CancelIcon from '@mui/icons-material/Cancel';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';

interface QuizResultsProps {
    quizId: number;
    quizName: string;
    onBack: () => void;
}

interface Submission {
    id: number;
    user_id: number;
    user_name: string;
    user_email: string;
    score: number;
    total_questions: number;
    percentage: number;
    passed: boolean;
    answers: any;
    submitted_at: string;
}

const QuizResults: React.FC<QuizResultsProps> = ({ quizId, quizName, onBack }) => {
    const [submissions, setSubmissions] = useState<Submission[]>([]);
    const [loading, setLoading] = useState(true);
    const [stats, setStats] = useState({
        total_submissions: 0,
        average_score: 0,
        pass_rate: 0,
    });

    useEffect(() => {
        loadResults();
    }, [quizId]);

    const loadResults = () => {
        setLoading(true);
        (wp as any).ajax.send('simpleform_get_quiz_results', {
            data: {
                nonce: getNonce(),
                quiz_id: quizId,
            },
            success(response: any) {
                if (response.submissions) {
                    const transformedSubmissions = response.submissions.map((sub: any) => ({
                        ...sub,
                        score: Number(sub.score),
                        total_questions: Number(sub.total_questions),
                        percentage: (Number(sub.score) / Number(sub.total_questions)) * 100,
                        passed: sub.passed === "1" || sub.passed === true,
                        user_name: sub.user_name || 'Anonymous',
                        user_email: sub.user_email || '-',
                        submitted_at: sub.created_at
                    }));
                    setSubmissions(transformedSubmissions);
                }
                if (response.stats) {
                    setStats(response.stats);
                }
                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'
        });
    };

    // Prepare data for charts
    const getScoreDistribution = () => {
        const distribution: { [key: string]: number } = {};
        submissions.forEach(sub => {
            const scoreRange = `${Math.floor(sub.percentage / 10) * 10}-${Math.floor(sub.percentage / 10) * 10 + 10}%`;
            distribution[scoreRange] = (distribution[scoreRange] || 0) + 1;
        });
        return Object.entries(distribution).map(([range, count]) => ({
            range,
            count
        })).sort((a, b) => parseInt(a.range) - parseInt(b.range));
    };

    const getPassFailData = () => {
        const passed = submissions.filter(s => s.passed).length;
        const failed = submissions.filter(s => !s.passed).length;
        return [
            { name: 'Passed', value: passed, color: '#10b981' },
            { name: 'Failed', value: failed, color: '#ef4444' }
        ];
    };

    const COLORS = ['#10b981', '#ef4444'];

    if (loading) {
        return (
            <div className="quiz-results-loading">
                <div className="spinner"></div>
                <p>Loading results...</p>
            </div>
        );
    }

    return (
        <div className="quiz-results-container">
            <div className="quiz-results-header">
                <button className="back-btn" onClick={onBack}>
                    <ArrowBackIcon />
                    Back to Quizzes
                </button>
                <div className="header-content">
                    <h1>
                        <AssessmentIcon />
                        Quiz Results: {quizName}
                    </h1>
                </div>
            </div>

            <div className="quiz-stats-cards">
                <div className="stat-card">
                    <div className="stat-icon">
                        <PersonIcon />
                    </div>
                    <div className="stat-content">
                        <h3>{stats.total_submissions}</h3>
                        <p>Total Submissions</p>
                    </div>
                </div>
                <div className="stat-card">
                    <div className="stat-icon">
                        <AssessmentIcon />
                    </div>
                    <div className="stat-content">
                        <h3>{stats.average_score.toFixed(1)}%</h3>
                        <p>Average Score</p>
                    </div>
                </div>
                <div className="stat-card">
                    <div className="stat-icon">
                        <CheckCircleIcon />
                    </div>
                    <div className="stat-content">
                        <h3>{stats.pass_rate.toFixed(1)}%</h3>
                        <p>Pass Rate</p>
                    </div>
                </div>
            </div>

            {submissions.length === 0 ? (
                <div className="no-results">
                    <AssessmentIcon className="no-results-icon" />
                    <h3>No submissions yet</h3>
                    <p>Results will appear here once users complete the quiz</p>
                </div>
            ) : (
                <>
                    <div className="quiz-charts">
                        <div className="chart-container">
                            <h3>Score Distribution</h3>
                            <ResponsiveContainer width="100%" height={300}>
                                <BarChart data={getScoreDistribution()}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="range" />
                                    <YAxis />
                                    <Tooltip />
                                    <Legend />
                                    <Bar dataKey="count" fill="#3b82f6" name="Number of Submissions" />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>

                        <div className="chart-container">
                            <h3>Pass/Fail Ratio</h3>
                            <ResponsiveContainer width="100%" height={300}>
                                <PieChart>
                                    <Pie
                                        data={getPassFailData()}
                                        cx="50%"
                                        cy="50%"
                                        labelLine={false}
                                        label={({ name, value, percent }) => `${name}: ${value} (${(percent * 100).toFixed(0)}%)`}
                                        outerRadius={80}
                                        fill="#8884d8"
                                        dataKey="value"
                                    >
                                        {getPassFailData().map((entry, index) => (
                                            <Cell key={`cell-${index}`} fill={entry.color} />
                                        ))}
                                    </Pie>
                                    <Tooltip />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>
                    </div>

                    <div className="submissions-table">
                        <h3>All Submissions</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Email</th>
                                    <th>Score</th>
                                    <th>Percentage</th>
                                    <th>Status</th>
                                    <th>Submitted</th>
                                </tr>
                            </thead>
                            <tbody>
                                {submissions.map(submission => (
                                    <tr key={submission.id}>
                                        <td>{submission.user_name}</td>
                                        <td>{submission.user_email}</td>
                                        <td>{submission.score} / {submission.total_questions}</td>
                                        <td>{submission.percentage.toFixed(1)}%</td>
                                        <td>
                                            <span className={`status-badge ${submission.passed ? 'passed' : 'failed'}`}>
                                                {submission.passed ? (
                                                    <>
                                                        <CheckCircleIcon fontSize="small" />
                                                        Passed
                                                    </>
                                                ) : (
                                                    <>
                                                        <CancelIcon fontSize="small" />
                                                        Failed
                                                    </>
                                                )}
                                            </span>
                                        </td>
                                        <td>{formatDate(submission.submitted_at)}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </>
            )}
        </div>
    );
};

export default QuizResults;