<script lang="ts">
    import type { ResponseRelation } from "@components/types/event";
    import type { Team } from "@components/types/team";
    import { Button } from "@components/ui/button";
    import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@components/ui/command";
    import { Popover, PopoverContent, PopoverTrigger } from "@components/ui/popover";
    import { Tabs, TabsContent, TabsList, TabsTrigger } from "@components/ui/tabs";
    import { Tooltip, TooltipContent, TooltipTrigger } from "@components/ui/tooltip";
    import { cn } from "@components/utils";
    import { Check, ChevronsUpDown, GitPullRequestArrow, Plus } from "lucide-svelte";
    import type { EventModel } from "../pages/event/eventmodel.svelte";
    import { Select, SelectContent, SelectItem, SelectTrigger } from "@components/ui/select";
    import { Label } from "@components/ui/label";
    import { eventRepo } from "@components/repo/event";

    interface Props {
        selectedTeam: Team | undefined;
        open?: boolean;
        team: "BLUE" | "RED";
        data: EventModel;
        fightId?: number;
        onSelect?: (team: Team) => void;
    }

    let { selectedTeam = $bindable(), data, team, open = $bindable(false), fightId, onSelect }: Props = $props();

    const currentRelation = $derived(data.relations.find((r) => r.fight === fightId && r.team === team));

    let fromType = $state<"FIGHT" | "GROUP">(currentRelation?.type ?? "FIGHT");

    let fromFight = $state<string | undefined>(currentRelation?.fromFight?.id?.toString());

    let fromFightData = $derived(data.fights.find((f) => f.id.toString() === fromFight));

    let fromGroup = $state<string | undefined>(currentRelation?.fromGroup?.id?.toString());

    let fromGroupData = $derived(data.groups.find((g) => g.id.toString() === fromGroup));

    let fromPlace = $state<string | undefined>(currentRelation?.fromPlace?.toString());

    let relationOpen = $state(false);

    async function saveRelation() {
        relationOpen = false;
        if (currentRelation === undefined) {
            await $eventRepo.createRelation(data.event.id, {
                fightId: fightId!,
                team,
                fromType,
                fromId: fromType === "FIGHT" ? parseInt(fromFight!) : parseInt(fromGroup!),
                fromPlace: parseInt(fromPlace!),
            });
        } else {
            await $eventRepo.updateRelation(data.event.id, currentRelation.id, {
                from: {
                    fromType,
                    fromId: fromType === "FIGHT" ? parseInt(fromFight!) : parseInt(fromGroup!),
                    fromPlace: parseInt(fromPlace!),
                },
            });
        }
        data.relations = await $eventRepo.listRelations(data.event.id);
        reset();
    }

    async function clearRelation() {
        relationOpen = false;
        if (currentRelation !== undefined) {
            await $eventRepo.deleteRelation(data.event.id, currentRelation.id);
            data.relations = await $eventRepo.listRelations(data.event.id);
        }
        reset();
    }

    function reset() {
        fromType = currentRelation?.type ?? "FIGHT";
        fromFight = currentRelation?.fromFight?.id.toString();
        fromGroup = currentRelation?.fromGroup?.id.toString();
        fromPlace = currentRelation?.fromPlace.toString();
    }

    let canSave = $derived(
        (fromType !== currentRelation?.type ||
            fromFight !== (currentRelation?.fromFight?.id.toString() ?? "") ||
            fromGroup !== (currentRelation?.fromGroup?.id.toString() ?? "") ||
            fromPlace !== (currentRelation?.fromPlace.toString() ?? "")) &&
            ((fromType === "FIGHT" && fromFight !== "" && fromPlace !== "") || (fromType === "GROUP" && fromGroup !== "" && fromPlace !== ""))
    );
</script>

