<script lang="ts">
    import type { EventFight, ExtendedEvent, ResponseGroups, ResponseTeam } from "@type/event";
    import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@components/ui/dialog";
    import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@components/ui/table";
    import { Button } from "@components/ui/button";
    import type { Team } from "@components/types/team";

    let { open = $bindable(), group, teams, fights }: { open?: boolean; group: ResponseGroups; teams: Team[]; fights: EventFight[] } = $props();
</script>

<Dialog bind:open>
    <DialogContent class="sm:max-w-[600px]">
        <DialogHeader>
            <DialogTitle>Ergebnisse: {group?.name}</DialogTitle>
            <DialogDescription>
                Punkte: Sieg: {group?.pointsPerWin}, Unentschieden: {group?.pointsPerDraw}, Niederlage: {group?.pointsPerLoss}
            </DialogDescription>
        </DialogHeader>
        {#if group.points !== null}
            <Table>
                <TableHeader>
                    <TableRow>
                        <TableHead>Team</TableHead>
                        <TableHead class="text-right">Spiele</TableHead>
                        <TableHead class="text-right">Punkte</TableHead>
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {#each Object.entries(group.points).toSorted((a, b) => b[1] - a[1]) as [teamIdString, points] (teamIdString)}
                        {@const teamId = Number(teamIdString)}
                        {@const team = teams.find((t) => t.id === teamId) as ResponseTeam | undefined}
                        {@const playedGames = fights.filter((f) => f.hasFinished && f.group?.id === group.id && (f.blueTeam.id === teamId || f.redTeam.id === teamId)).length}
                        <TableRow>
                            <TableCell>{team?.name ?? "?"} ({team?.kuerzel ?? "?"})</TableCell>
                            <TableCell class="text-right">{playedGames}</TableCell>
                            <TableCell class="text-right font-bold">{points}</TableCell>
                        </TableRow>
                    {/each}
                </TableBody>
            </Table>
        {:else}
            <p class="text-center py-4">Noch keine Ergebnisse für diese Gruppe vorhanden oder keine Spiele zugeordnet.</p>
        {/if}
        <DialogFooter>
            <Button variant="outline" onclick={() => (open = false)}>Schließen</Button>
        </DialogFooter>
    </DialogContent>
</Dialog>
