<script lang="ts">
    import type { GroupUpdateEdit, ResponseGroups, SWEvent } from "@type/event";
    import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@components/ui/dialog";
    import GroupEdit from "@components/moderator/components/GroupEdit.svelte";
    import { Button } from "@components/ui/button";
    import { eventRepo } from "@repo/event";

    let { group, groups = $bindable(), open = $bindable(), event }: { group: ResponseGroups; groups: ResponseGroups[]; open?: boolean; event: SWEvent } = $props();

    async function handleSave(groupData: GroupUpdateEdit) {
        if (!group) return;
        const updatedGroup = await $eventRepo.updateGroup(event.id.toString(), group.id.toString(), groupData);
        groups = groups.map((g) => (g.id === updatedGroup.id ? updatedGroup : g));
        open = false;
    }

    async function handleDelete() {
        if (!group) return;
        await $eventRepo.deleteGroup(event.id.toString(), group.id.toString());
        groups = groups.filter((g) => g.id !== group.id);
        open = false;
    }
</script>

{#if group}
    <Dialog bind:open>
        <DialogContent>
            <DialogHeader>
                <DialogTitle>Gruppe Bearbeiten: {group.name}</DialogTitle>
                <DialogDescription>Hier kannst du die Gruppendetails bearbeiten.</DialogDescription>
            </DialogHeader>
            <GroupEdit {group} onSave={handleSave}>
                {#snippet actions(dirty, submit)}
                    <DialogFooter class="flex justify-between">
                        <Button variant="destructive" onclick={handleDelete}>Löschen</Button>
                        <div class="flex gap-2">
                            <Button variant="outline" onclick={() => (open = false)}>Abbrechen</Button>
                            <Button disabled={!dirty} onclick={submit}>Speichern</Button>
                        </div>
                    </DialogFooter>
                {/snippet}
            </GroupEdit>
        </DialogContent>
    </Dialog>
{/if}
