<template>
  <q-card-section class="fit row justify-left content-center items-center q-col-gutter-sm">
    <div class="col-5">
      <div v-if="balance" class="text-h6">
        Aktueller Stand: {{ balance.balance.toFixed(2) }} €
        <q-badge v-if="isLocked" color="negative" align="top"> gesperrt </q-badge>
      </div>
      <q-spinner v-else color="primary" size="3em" />
    </div>
    <div v-if="showSelector" class="col-6">
      <UserSelector v-model="user" />
    </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 { computed, defineComponent, onBeforeMount, PropType } from 'vue';
import UserSelector from 'src/plugins/user/components/UserSelector.vue';
import { useBalanceStore } from '../store';
import { useMainStore } from 'src/stores';

export default defineComponent({
  name: 'BalanceHeader',
  components: { UserSelector },
  props: {
    showSelector: Boolean,
    modelValue: {
      required: true,
      type: Object as PropType<FG.User>,
    },
  },
  emits: { 'update:modelValue': (u: FG.User) => !!u, 'open-history': () => true },
  setup(props, { emit }) {
    const store = useBalanceStore();
    const mainStore = useMainStore();

    onBeforeMount(() => void store.getBalance(mainStore.currentUser));

    const balance = computed(() =>
      store.balances.find((x) => x.userid === props.modelValue.userid)
    );

    const isLocked = computed(
      () =>
        balance.value === undefined ||
        (balance.value.limit !== undefined && balance.value.balance <= balance.value.limit)
    );
    const user = computed({
      get: () => props.modelValue,
      set: (x: FG.User) => {
        void store.getBalance(x);
        emit('update:modelValue', x);
      },
    });

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

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