<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 } from '../store/balance';
import { Store, useStore } from 'vuex';
import { UserStateInterface } from 'src/plugins/user/store/user';
import { StateInterface } from 'src/store';

interface Props {
  showSelector: boolean;
}

export default defineComponent({
  name: 'BalanceHeader',
  components: { UserSelector },
  props: ['showSelector'],
  setup(props: Props, { root, emit }) {
    onBeforeMount(() => void store.dispatch('balance/getBalance'));
    //const store = <Store<StateInterfaceBalance>>root.$store;
    const store = useStore<StateInterfaceBalance>();
    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
    const user = ref(<FG.User>store.state.user.currentUser);
    const balance = computed(() => {
      const balances = store.state.balance.balances;
      return 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;
      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      emit('update:user', selectedUser);
    }

    function openHistory() {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      emit('open-history');
    }

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