<template>
    <div class="trainerSelector">
        <div class="header">
            <div>Trainer</div>
        </div>
        <div class="trainers">
            <div class="trainer" v-for="trainer in trainers" :key="trainer.id" v-on:click="clicked(trainer.id)"
                v-bind:class="{ 'selected': selectedTrainers.includes(trainer.id) }">
                {{ trainer.first_name }} {{ trainer.last_name }}
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import type { Trainer } from '@/interfaces/trainer';

export default {
    name: "TrainerSelector",
    emits: ["selectionChanged"],
    props: {
        centers: Array<number>
    },
    async mounted() {
        const filters = this.centers?.map(c => `center=${c}`).join("&");
        const res = await fetch(`${import.meta.env.VITE_BASE_API_URL}/trainer?${filters}`);
        if (res.status === 200) {
            this.trainers = await res.json();
        }
    },
    watch: {
        centers: {
            async handler(centers: number[]) {
                this.selectedTrainers = [];
                const filters = centers?.map(c => `center=${c}`).join("&");
                const res = await fetch(`${import.meta.env.VITE_BASE_API_URL}/trainer?${filters}`);
                if (res.status === 200) {
                    this.trainers = await res.json();
                }
            },
            deep: true
        }
    },
    data() {
        return {
            trainers: [] as Trainer[],
            selectedTrainers: [] as number[]
        };
    },
    methods: {
        clicked(id: number) {
            if (this.selectedTrainers.includes(id)) {
                this.selectedTrainers = this.selectedTrainers.filter(c => c !== id);
            } else {
                this.selectedTrainers.push(id);
            }
            this.$emit("selectionChanged", this.selectedTrainers);
        }
    }
}
</script>

<style scoped>
.trainerSelector {
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
    min-width: fit-content;
    width: 300px;
    /* padding: 5px; */
    font-size: 1em;
}

.header {
    border-bottom: 1px solid #cbd5e1;
    font-weight: 500;
    font-size: 1.1em;
}

.header div {
    padding: 10px;
}

.trainers {
    padding: 10px;
}

.trainer {
    cursor: pointer;
    user-select: none;
}

.trainer.selected {
    font-weight: 500;
    color: #2563eb;
}

.trainer:hover {
    opacity: 0.8;
}
</style>
