import type IGame from "../api/types/IGame.ts";
import {
    Accordion,
    AccordionDetails,
    AccordionSummary,
    AspectRatio,
    Card,
    CardContent,
    Stack, Typography
} from "@mui/joy";
import type IPlayer from "../api/types/IPlayer.ts";
import {useContext, useEffect, useState} from "react";
import {ApiUriContext} from "../api/fetchApi.tsx";
import {GetGamesOfPlayer} from "../api/endpoints/Data.tsx";

export default function PlayerAccordionItem({player} : {player: IPlayer}) {
    const apiUri = useContext(ApiUriContext);

    const [games, setGames] = useState<IGame[]>([]);
    const [expanded, setExpanded] = useState<boolean>(false);

    useEffect(() => {
        if(!expanded)
            return;
        GetGamesOfPlayer(apiUri, player.steamId).then(setGames);
    }, [expanded]);

    return (
        <Accordion key={player.steamId} onChange={(_, expanded) => setExpanded(expanded)}>
            <AccordionSummary>{player.name}</AccordionSummary>
            <AccordionDetails>
                <Stack flexWrap={"wrap"} direction={"row"} useFlexGap={true} spacing={1}>
                    {games?.map((game) =>
                        <AspectRatio sx={{width: "128px"}} ratio={2/3}>
                            <Card key={game.appId}>
                                <CardContent>
                                    <Typography level={"body-lg"}>{game.name}</Typography>
                                </CardContent>
                            </Card>
                        </AspectRatio>
                    )}
                </Stack>
            </AccordionDetails>
        </Accordion>
    );
}