<script lang="ts" setup>
import { computed, ref } from 'vue';
import Modal from '../components/Modal.vue';
import { useAccountStore } from '../stores/budget-account';
import Input from '../components/Input.vue';
import Checkbox from '../components/Checkbox.vue';
import { useRouter } from 'vue-router';
import { useBudgetsStore } from '../stores/budget';

const router = useRouter();
const accountStore = useAccountStore();
const CurrentAccount = computed(() => accountStore.CurrentAccount);

const accountName = ref("");
const accountOnBudget = ref(true);
const accountOpen = ref(true);
const error = ref("");

function editAccount(e : {cancel:boolean}) : boolean {
    if(CurrentAccount.value?.ClearedBalance != 0 && !accountOpen.value){
        e.cancel = true;
        error.value = "Cannot close account with balance";
        return false;
    }

    error.value = "";
    accountStore.EditAccount(CurrentAccount.value?.ID ?? "", accountName.value, accountOnBudget.value, accountOpen.value);

    // account closed, move to Budget
    if(!accountOpen.value){
        const currentBudgetID = useBudgetsStore().CurrentBudgetID;
        router.replace('/budget/'+currentBudgetID+'/budgeting');
    }
    return true;
}

function openEditAccount(e : any) {
    accountName.value = CurrentAccount.value?.Name ?? "";
    accountOnBudget.value = CurrentAccount.value?.OnBudget ?? true;
    accountOpen.value = CurrentAccount.value?.IsOpen ?? true;
}
</script>

<template>
  <Modal
    button-text="Edit Account"
    @open="openEditAccount"
    @submit="editAccount"
  >
    <template #placeholder>
      <span class="ml-2">✎</span>
    </template>
    <div class="mt-2 px-7 py-3">
      <Input
        v-model="accountName"
        class="border-2 dark:border-gray-700"
        type="text"
        placeholder="Account name"
        required
      />
    </div>
    <div class="mt-2 px-7 py-3">
      <Checkbox
        v-model="accountOnBudget"
        class="border-2"
        required
      />
      <label>On Budget</label>
    </div>
    <div class="mt-2 px-7 py-3">
      <Checkbox
        v-model="accountOpen"
        class="border-2"
        required
      />
      <label>Open</label>
    </div>
    <div
      v-if="error != ''"
      class="dark:text-red-300 text-red-700"
    >
      {{ error }}
    </div>
  </Modal>
</template>
