<script setup lang="ts">
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import bus, { SYNC } from '@/utils/bus-event'
import { useUserStore } from '@/stores/user'
import transactionService from '@/services/TransactionService'
import exchangeService from '@/services/ExchangeService'
import { confirmation } from '@/utils'
import { money } from '@/utils/format'
import type IAccount from '@/models/IAccount'
import type IRefund from '@/models/IRefund'
import type ITransaction from '@/models/ITransaction'
import TransactionTag from '@/enums/TransactionTag'
import TransactionType from '@/enums/TransactionType'
import ConfirmButton from '@/components/ConfirmButton.vue'

const props = defineProps<{ refund: IRefund; account: IAccount }>()

const userStore = useUserStore()
const { user } = storeToRefs(userStore)

const refunded = ref(false)

const canRefund = computed(() => {
  if (!user.value || !props.account.admin) return true
  return [props.account.admin.email, props.refund.from.email].includes(user.value.email)
})

const fromMe = computed(
  () => !!user.value && !!props.refund.from && props.refund.from.userId === user.value.userId
)
const toMe = computed(
  () => !!user.value && !!props.refund.to && props.refund.to.userId === user.value.userId
)

const refundTo = async (done: () => void) => {
  if (!props.account._id) {
    done()
    return
  }
  const date = new Date()
  const currencies = props.account.currencies.map((c) => c.code)
  const transaction: ITransaction = {
    accountId: props.account._id,
    doctype: 'transaction',
    name: 'Remboursement',
    date,
    tag: TransactionTag.None,
    amount: props.refund.amount || 0,
    payBy: props.refund.from.alias || '',
    payFor: [{ alias: props.refund.to.alias || '', weight: 1 }],
    userIds: props.account.userIds,
    mainCurrency: props.account.mainCurrency,
    currencies: props.account.currencies,
    transactionType: TransactionType.refund,
    exchange: await exchangeService.get(props.account.mainCurrency.code, date, currencies)
  }
  const response = await transactionService.add(props.account._id, transaction)
  if (response.ok) {
    refunded.value = true
    confirmation('Remboursement effectué avec succès')
  }
  bus.emit(SYNC)
  done()
}
</script>

<template>
  <div class="refund-transaction card bg-base-100 shadow my-2">
    <div class="card-body">
      <div v-if="refunded">Somme remboursée...</div>
      <div v-else>
        <span v-if="toMe">
          <span class="font-bold">{{ refund.from.alias }}</span> vous doit
          <span class="numeric">{{ money(refund.amount, account.mainCurrency) }}</span>
        </span>
        <span v-else-if="fromMe">
          Vous devez
          <span class="numeric">{{ money(refund.amount, account.mainCurrency) }}</span> à
          <span class="font-bold">{{ refund.to.alias }}</span>
        </span>
        <span v-else>
          <span class="font-bold">{{ refund.from.alias }}</span> doit
          <span class="numeric">{{ money(refund.amount, account.mainCurrency) }}</span> à
          <span class="font-bold">{{ refund.to.alias }}</span>
        </span>
      </div>
    </div>
    <div v-if="canRefund && !refunded" class="card-actions justify-end p-2 border-t">
      <ConfirmButton class="btn-ghost btn-block" @confirm="refundTo">
        Rembourser
      </ConfirmButton>
    </div>
  </div>
</template>
