<script setup lang="ts">
import { ref, useTemplateRef, type Ref } from 'vue'
import AppForm from '@/components/common/form/AppForm.vue'
import FormControl from '@/components/common/form/FormControl.vue'
import FormGroup from '@/components/common/form/FormGroup.vue'
import ModalWrapper from '@/components/common/ModalWrapper.vue'
import AppButton from '@/components/common/AppButton.vue'
import {
  AccountApiClient,
  AccountValueRecordType,
  type Account,
  type AccountValueRecord,
  type AccountValueRecordCreationPayload,
} from '@/api/account'
import { datetimeLocalToISO, getDatetimeLocalValueForNow } from '@/util/time'
import FileSelector from '@/components/common/FileSelector.vue'
import { useRoute } from 'vue-router'
import { showConfirm } from '@/util/alert'

const route = useRoute()
const props = defineProps<{ account: Account }>()
const modal = useTemplateRef('modal')
const savedValueRecord: Ref<AccountValueRecord | undefined> = ref(undefined)

// Form data:
const timestamp = ref('')
const amount = ref(0)
const attachments: Ref<File[]> = ref([])

async function show(): Promise<AccountValueRecord | undefined> {
  if (!modal.value) return Promise.resolve(undefined)
  timestamp.value = getDatetimeLocalValueForNow()
  if (props.account.currentBalance !== null) {
    amount.value =
      props.account.currentBalance / Math.pow(10, props.account.currency.fractionalDigits)
  } else {
    amount.value = 0
  }
  savedValueRecord.value = undefined
  const result = await modal.value.show()
  if (result === 'saved') {
    return savedValueRecord.value
  }
  return undefined
}

async function addValueRecord() {
  const payload: AccountValueRecordCreationPayload = {
    timestamp: datetimeLocalToISO(timestamp.value),
    type: AccountValueRecordType.BALANCE,
    value: Math.round(amount.value * Math.pow(10, props.account.currency.fractionalDigits)),
  }
  // Check and confirm with the user if the value they entered doesn't match the expected balance of the account.
  if (props.account.currentBalance !== null && payload.value !== props.account.currentBalance) {
    const result = await showConfirm(
      "The balance you entered doesn't match the expected current balance for this account. Proceeding to add this value record will result in an incomplete account history and possible reconciliation errors. Are you sure you want to proceed?",
    )
    if (!result) return
  }
  const api = new AccountApiClient(route)
  try {
    savedValueRecord.value = await api.createValueRecord(
      props.account.id,
      payload,
      attachments.value,
    )
    modal.value?.close('saved')
  } catch (err) {
    console.error(err)
    savedValueRecord.value = undefined
  }
}

defineExpose({ show })
</script>
<template>
  <ModalWrapper ref="modal">
    <template v-slot:default>
      <h2>Add Value Record</h2>
      <p>
        Record the current value of this account, to act as a keyframe from which the account's
        balance can be derived.
      </p>
      <AppForm>
        <FormGroup>
          <FormControl label="Timestamp">
            <input
              type="datetime-local"
              v-model="timestamp"
              step="1"
              style="min-width: 250px"
            />
          </FormControl>
          <FormControl label="Value">
            <input
              type="number"
              v-model="amount"
              step="0.01"
            />
          </FormControl>
        </FormGroup>
        <FormGroup>
          <h5>Attachments</h5>
          <FileSelector v-model:uploaded-files="attachments" />
        </FormGroup>
      </AppForm>
    </template>
    <template v-slot:buttons>
      <AppButton @click="addValueRecord()">Add</AppButton>
      <AppButton
        button-style="secondary"
        @click="modal?.close()"
        >Cancel</AppButton
      >
    </template>
  </ModalWrapper>
</template>
