import { useEffect, useState, useContext } from "react";
import { StateContext } from "@/common/contexts/StateContext";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrophy, faMedal, faAward, faHome, faCrown } from "@fortawesome/free-solid-svg-icons";
import "./styles.sass";

export const Ending = () => {
    const { setCurrentState } = useContext(StateContext);
    const [finalScores, setFinalScores] = useState([]);
    
    useEffect(() => {
        const savedData = JSON.parse(localStorage.getItem('finalScores') || '{"scores":{}}');
        const sortedScores = Object.entries(savedData.scores)
            .map(([userId, data]) => ({
                id: userId,
                name: data.name,
                score: data.score
            }))
            .sort((a, b) => b.score - a.score);
        setFinalScores(sortedScores);
    }, []);

    const getPlayerIcon = (index) => {
        switch(index) {
            case 0: return <FontAwesomeIcon icon={faTrophy} className="gold" />;
            case 1: return <FontAwesomeIcon icon={faMedal} className="silver" />;
            case 2: return <FontAwesomeIcon icon={faAward} className="bronze" />;
            default: return <FontAwesomeIcon icon={faCrown} className="normal" />;
        }
    };

    const handleReturnHome = () => {
        localStorage.removeItem('finalScores');
        setCurrentState("Home");
    };

    return (
        <div className="ending-page">
            <div className="background-overlay">
                <div className="rotating-gradient"></div>
            </div>
            
            <div className="ending-content">
                <h1>Spiel beendet!</h1>
                <div className="final-scores">
                    <h2>Endstand</h2>
                    <div className="leaderboard">
                        {finalScores.map((player, index) => (
                            <div 
                                key={player.id} 
                                className={`leaderboard-entry ${index < 3 ? `top-${index + 1}` : ''}`}
                            >
                                <div className="rank-icon">
                                    {getPlayerIcon(index)}
                                </div>
                                <div className="player-info">
                                    <span className="player-name">{player.name}</span>
                                    <span className="player-score">{player.score} Punkte</span>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
                
                <button className="return-home" onClick={handleReturnHome}>
                    <FontAwesomeIcon icon={faHome} />
                    Zurück zum Hauptmenü
                </button>
            </div>
        </div>
    );
};