<template>
    <div class="relative w-full flex flex-col">
        <info :step="1" v-model="step">
            <template #finished>
                <div class="flex items-center justify-between">
                    <div>Erfolgreich eingeloggt als {{ user }}.</div>
                    <v-btn class="self-end" @click.prevent="innerLogout">Abmelden</v-btn>
                </div>
            </template>
            <template #current>
                <div class="space-y-1">
                    <p>Bitte melde dich mit deinen <span class="font-semibold">NaMi Zugangsdaten</span> an. Im Anschluss kannst du deine Grüpplinge aus deiner Gruppierung hier hinzufügen.</p>
                    <p>
                        Falls du noch keine NaMi Zugangsdaten hast, kannst du sie
                        <a href="https://nami.dpsg.de/ica/pages/requestLogin.jsp" target="_BLANK" class="font-semibold">hier</a>
                        beantragen.
                    </p>
                    <p>
                        Bitte achte außerdem darauf, dass du mindestens <span class="font-semibold">Leserechte</span> auf deine Gruppierung hast. Diese kann dir i.d.R. dein
                        <span class="font-semibold">StaVo</span> erteilen.
                    </p>
                </div>
                <div class="flex mt-4 space-x-3">
                    <v-text @keypress.enter="innerLogin" name="nami_mglnr" label="Mitgliedsnummer" id="nami_mglnr" v-model="loginData.mglnr" required></v-text>
                    <v-text @keypress.enter="innerLogin" name="nami_password" label="Passwort" id="nami_password" v-model="loginData.password" type="password" required></v-text>
                    <v-btn class="self-end" @click.prevent="innerLogin">Anmelden</v-btn>
                </div>
            </template>
        </info>

        <info class="mt-4" :step="2" v-model="step">
            <template #finished>
                <div class="flex items-center justify-between">
                    <div>{{ inner.length }} Mitglieder ausgewählt</div>
                    <v-btn class="self-end" @click.prevent="logout">Bearbeiten</v-btn>
                </div>
            </template>
            <template #due>
                <div>Mitglieder auswählen</div>
            </template>
            <template #current>
                <p>
                    Nun kannst du hier nach Mitgliedern suchen. Wähle die Mitglieder aus, die <span class="font-semibold">mit zur Veranstaltung fahren</span>. Dich selbst musst du hier nicht nochmal
                    auswählen.
                </p>
                <div class="flex mt-4 space-x-3">
                    <v-text name="search_firstname" label="Vorname" id="search_firstname" v-model="searchData.vorname" @input="searchForMember"></v-text>
                    <v-text name="search_lastname" label="Nachname" id="search_lastname" v-model="searchData.nachname" @input="searchForMember"></v-text>
                    <v-dropdown name="search_group" label="Stufe" id="search_group" v-model="searchData.untergliederungId" @input="searchForMember" :options="eventMeta.agegroups"></v-dropdown>
                </div>

                <div class="relative min-h-48">
                    <div class="relative" v-for="member in searchResults" :id="member.id" v-if="!searching">
                        {{ member.name }}
                    </div>
                    <div class="absolute flex h-full w-full justify-center items-center opacity-80" v-if="searching">
                        <spinner class="w-20 h-20"></spinner>
                    </div>
                </div>

                <div v-for="(member, index) in inner" class="flex space-x-2 mt-6" :key="index">
                    <label class="w-full border border-solid border-gray-500 focus-within:border-primary rounded-lg relative flex mt-2">
                        <input
                            :id="`${field.key}-${index}`"
                            v-model="member.id"
                            :name="`${field.key}-${index}`"
                            type="text"
                            placeholder=""
                            class="bg-white rounded-lg focus:outline-none text-gray-600 text-left py-1 px-2 @sm:py-2 text-sm @sm:text-base @sm:px-3 w-full"
                        />
                        <field-label name="Mitgliedsnr" :required="true"></field-label>
                    </label>
                    <div class="w-full" v-for="(memberField, memberIndex) in memberFields" :key="field.key">
                        <component
                            :is="resolveComponentName(memberField)"
                            :id="`${field.key}-${memberIndex}`"
                            v-model="member[memberField.key]"
                            :fields="fields"
                            :payload="member"
                            :field="memberField"
                        >
                        </component>
                    </div>
                </div>
            </template>
        </info>

        <button type="button" class="bg-primary hover:bg-secondary px-4 py-2 shadow text-font leading-none rounded-lg mt-5" @click.prevent="addMember">Mitglieder hinzufügen</button>
    </div>
</template>

<script setup>
import {computed, ref} from 'vue';
import FieldLabel from '../FieldLabel.vue';
import VText from './VText.vue';
import VDropdown from './VDropdown.vue';
import useFields from '../../composables/useFieldsWithoutNami.js';
import Info from '../Info.vue';
import VBtn from '../VBtn.vue';
import Spinner from '../Spinner.vue';
import useAdremaLogin from '../../composables/useAdremaLogin.js';
import useEventMeta from '../../composables/useEventMeta.js';

const eventMeta = useEventMeta();
const {login, logout, user, loginData, searchData, searchForMember, resetSearchData, searchResults, searching} = useAdremaLogin();

if (user.value !== null) {
    resetSearchData();
    searchForMember();
}

const {resolveComponentName} = useFields();
const step = computed(() => {
    if (user.value === null) {
        return 1;
    }

    return 2;
});

const emit = defineEmits(['update:modelValue']);
const props = defineProps({
    modelValue: {
        required: true,
        validator: (value) => typeof value === 'object',
    },
    field: {
        required: true,
        validator: (value) => true,
    },
    fields: {
        required: true,
    },
});

const model = ref(null);

const defaultMember = computed(() => {
    var fields = {};
    memberFields.value.forEach((field) => (fields[field.key] = field.default));

    return fields;
});

const memberFields = computed(() => props.fields.filter((field) => field.for_members === true && field.nami_type === null));

function addMember() {
    inner.value.push({id: '', ...defaultMember.value});
}

const inner = computed(
    {
        get: () => props.modelValue,
        set: (v) => emit('update:modelValue', v),
    },
    {deep: true},
);
async function innerLogin() {
    await login();
    resetSearchData();
    searchForMember();
}

async function innerLogout() {
    logout();
    resetSearchData();
    inner.value = [];
}
</script>
