<script setup lang="ts">
import { ApiError } from '@/api/base'
import { formatMoney } from '@/api/data'
import { getSelectedProfile } from '@/api/profile'
import {
  TransactionApiClient,
  type RecurringTransactionResponse,
  type TransactionDraftResponse,
} from '@/api/transaction'
import AppButton from '@/components/common/AppButton.vue'
import AppPage from '@/components/common/AppPage.vue'
import CategoryLabel from '@/components/CategoryLabel.vue'
import PropertiesTable from '@/components/PropertiesTable.vue'
import TagLabel from '@/components/TagLabel.vue'
import { showAlert, showConfirm } from '@/util/alert'
import { computed, onMounted, ref, useTemplateRef, type Ref } from 'vue'
import AttachmentRow from '@/components/common/AttachmentRow.vue'
import LineItemCard from '@/components/LineItemCard.vue'
import AppBadge from '@/components/common/AppBadge.vue'
import ButtonBar from '@/components/common/ButtonBar.vue'
import { useRoute, useRouter } from 'vue-router'
import AddRecurringTransactionModal from '@/components/AddRecurringTransactionModal.vue'
import cronstrue from 'cronstrue'

const route = useRoute()
const router = useRouter()
const transactionApi = new TransactionApiClient(getSelectedProfile(route))
const addRecurringTransactionModal = useTemplateRef('addRecurringTransactionModal')

const draft: Ref<TransactionDraftResponse | undefined> = ref()
const recurringTransactions: Ref<RecurringTransactionResponse[]> = ref([])

const pageTitle = computed(() => {
  if (draft.value === undefined) return 'Transaction Draft'
  if (draft.value.templateName !== null && draft.value.templateName.length > 0) {
    return `Transaction Template ${draft.value.id}: "${draft.value.templateName}"`
  }
  return 'Transaction Draft ' + draft.value.id
})

onMounted(async () => {
  const draftId = parseInt(route.params.id as string)
  recurringTransactions.value = []
  try {
    draft.value = await transactionApi.getDraft(draftId)
    recurringTransactions.value = await transactionApi.getRecurringTransactionsForDraft(draftId)
  } catch (err) {
    console.error(err)
    await router.replace('/')
    if (err instanceof ApiError) {
      await showAlert('Failed to fetch transaction: ' + err.message)
    }
  }
})

async function deleteDraft() {
  if (!draft.value) return
  const conf = await showConfirm(
    'Are you sure you want to delete this draft? This will permanently delete all data pertaining to this draft, and it cannot be recovered.',
  )
  if (!conf) return
  try {
    await transactionApi.deleteDraft(draft.value.id)
    await router.replace(`/profiles/${getSelectedProfile(route)}`)
  } catch (err) {
    console.error(err)
  }
}

async function onVendorClicked() {
  if (draft.value && draft.value.vendor) {
    await router.push(`/profiles/${getSelectedProfile(route)}/vendors/${draft.value.vendor.id}`)
  }
}

async function addRecurringTransaction() {
  const result = await addRecurringTransactionModal.value?.show()
  if (result !== undefined && draft.value) {
    recurringTransactions.value = await transactionApi.getRecurringTransactionsForDraft(
      draft.value.id,
    )
  }
}

async function deleteRecurringTransaction(rt: RecurringTransactionResponse) {
  if (!draft.value) return
  await transactionApi.deleteRecurringTransaction(rt.id)
  recurringTransactions.value = await transactionApi.getRecurringTransactionsForDraft(
    draft.value.id,
  )
}

