<template>
  <q-card-section class="fit row justify-left content-center items-center q-col-gutter-sm">
    <div class="text-h6 col-5">
      Aktueller Stand: {{ balance.balance.toFixed(2) }} €
      <q-badge color="negative" align="top" v-if="isLocked"> gesperrt </q-badge>
    </div>
    <div v-if="showSelector" class="col-6">
      <UserSelector :user="user" @update:user="userUpdated" />
    </div>
    <div class="col-1 justify-end">
      <q-btn round flat icon="mdi-format-list-checks" @click="openHistory" />
    </div>
  </q-card-section>
</template>

<script lang="ts">
import { ref, computed, defineComponent, onBeforeMount } from 'vue';
import UserSelector from 'src/plugins/user/components/UserSelector.vue';
import { StateInterfaceBalance, UserBalance } from '../store/balance';
import { useStore, mapGetters } from 'vuex';

export default defineComponent({
  name: 'BalanceHeader',
  components: { UserSelector },
  props: { showSelector: Boolean },
  emits: { 'update:user': (u: FG.User) => !!u, 'open-history': () => true },
  setup(_, { emit }) {
    onBeforeMount(() => void store.dispatch('balance/getBalance'));
    const store = useStore<StateInterfaceBalance>();
    const userGetters = mapGetters('users', ['currentUser']);
    const balanceGetters = mapGetters('balance', ['balances']);
    const user = ref(<FG.User>userGetters.currentUser());
    const balance = computed(() => {
      return (
        (<Map<string, UserBalance>>balanceGetters.balances()).get(user.value.userid) || {
          balance: 0,
          limit: null,
        }
      );
    });

    const isLocked = computed(
      () => balance.value.limit !== null && balance.value.balance >= balance.value.limit
    );

    function userUpdated(selectedUser: FG.User) {
      void store.dispatch('balance/getBalance', selectedUser);
      user.value = selectedUser;
      emit('update:user', selectedUser);
    }

    function openHistory() {
      emit('open-history');
    }

    return { user, balance, isLocked, userUpdated, openHistory };
  },
});
</script>
