// static/js/testReview.jsx

function TestReview({ testId }) {
    const { token, setView } = useContext(AuthContext);
    const [loading, setLoading] = useState(true);
    const [data, setData] = useState(null);
    const [error, setError] = useState("");

    useEffect(() => {
        let isMounted = true;

        async function loadReview() {
            try {
                setLoading(true);
                setError("");
                const review = await API.userReviewTestAnswers(token, testId);
                if (isMounted) {
                    setData(review);
                }
            } catch (e) {
                console.error(e);
                if (isMounted) {
                    setError(e.message || "Не удалось загрузить ответы");
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        }

        loadReview();

        return () => {
            isMounted = false;
        };
    }, [token, testId]);

    if (loading) {
        return (
            <div className="flex justify-center mt-20">
                <div className="spinner"></div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="max-w-3xl mx-auto bg-white p-6 rounded shadow">
                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-2 rounded text-sm mb-4">
                    {error}
                </div>
                <button
                    type="button"
                    onClick={() => setView('dashboard')}
                    className="px-4 py-2 rounded bg-slate-700 text-white font-semibold"
                >
                    Назад
                </button>
            </div>
        );
    }

    const result = data.result || {};
    const percent = typeof result.percent === 'number' ? result.percent.toFixed(1) : '0.0';

    return (
        <div className="max-w-4xl mx-auto">
            <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 mb-5">
                <div>
                    <h2 className="text-2xl font-bold">{data.test.title}</h2>
                    <div className="text-sm text-gray-600 mt-1">
                        Баллы: <span className="font-semibold">{result.score}</span>
                        {typeof result.max_score === 'number' ? ` из ${result.max_score}` : ''} ({percent}%)
                    </div>
                </div>
                <button
                    type="button"
                    onClick={() => setView('dashboard')}
                    className="px-4 py-2 rounded bg-slate-700 text-white font-semibold"
                >
                    Назад
                </button>
            </div>

            <div className="space-y-4">
                {(data.questions || []).map((q, idx) => {
                    const earnedFull = Number(q.score_awarded || 0) >= Number(q.score || 0) && Number(q.score || 0) > 0;
                    return (
                        <div key={`${q.id}-${idx}`} className="bg-white p-5 rounded shadow">
                            <div className="flex items-start justify-between gap-3 mb-3">
                                <div className="font-semibold">
                                    {idx + 1}. {q.text}
                                </div>
                                <div className={`text-xs font-bold px-2 py-1 rounded ${earnedFull ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                                    {q.score_awarded || 0} / {q.score || 0}
                                </div>
                            </div>

                            {(q.options || []).length > 0 ? (
                                <div className="space-y-2">
                                    {q.options.map(opt => {
                                        let cls = "border rounded p-3 text-sm";
                                        if (opt.is_correct) cls += " border-green-300 bg-green-50";
                                        else if (opt.selected) cls += " border-red-300 bg-red-50";
                                        else cls += " border-gray-200 bg-gray-50";
                                        return (
                                            <div key={opt.id} className={cls}>
                                                <span className="font-semibold mr-2">
                                                    {opt.is_correct ? "Верно" : (opt.selected ? "Ваш ответ" : "")}
                                                </span>
                                                {opt.text}
                                            </div>
                                        );
                                    })}
                                </div>
                            ) : (
                                <div className="space-y-2 text-sm">
                                    <div className="border rounded p-3 bg-gray-50">
                                        <span className="font-semibold">Ваш ответ: </span>
                                        {q.text_answer || "Нет ответа"}
                                    </div>
                                    {q.correct_text && (
                                        <div className="border rounded p-3 bg-green-50 border-green-300">
                                            <span className="font-semibold">Правильный ответ: </span>
                                            {q.correct_text}
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