function formatRecurringTransactionScheduleExpr(rt: RecurringTransactionResponse) {
  return cronstrue.toString(rt.scheduleExpr)
}
</script>
<template>
  <AppPage
    :title="pageTitle"
    v-if="draft"
  >
    <!-- Top-row with some badges for amount, vendor, and category. -->
    <div>
      <AppBadge
        size="lg"
        class="font-mono"
        v-if="draft.currency && draft.amount"
      >
        {{ draft.currency.code }} {{ formatMoney(draft.amount, draft.currency) }}
      </AppBadge>
      <AppBadge
        size="md"
        v-if="draft.vendor"
        style="cursor: pointer"
        @click="onVendorClicked()"
      >
        {{ draft.vendor.name }}
      </AppBadge>
      <CategoryLabel
        v-if="draft.category"
        :category="draft.category"
        :clickable="true"
      />
      <AppBadge
        size="sm"
        v-if="draft.internalTransfer"
      >
        <font-awesome-icon icon="fa-rotate"></font-awesome-icon>
        Internal Transfer
      </AppBadge>
    </div>
    <!-- Second row that lists all tags. -->
    <div
      v-if="draft.tags.length > 0"
      class="mt-1"
    >
      <TagLabel
        v-for="t in draft.tags"
        :key="t"
        :tag="t"
      />
    </div>

    <p style="white-space: pre-wrap">{{ draft.description }}</p>

    <div
      v-if="draft.creditedAccount"
      class="my-1"
    >
      <strong class="text-negative">Credited</strong> from
      <RouterLink
        :to="`/profiles/${getSelectedProfile(route)}/accounts/${draft.creditedAccount.id}`"
      >
        {{ draft.creditedAccount.name }} (#{{ draft.creditedAccount.numberSuffix }})
      </RouterLink>
    </div>

    <div
      v-if="draft.debitedAccount"
      class="my-1"
    >
      <strong class="text-positive">Debited</strong> to
      <RouterLink
        :to="`/profiles/${getSelectedProfile(route)}/accounts/${draft.debitedAccount.id}`"
      >
        {{ draft.debitedAccount.name }} (#{{ draft.debitedAccount.numberSuffix }})
      </RouterLink>
    </div>

    <!-- All remaining properties are put in this table. -->
    <PropertiesTable>
      <tr>
        <th>Timestamp</th>
        <td v-if="draft.timestamp !== null">{{ new Date(draft.timestamp).toLocaleString() }}</td>
        <td v-if="draft.timestamp === null"><em>null</em></td>
      </tr>
      <tr>
        <th>Added to Finnow</th>
        <td>{{ new Date(draft.addedAt).toLocaleString() }}</td>
      </tr>
    </PropertiesTable>

    <div v-if="draft.lineItems.length > 0 && draft.currency">
      <h3>Line Items</h3>
      <LineItemCard
        v-for="item of draft.lineItems"
        :key="item.idx"
        :line-item="item"
        :currency="draft.currency"
        :total-count="draft.lineItems.length"
        :editable="false"
      />
    </div>

    <div v-if="draft.attachments.length > 0">
      <h3>Attachments</h3>
      <AttachmentRow
        v-for="a in draft.attachments"
        :attachment="a"
        :key="a.id"
        disabled
      />
    </div>
    <ButtonBar>
      <AppButton
        icon="wrench"
        @click="
          router.push(`/profiles/${getSelectedProfile(route)}/transaction-drafts/${draft?.id}/edit`)
        "
      >
        Edit
      </AppButton>
      <AppButton
        icon="trash"
        @click="deleteDraft()"
        >Delete</AppButton
      >
    </ButtonBar>
    <ButtonBar>
      <AppButton
        icon="repeat"
        @click="addRecurringTransaction()"
      >
        Add Recurring Transaction
      </AppButton>
    </ButtonBar>

    <div v-if="recurringTransactions.length > 0">
      <h3>Recurring Transactions</h3>
      <p>This template will be used to create new drafts using the following schedules:</p>
      <ul>
        <li
          v-for="rt in recurringTransactions"
          :key="rt.id"
        >
          {{ formatRecurringTransactionScheduleExpr(rt) }}
          <AppButton
            icon="trash"
            @click="deleteRecurringTransaction(rt)"
          />
        </li>
      </ul>
    </div>

    <AddRecurringTransactionModal
      ref="addRecurringTransactionModal"
      :draft-id="draft.id"
    />
  </AppPage>
</template>