<div class="flex gap-2">
    <Popover bind:open>
        <PopoverTrigger>
            {#snippet child({ props })}
                <Button variant="outline" class="justify-between flex-1" {...props} role="combobox">
                    {#if selectedTeam?.id === -1}
                        ???
                    {:else if selectedTeam?.id === 0}
                        PUB
                    {:else}
                        {data.teams.find((v) => v.id === selectedTeam?.id)?.name || selectedTeam?.name || "Select a team..."}
                    {/if}

                    {#if currentRelation !== undefined}
                        ({#if currentRelation.type === "FIGHT"}
                            {currentRelation.fromPlace === 0 ? "Gewinner" : "Verlierer"} von {currentRelation.fromFight?.blueTeam.name} vs {currentRelation.fromFight?.redTeam.name} ({new Date(
                                currentRelation.fromFight?.start ?? 0
                            ).toLocaleTimeString("de-DE", {
                                timeStyle: "short",
                            })})
                        {:else}
                            {currentRelation.fromPlace + 1}. Platz von {currentRelation.fromGroup?.name}
                        {/if})
                    {/if}

                    <ChevronsUpDown class="ml-2 size-4 shrink-0 opacity-50" />
                </Button>
            {/snippet}
        </PopoverTrigger>
        <PopoverContent class="p-0">
            <Command>
                <CommandInput placeholder="Search Teams..." />
                <CommandList>
                    <CommandEmpty>No team found.</CommandEmpty>
                    <CommandGroup>
                        <CommandItem
                            value={"-1"}
                            onSelect={() => {
                                selectedTeam = {
                                    id: -1,
                                    name: "?",
                                    color: "7",
                                    kuerzel: "?",
                                };
                                onSelect?.(selectedTeam);
                                open = false;
                            }}
                            keywords={["?"]}>???</CommandItem
                        >
                        <CommandItem
                            value={"0"}
                            onSelect={() => {
                                selectedTeam = {
                                    id: 0,
                                    name: "Public",
                                    color: "7",
                                    kuerzel: "PUB",
                                };
                                onSelect?.(selectedTeam);
                                open = false;
                            }}
                            keywords={["PUB", "Public"]}>PUB</CommandItem
                        >
                    </CommandGroup>
                    <CommandGroup heading="Teams">
                        {#each data.teams as team}
                            <CommandItem
                                value={team.name}
                                onSelect={() => {
                                    selectedTeam = team;
                                    onSelect?.(selectedTeam);
                                    open = false;
                                }}
                            >
                                <Check class={cn("mr-2 size-4", team.id !== selectedTeam?.id && "text-transparent")} />
                                {team.name}
                            </CommandItem>
                        {/each}
                    </CommandGroup>
                </CommandList>
            </Command>
        </PopoverContent>
    </Popover>
    <Popover bind:open={relationOpen}>
        <PopoverTrigger>
            {#snippet child({ props })}
                <Tooltip>
                    <TooltipTrigger>
                        <Button {...props} size="icon" variant={currentRelation !== undefined ? "default" : "outline"} disabled={fightId === undefined}>
                            <GitPullRequestArrow />
                        </Button>
                    </TooltipTrigger>
                    <TooltipContent>Kampfverbindung</TooltipContent>
                </Tooltip>
            {/snippet}
        </PopoverTrigger>
        <PopoverContent>
            <Tabs bind:value={fromType}>
                <TabsList>
                    <TabsTrigger value="FIGHT">Kampf</TabsTrigger>
                    <TabsTrigger value="GROUP">Gruppe</TabsTrigger>
                </TabsList>
                <TabsContent value="FIGHT">
                    <Label>Kampf</Label>
                    <Select bind:value={fromFight} type="single" disabled={data.fights.length === 0}>
                        <SelectTrigger>
                            {fromFightData
                                ? `${new Date(fromFightData.start).toLocaleString("de-DE", { timeStyle: "short" })}: ${fromFightData.blueTeam.kuerzel} vs. ${fromFightData.redTeam.kuerzel}`
                                : "Kampf auswählen..."}
                        </SelectTrigger>
                        <SelectContent>
                            {#each data.fights.filter((v) => v.id !== fightId) as fight (fight.id)}
                                <SelectItem value={fight.id.toString()}
                                    >{new Date(fight.start).toLocaleString("de-DE", {
                                        timeStyle: "short",
                                    })}: {fight.blueTeam.kuerzel} vs. {fight.redTeam.kuerzel}</SelectItem
                                >
                            {/each}
                        </SelectContent>
                    </Select>
                    <Label>Team</Label>
                    <Select bind:value={fromPlace} type="single" disabled={data.fights.length === 0}>
                        <SelectTrigger>
                            {fromPlace ? (fromPlace === "0" ? "Gewinner" : "Verlierer") : "Platz auswählen..."}
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value={"0"}>Gewinner</SelectItem>
                            <SelectItem value={"1"}>Verlierer</SelectItem>
                        </SelectContent>
                    </Select>
                </TabsContent>
                <TabsContent value="GROUP">
                    <Label>Gruppe</Label>
                    <Select bind:value={fromGroup} type="single" disabled={data.groups.length === 0}>
                        <SelectTrigger>
                            {fromGroupData ? fromGroupData.name : "Kampf auswählen..."}
                        </SelectTrigger>
                        <SelectContent>
                            {#each data.groups as group (group.id)}
                                <SelectItem value={group.id.toString()}>{group.name}</SelectItem>
                            {/each}
                        </SelectContent>
                    </Select>
                    <Label>Platz</Label>
                    <Select bind:value={fromPlace} type="single" disabled={data.fights.length === 0}>
                        <SelectTrigger>
                            {fromPlace ? `${parseInt(fromPlace) + 1}. Platz` : "Platz auswählen..."}
                        </SelectTrigger>
                        <SelectContent>
                            {#each Array(32) as _, i}
                                <SelectItem value={i.toString()}>{i + 1}. Platz</SelectItem>
                            {/each}
                        </SelectContent>
                    </Select>
                </TabsContent>
            </Tabs>
            <div class="flex justify-end gap-2 mt-2">
                <Button onclick={clearRelation} variant="destructive">Löschen</Button>
                <Button onclick={saveRelation} disabled={!canSave}>Übernehmen</Button>
            </div>
        </PopoverContent>
    </Popover>
</div>
